1use std::{
2 fmt::Display,
3 ops::{Deref, DerefMut},
4};
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
7
8use crate::wire::{Basic, Type};
9
10pub trait NoneValue {
25 type NoneType;
27
28 fn null_value() -> Self::NoneType;
30}
31
32impl<T> NoneValue for T
33where
34 T: Default,
35{
36 type NoneType = Self;
37
38 fn null_value() -> Self {
39 Default::default()
40 }
41}
42
43#[derive(Clone, Debug, PartialEq, Eq, Hash)]
78pub struct Optional<T>(Option<T>);
79
80impl<T> Basic for Optional<T>
81where
82 T: Basic,
83{
84 const SIGNATURE_CHAR: char = T::SIGNATURE_CHAR;
85 const SIGNATURE_STR: &'static str = T::SIGNATURE_STR;
86}
87
88impl<T> Type for Optional<T>
89where
90 T: Type,
91{
92 const SIGNATURE: &'static crate::Signature = T::SIGNATURE;
93}
94
95impl<T> Serialize for Optional<T>
96where
97 T: Type + NoneValue + Serialize,
98 <T as NoneValue>::NoneType: Serialize,
99{
100 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
101 where
102 S: Serializer,
103 {
104 if T::SIGNATURE == bool::SIGNATURE {
105 panic!("`Optional<bool>` type is not supported");
106 }
107
108 match &self.0 {
109 Some(value) => value.serialize(serializer),
110 None => T::null_value().serialize(serializer),
111 }
112 }
113}
114
115impl<'de, T, E> Deserialize<'de> for Optional<T>
116where
117 T: Type + NoneValue + Deserialize<'de>,
118 <T as NoneValue>::NoneType: Deserialize<'de> + TryInto<T, Error = E> + PartialEq,
119 E: Display,
120{
121 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122 where
123 D: Deserializer<'de>,
124 {
125 if T::SIGNATURE == bool::SIGNATURE {
126 panic!("`Optional<bool>` type is not supported");
127 }
128
129 let value = <<T as NoneValue>::NoneType>::deserialize(deserializer)?;
130 if value == T::null_value() {
131 Ok(Optional(None))
132 } else {
133 Ok(Optional(Some(value.try_into().map_err(de::Error::custom)?)))
134 }
135 }
136}
137
138impl<T> From<Option<T>> for Optional<T> {
139 fn from(value: Option<T>) -> Self {
140 Optional(value)
141 }
142}
143
144impl<T> From<Optional<T>> for Option<T> {
145 fn from(value: Optional<T>) -> Self {
146 value.0
147 }
148}
149
150impl<T> Deref for Optional<T> {
151 type Target = Option<T>;
152
153 fn deref(&self) -> &Self::Target {
154 &self.0
155 }
156}
157
158impl<T> DerefMut for Optional<T> {
159 fn deref_mut(&mut self) -> &mut Self::Target {
160 &mut self.0
161 }
162}
163
164impl<T> Default for Optional<T> {
165 fn default() -> Self {
166 Self(None)
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use std::panic::catch_unwind;
173
174 #[test]
175 fn value_conversion_maps_null_sentinel_to_none() {
176 use crate::wire::{Optional, OwnedVariant, Str, Variant};
177
178 let opt = Optional::<String>::try_from(Variant::from("")).unwrap();
179 assert_eq!(*opt, None);
180 let opt = Optional::<String>::try_from(Variant::from("hello")).unwrap();
181 assert_eq!(*opt, Some("hello".to_string()));
182
183 let opt = Optional::<u32>::try_from(Variant::from(0u32)).unwrap();
184 assert_eq!(*opt, None);
185 let opt = Optional::<u32>::try_from(Variant::from(42u32)).unwrap();
186 assert_eq!(*opt, Some(42));
187
188 let owned = OwnedVariant::try_from(Variant::from(Str::from(""))).unwrap();
189 let opt = Optional::<String>::try_from(owned).unwrap();
190 assert_eq!(*opt, None);
191 }
192
193 #[test]
194 fn bool_in_optional() {
195 use crate::wire::{LE, Optional, to_bytes};
197
198 let ctxt = crate::wire::serialized::Context::new(LE, 0);
199 let res = catch_unwind(|| to_bytes(ctxt, &Optional::<bool>::default()));
200 assert!(res.is_err());
201
202 let data = crate::wire::serialized::Data::new([0, 0, 0, 0].as_slice(), ctxt);
203 let res = catch_unwind(|| data.deserialize::<Optional<bool>>());
204 assert!(res.is_err());
205 }
206}