protobuf2/
message_field.rs

1use std::default::Default;
2use std::hash::Hash;
3use std::ops::Deref;
4use std::option;
5
6use crate::Message;
7
8/// Wrapper around `Option<Box<T>>`, convenient newtype.
9///
10/// # Examples
11///
12/// ```no_run
13/// # use protobuf::MessageField;
14/// # use std::ops::Add;
15/// # struct Address {
16/// # }
17/// # struct Customer {
18/// #     address: MessageField<Address>,
19/// # }
20/// # impl Customer {
21/// #     fn new() -> Customer { unimplemented!() }
22/// # }
23/// #
24/// #
25/// # fn make_address() -> Address { unimplemented!() }
26/// let mut customer = Customer::new();
27///
28/// // field of type `SingularPtrField` can be initialized like this
29/// customer.address = MessageField::some(make_address());
30/// // or using `Option` and `Into`
31/// customer.address = Some(make_address()).into();
32/// ```
33#[derive(Clone, Debug, Eq, PartialEq, Hash)]
34pub struct MessageField<T>(pub Option<Box<T>>);
35
36impl<T> MessageField<T> {
37    /// Construct `SingularPtrField` from given object.
38    #[inline]
39    pub fn some(value: T) -> MessageField<T> {
40        MessageField(Some(Box::new(value)))
41    }
42
43    /// Construct an empty `SingularPtrField`.
44    #[inline]
45    pub const fn none() -> MessageField<T> {
46        MessageField(None)
47    }
48
49    /// Construct `SingularPtrField` from optional.
50    #[inline]
51    pub fn from_option(option: Option<T>) -> MessageField<T> {
52        match option {
53            Some(x) => MessageField::some(x),
54            None => MessageField::none(),
55        }
56    }
57
58    /// True iff this object contains data.
59    #[inline]
60    pub fn is_some(&self) -> bool {
61        self.0.is_some()
62    }
63
64    /// True iff this object contains no data.
65    #[inline]
66    pub fn is_none(&self) -> bool {
67        self.0.is_none()
68    }
69
70    /// Convert into `Option<T>`.
71    #[inline]
72    pub fn into_option(self) -> Option<T> {
73        self.0.map(|v| *v)
74    }
75
76    /// View data as reference option.
77    #[inline]
78    pub fn as_ref(&self) -> Option<&T> {
79        self.0.as_ref().map(|v| &**v)
80    }
81
82    /// View data as mutable reference option.
83    #[inline]
84    pub fn as_mut(&mut self) -> Option<&mut T> {
85        self.0.as_mut().map(|v| &mut **v)
86    }
87
88    /// Take the data.
89    /// Panics if empty
90    #[inline]
91    pub fn unwrap(self) -> T {
92        *self.0.unwrap()
93    }
94
95    /// Take the data or return supplied default element if empty.
96    #[inline]
97    pub fn unwrap_or(self, def: T) -> T {
98        self.0.map(|v| *v).unwrap_or(def)
99    }
100
101    /// Take the data or return supplied default element if empty.
102    #[inline]
103    pub fn unwrap_or_else<F>(self, f: F) -> T
104    where
105        F: FnOnce() -> T,
106    {
107        self.0.map(|v| *v).unwrap_or_else(f)
108    }
109
110    /// Apply given function to contained data to construct another `SingularPtrField`.
111    /// Returns empty `SingularPtrField` if this object is empty.
112    #[inline]
113    pub fn map<U, F>(self, f: F) -> MessageField<U>
114    where
115        F: FnOnce(T) -> U,
116    {
117        MessageField::from_option(self.into_option().map(f))
118    }
119
120    /// View data as iterator.
121    #[inline]
122    pub fn iter(&self) -> option::IntoIter<&T> {
123        self.as_ref().into_iter()
124    }
125
126    /// View data as mutable iterator.
127    #[inline]
128    pub fn mut_iter(&mut self) -> option::IntoIter<&mut T> {
129        self.as_mut().into_iter()
130    }
131
132    /// Take data as option, leaving this object empty.
133    #[inline]
134    pub fn take(&mut self) -> Option<T> {
135        self.0.take().map(|v| *v)
136    }
137
138    /// Clear this object, but do not call destructor of underlying data.
139    #[inline]
140    pub fn clear(&mut self) {
141        self.0 = None;
142    }
143}
144
145impl<T: Default> MessageField<T> {
146    /// Get contained data, consume self. Return default value for type if this is empty.
147    #[inline]
148    pub fn unwrap_or_default(self) -> T {
149        *self.0.unwrap_or_default()
150    }
151}
152
153impl<M: Message> MessageField<M> {
154    /// Get a reference to contained value or a default instance.
155    pub fn get_or_default(&self) -> &M {
156        self.as_ref().unwrap_or_else(|| M::default_instance())
157    }
158
159    /// Get a mutable reference to contained value, initialize if not initialized yet.
160    pub fn mut_or_insert_default(&mut self) -> &mut M {
161        if self.is_none() {
162            *self = MessageField::some(Default::default());
163        }
164        self.as_mut().unwrap()
165    }
166}
167
168/// Get a reference to contained value or a default instance if the field is not initialized.
169impl<M: Message> Deref for MessageField<M> {
170    type Target = M;
171
172    fn deref(&self) -> &Self::Target {
173        self.get_or_default()
174    }
175}
176
177/// Get a mutable reference to the message **and** initialize the message if not initialized yet.
178///
179/// Note that part about initializing is not conventional.
180/// Generally `DerefMut` is not supposed to modify the state.
181#[cfg(no)]
182impl<M: Message> DerefMut for MessageField<M> {
183    fn deref_mut(&mut self) -> &mut Self::Target {
184        self.mut_or_insert_default()
185    }
186}
187
188impl<T> Default for MessageField<T> {
189    #[inline]
190    fn default() -> MessageField<T> {
191        MessageField::none()
192    }
193}
194
195/// We don't have `From<Option<Box<T>>> for MessageField<T>` because
196/// it would make type inference worse.
197impl<T> From<Option<T>> for MessageField<T> {
198    fn from(o: Option<T>) -> Self {
199        MessageField::from_option(o)
200    }
201}
202
203impl<'a, T> IntoIterator for &'a MessageField<T> {
204    type Item = &'a T;
205    type IntoIter = option::IntoIter<&'a T>;
206
207    fn into_iter(self) -> option::IntoIter<&'a T> {
208        self.iter()
209    }
210}