protobuf/
message_field.rs

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