Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Split prost-types lib.rs into separate modules. #1007

Merged
merged 3 commits into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions prost-types/src/any.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use super::*;

impl Any {
/// Serialize the given message type `M` as [`Any`].
pub fn from_msg<M>(msg: &M) -> Result<Self, EncodeError>
where
M: Name,
{
let type_url = M::type_url();
let mut value = Vec::new();
Message::encode(msg, &mut value)?;
Ok(Any { type_url, value })
}

/// Decode the given message type `M` from [`Any`], validating that it has
/// the expected type URL.
pub fn to_msg<M>(&self) -> Result<M, DecodeError>
where
M: Default + Name + Sized,
{
let expected_type_url = M::type_url();

match (
TypeUrl::new(&expected_type_url),
TypeUrl::new(&self.type_url),
) {
(Some(expected), Some(actual)) => {
if expected == actual {
return Ok(M::decode(self.value.as_slice())?);
}
}
_ => (),
}

let mut err = DecodeError::new(format!(
"expected type URL: \"{}\" (got: \"{}\")",
expected_type_url, &self.type_url
));
err.push("unexpected type URL", "type_url");
Err(err)
}
}

impl Name for Any {
const PACKAGE: &'static str = PACKAGE;
const NAME: &'static str = "Any";

fn type_url() -> String {
type_url_for::<Self>()
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn check_any_serialization() {
let message = Timestamp::date(2000, 1, 1).unwrap();
let any = Any::from_msg(&message).unwrap();
assert_eq!(
&any.type_url,
"type.googleapis.com/google.protobuf.Timestamp"
);

let message2 = any.to_msg::<Timestamp>().unwrap();
assert_eq!(message, message2);

// Wrong type URL
assert!(any.to_msg::<Duration>().is_err());
}
}
Loading
Loading