Skip to main content

proto_types/
any.rs

1// Parts of the code in this file have been extracted from (prost-types)[https://github.com/tokio-rs/prost/blob/master/prost-types/src/any.rs], licensed under the Apache-2.0 license.
2use super::*;
3use crate::constants::PACKAGE_PREFIX;
4
5impl Any {
6	/// Serialize the given message type `M` as [`Any`].
7	pub fn from_msg<M>(msg: &M) -> Result<Self, EncodeError>
8	where
9		M: Name,
10	{
11		let type_url = M::type_url();
12
13		let mut value = Vec::new();
14
15		Message::encode(msg, &mut value)?;
16
17		Ok(Self { type_url, value })
18	}
19
20	/// Decode the given message type `M` from [`Any`], validating that it has
21	/// the expected type URL.
22	pub fn to_msg<M>(&self) -> Result<M, DecodeError>
23	where
24		M: Default + Name + Sized,
25	{
26		let expected_type_url = M::type_url();
27
28		if let (Some(expected), Some(actual)) = (
29			TypeUrl::new(&expected_type_url),
30			TypeUrl::new(&self.type_url),
31		) && expected == actual
32		{
33			return M::decode(self.value.as_slice());
34		}
35
36		#[allow(deprecated)]
37		let mut err = DecodeError::new(format!(
38			"expected type URL: \"{}\" (got: \"{}\")",
39			expected_type_url, &self.type_url
40		));
41
42		err.push("unexpected type URL", "type_url");
43
44		Err(err)
45	}
46}
47
48impl Name for Any {
49	const PACKAGE: &'static str = PACKAGE_PREFIX;
50
51	const NAME: &'static str = "Any";
52
53	fn type_url() -> String {
54		type_url_for::<Self>()
55	}
56}