proto_types/
empty.rs

1use prost::Name;
2
3use crate::{constants::PACKAGE_PREFIX, type_url_for, Empty};
4
5impl From<()> for Empty {
6  fn from(_: ()) -> Self {
7    Empty {}
8  }
9}
10
11impl Name for Empty {
12  const PACKAGE: &'static str = PACKAGE_PREFIX;
13
14  const NAME: &'static str = "Empty";
15
16  fn type_url() -> String {
17    type_url_for::<Self>()
18  }
19}
20
21#[cfg(feature = "serde")]
22mod serde {
23  use std::fmt;
24
25  use serde::{ser::SerializeStruct, Deserialize, Serialize};
26
27  use crate::Empty;
28  impl Serialize for Empty {
29    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
30    where
31      S: serde::Serializer,
32    {
33      // Serialize as an empty struct (which maps to an empty JSON object `{}`)
34      serializer.serialize_struct("Empty", 0)?.end()
35    }
36  }
37
38  impl<'de> Deserialize<'de> for Empty {
39    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
40    where
41      D: serde::Deserializer<'de>,
42    {
43      struct EmptyVisitor;
44
45      impl<'de> serde::de::Visitor<'de> for EmptyVisitor {
46        type Value = Empty;
47
48        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
49          formatter.write_str("an empty object `{}`")
50        }
51
52        fn visit_map<A>(self, mut _map: A) -> Result<Self::Value, A::Error>
53        where
54          A: serde::de::MapAccess<'de>,
55        {
56          // Ensure there are no unexpected fields in the map
57          if let Some(key) = _map.next_key::<String>()? {
58            return Err(serde::de::Error::custom(format!(
59              "Unexpected field in Empty message: {}",
60              key
61            )));
62          }
63          Ok(Empty {})
64        }
65
66        // Also allow deserializing from unit (`()`) if needed, though `{}` is standard for JSON
67        fn visit_unit<E>(self) -> Result<Self::Value, E>
68        where
69          E: serde::de::Error,
70        {
71          Ok(Empty {})
72        }
73      }
74
75      deserializer.deserialize_unit_struct("Empty", EmptyVisitor) // Expect a struct with no fields
76    }
77  }
78}