Skip to content

Commit 50bab4f

Browse files
authored
chore: Split prost-types lib.rs into separate modules. (#1007)
* prost-types: Place type implementations in modules. * prost-types: Extract modules to separate files. * prost-types: Move tests to the respective modules.
1 parent 0bd9482 commit 50bab4f

5 files changed

Lines changed: 899 additions & 865 deletions

File tree

prost-types/src/any.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
use super::*;
2+
3+
impl Any {
4+
/// Serialize the given message type `M` as [`Any`].
5+
pub fn from_msg<M>(msg: &M) -> Result<Self, EncodeError>
6+
where
7+
M: Name,
8+
{
9+
let type_url = M::type_url();
10+
let mut value = Vec::new();
11+
Message::encode(msg, &mut value)?;
12+
Ok(Any { type_url, value })
13+
}
14+
15+
/// Decode the given message type `M` from [`Any`], validating that it has
16+
/// the expected type URL.
17+
pub fn to_msg<M>(&self) -> Result<M, DecodeError>
18+
where
19+
M: Default + Name + Sized,
20+
{
21+
let expected_type_url = M::type_url();
22+
23+
match (
24+
TypeUrl::new(&expected_type_url),
25+
TypeUrl::new(&self.type_url),
26+
) {
27+
(Some(expected), Some(actual)) => {
28+
if expected == actual {
29+
return Ok(M::decode(self.value.as_slice())?);
30+
}
31+
}
32+
_ => (),
33+
}
34+
35+
let mut err = DecodeError::new(format!(
36+
"expected type URL: \"{}\" (got: \"{}\")",
37+
expected_type_url, &self.type_url
38+
));
39+
err.push("unexpected type URL", "type_url");
40+
Err(err)
41+
}
42+
}
43+
44+
impl Name for Any {
45+
const PACKAGE: &'static str = PACKAGE;
46+
const NAME: &'static str = "Any";
47+
48+
fn type_url() -> String {
49+
type_url_for::<Self>()
50+
}
51+
}
52+
53+
#[cfg(test)]
54+
mod tests {
55+
use super::*;
56+
57+
#[test]
58+
fn check_any_serialization() {
59+
let message = Timestamp::date(2000, 1, 1).unwrap();
60+
let any = Any::from_msg(&message).unwrap();
61+
assert_eq!(
62+
&any.type_url,
63+
"type.googleapis.com/google.protobuf.Timestamp"
64+
);
65+
66+
let message2 = any.to_msg::<Timestamp>().unwrap();
67+
assert_eq!(message, message2);
68+
69+
// Wrong type URL
70+
assert!(any.to_msg::<Duration>().is_err());
71+
}
72+
}

0 commit comments

Comments
 (0)