proto_types/
any.rs

1// From (prost-types)[https://github.com/tokio-rs/prost/blob/master/prost-types/src/any.rs]
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(Any { 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    )
32      && expected == actual {
33        return M::decode(self.value.as_slice());
34      }
35
36    let mut err = DecodeError::new(format!(
37      "expected type URL: \"{}\" (got: \"{}\")",
38      expected_type_url, &self.type_url
39    ));
40
41    err.push("unexpected type URL", "type_url");
42
43    Err(err)
44  }
45}
46
47impl Name for Any {
48  const PACKAGE: &'static str = PACKAGE_PREFIX;
49
50  const NAME: &'static str = "Any";
51
52  fn type_url() -> String {
53    type_url_for::<Self>()
54  }
55}