nson/
message.rs

1use std::result;
2use std::fmt;
3use std::io::{Write, Read, Cursor};
4use std::iter::{FromIterator, Extend};
5use std::cmp::Ordering;
6use std::ops::RangeFull;
7
8use indexmap::IndexMap;
9
10use crate::value::{Value, TimeStamp, Binary};
11use crate::array::Array;
12use crate::message_id::MessageId;
13use crate::encode::{encode_message, encode_value, write_u32, write_cstring, EncodeResult};
14use crate::decode::{decode_message, DecodeResult};
15
16pub use indexmap::map::{IntoIter, Iter, IterMut, Entry, Keys, Values, ValuesMut, Drain};
17
18#[derive(PartialEq, Debug)]
19pub enum Error {
20    NotPresent,
21    UnexpectedType,
22}
23
24pub type Result<T> = result::Result<T, Error>;
25
26#[derive(Clone, PartialEq, Eq, Default)]
27pub struct Message {
28    inner: IndexMap<String, Value>
29}
30
31impl Message {
32    pub fn new() -> Message {
33        Message {
34            inner: IndexMap::new()
35        }
36    }
37
38    pub fn with_capacity(n: usize) -> Message {
39        Message {
40            inner: IndexMap::with_capacity(n)
41        }
42    }
43
44    pub fn capacity(&self) -> usize {
45        self.inner.capacity()
46    }
47
48    pub fn clear(&mut self) {
49        self.inner.clear();
50    }
51
52    pub fn get(&self, key: &str) -> Option<&Value> {
53        self.inner.get(key)
54    }
55
56    pub fn get_full(&self, key: &str) -> Option<(usize, &String, &Value)> {
57        self.inner.get_full(key)
58    }
59
60    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
61        self.inner.get_mut(key)
62    }
63
64    pub fn get_mut_full(&mut self, key: &str) -> Option<(usize, &String, &mut Value)> {
65        self.inner.get_full_mut(key)
66    }
67
68    pub fn contains_key(&self, key: &str) -> bool {
69        self.inner.contains_key(key)
70    }
71
72    pub fn len(&self) -> usize {
73        self.inner.len()
74    }
75
76    pub fn is_empty(&self) -> bool {
77        self.inner.is_empty()
78    }
79
80    pub fn entry(&mut self, key: impl Into<String>) -> Entry<String, Value> {
81        self.inner.entry(key.into())
82    }
83
84    pub fn insert_value(&mut self, key: impl Into<String>, value: Value) -> Option<Value> {
85        self.inner.insert(key.into(), value)
86    }
87
88    pub fn insert_value_full(&mut self, key: impl Into<String>, value: impl Into<Value>) -> (usize, Option<Value>) {
89        self.inner.insert_full(key.into(), value.into())
90    }
91
92    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<Value>) -> Option<Value> {
93        self.insert_value(key.into(), value.into())
94    }
95
96    pub fn insert_full(&mut self, key: impl Into<String>, value: impl Into<Value>) -> (usize, Option<Value>) {
97        self.insert_value_full(key.into(), value.into())
98    }
99
100    pub fn remove(&mut self, key: &str) -> Option<Value> {
101        self.inner.swap_remove(key)
102    }
103
104    pub fn swap_remove(&mut self, key: &str) -> Option<Value> {
105        self.inner.swap_remove(key)
106    }
107
108    pub fn swap_remove_full(&mut self, key: &str) -> Option<(usize, String, Value)> {
109        self.inner.swap_remove_full(key)
110    }
111
112    pub fn shift_remove(&mut self, key: &str) -> Option<Value> {
113        self.inner.shift_remove(key)
114    }
115
116    pub fn shift_remove_full(&mut self, key: &str) -> Option<(usize, String, Value)> {
117        self.inner.shift_remove_full(key)
118    }
119
120    pub fn pop(&mut self) -> Option<(String, Value)> {
121        self.inner.pop()
122    }
123
124    pub fn retain<F>(&mut self, keep: F)
125        where F: FnMut(&String, &mut Value) -> bool
126    {
127        self.inner.retain(keep)
128    }
129
130    pub fn sort_keys(&mut self) {
131        self.inner.sort_keys()
132    }
133
134    pub fn sort_by<F>(&mut self, compare: F)
135        where F: FnMut(&String, &Value, &String, &Value) -> Ordering
136    {
137        self.inner.sort_by(compare)
138    }
139
140    pub fn sorted_by<F>(self, compare: F) -> IntoIter<String, Value>
141        where F: FnMut(&String, &Value, &String, &Value) -> Ordering
142    {
143        self.inner.sorted_by(compare)
144    }
145
146    pub fn drain(&mut self, range: RangeFull) -> Drain<String, Value> {
147        self.inner.drain(range)
148    }
149
150    pub fn iter(&self) -> Iter<'_, String, Value> {
151        self.into_iter()
152    }
153
154    pub fn iter_mut(&mut self) -> IterMut<'_, String, Value> {
155        self.into_iter()
156    }
157
158    pub fn keys(&self) -> Keys<String, Value> {
159        self.inner.keys()
160    }
161
162    pub fn values(&self) -> Values<String, Value> {
163        self.inner.values()
164    }
165
166    pub fn value_mut(&mut self) -> ValuesMut<String, Value> {
167        self.inner.values_mut()
168    }
169
170    pub fn get_f32(&self, key: &str) -> Result<f32> {
171        match self.get(key) {
172            Some(&Value::F32(v)) => Ok(v),
173            Some(_) => Err(Error::UnexpectedType),
174            None => Err(Error::NotPresent),
175        }
176    }
177
178    pub fn get_f64(&self, key: &str) -> Result<f64> {
179        match self.get(key) {
180            Some(&Value::F64(v)) => Ok(v),
181            Some(_) => Err(Error::UnexpectedType),
182            None => Err(Error::NotPresent),
183        }
184    }
185
186    pub fn get_i32(&self, key: &str) -> Result<i32> {
187        match self.get(key) {
188            Some(&Value::I32(v)) => Ok(v),
189            Some(_) => Err(Error::UnexpectedType),
190            None => Err(Error::NotPresent),
191        }
192    }
193
194    pub fn get_u32(&self, key: &str) -> Result<u32> {
195        match self.get(key) {
196            Some(&Value::U32(v)) => Ok(v),
197            Some(_) => Err(Error::UnexpectedType),
198            None => Err(Error::NotPresent),
199        }
200    }
201
202    pub fn get_i64(&self, key: &str) -> Result<i64> {
203        match self.get(key) {
204            Some(&Value::I64(v)) => Ok(v),
205            Some(_) => Err(Error::UnexpectedType),
206            None => Err(Error::NotPresent),
207        }
208    }
209
210    pub fn get_u64(&self, key: &str) -> Result<u64> {
211        match self.get(key) {
212            Some(&Value::U64(v)) => Ok(v),
213            Some(_) => Err(Error::UnexpectedType),
214            None => Err(Error::NotPresent),
215        }
216    }
217
218    pub fn get_str(&self, key: &str) -> Result<&str> {
219        match self.get(key) {
220            Some(&Value::String(ref v)) => Ok(v),
221            Some(_) => Err(Error::UnexpectedType),
222            None => Err(Error::NotPresent),
223        }
224    }
225
226    pub fn get_array(&self, key: &str) -> Result<&Array> {
227        match self.get(key) {
228            Some(&Value::Array(ref v)) => Ok(v),
229            Some(_) => Err(Error::UnexpectedType),
230            None => Err(Error::NotPresent),
231        }
232    }
233
234    pub fn get_message(&self, key: &str) -> Result<&Message> {
235        match self.get(key) {
236            Some(&Value::Message(ref v)) => Ok(v),
237            Some(_) => Err(Error::UnexpectedType),
238            None => Err(Error::NotPresent),
239        }
240    }
241
242    pub fn get_bool(&self, key: &str) -> Result<bool> {
243        match self.get(key) {
244            Some(&Value::Bool(v)) => Ok(v),
245            Some(_) => Err(Error::UnexpectedType),
246            None => Err(Error::NotPresent),
247        }
248    }
249
250    pub fn is_null(&self, key: &str) -> bool {
251        self.get(key) == Some(&Value::Null)
252    }
253
254    pub fn get_binary(&self, key: &str) -> Result<&Binary> {
255        match self.get(key) {
256            Some(&Value::Binary(ref v)) => Ok(v),
257            Some(_) => Err(Error::UnexpectedType),
258            None => Err(Error::NotPresent),
259        }
260    }
261
262    pub fn get_message_id(&self, key: &str) -> Result<&MessageId> {
263        match self.get(key) {
264            Some(&Value::MessageId(ref v)) => Ok(v),
265            Some(_) => Err(Error::UnexpectedType),
266            None => Err(Error::NotPresent),
267        }
268    }
269
270    pub fn get_timestamp(&self, key: &str) -> Result<&TimeStamp> {
271        match self.get(key) {
272            Some(&Value::TimeStamp(ref v)) => Ok(v),
273            Some(_) => Err(Error::UnexpectedType),
274            None => Err(Error::NotPresent),
275        }
276    }
277
278    pub fn encode(&self, writer: &mut impl Write) -> EncodeResult<()> {
279        encode_message(writer, self)
280    }
281
282    pub fn decode(reader: &mut impl Read) -> DecodeResult<Message> {
283        decode_message(reader)
284    }
285
286    pub fn to_bytes(&self) -> EncodeResult<Vec<u8>> {
287        let len = self.bytes_size();
288
289        let mut buf = Vec::with_capacity(len);
290        write_u32(&mut buf, len as u32)?;
291
292        for (key, val) in self {
293            buf.write_all(&[val.element_type() as u8])?;
294            write_cstring(&mut buf, key)?;
295
296            encode_value(&mut buf, val)?;
297        }
298
299        buf.write_all(&[0])?;
300
301        Ok(buf)
302    }
303
304    pub fn from_bytes(slice: &[u8]) -> DecodeResult<Message> {
305        let mut reader = Cursor::new(slice);
306        decode_message(&mut reader)
307    }
308
309    pub fn extend<I: IntoIterator<Item=(String, Value)>>(&mut self, iter: I) {
310        self.inner.extend(iter);
311    }
312
313    pub fn get_index_of(&self, key: &str) -> Option<usize> {
314        self.inner.get_index_of(key)
315    }
316
317    pub fn get_index(&self, index: usize) -> Option<(&String, &Value)> {
318        self.inner.get_index(index)
319    }
320
321    pub fn get_index_mut(&mut self, index: usize) -> Option<(&mut String, &mut Value)> {
322        self.inner.get_index_mut(index)
323    }
324
325    pub fn swap_remove_index(&mut self, index: usize) -> Option<(String, Value)> {
326        self.inner.swap_remove_index(index)
327    }
328
329    pub fn shift_remove_index(&mut self, index: usize) -> Option<(String, Value)> {
330        self.inner.shift_remove_index(index)
331    }
332
333    pub fn bytes_size(&self) -> usize {
334        4 + self.iter().map(|(k, v)| { 1 + k.len() + 1 + v.bytes_size() }).sum::<usize>() + 1
335    }
336}
337
338impl fmt::Debug for Message {
339    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
340        write!(fmt, "Message{:?}", self.inner)
341    }
342}
343
344impl fmt::Display for Message {
345    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
346        write!(fmt, "Message{{")?;
347
348        let mut first = true;
349        for (k, v) in self.iter() {
350            if first {
351                first = false;
352            } else {
353                write!(fmt, ", ")?;
354            }
355
356            write!(fmt, "{}: {}", k, v)?;
357        }
358
359        write!(fmt, "}}")?;
360
361        Ok(())
362    }
363}
364
365impl IntoIterator for Message {
366    type Item = (String, Value);
367    type IntoIter = IntoIter<String, Value>;
368
369    fn into_iter(self) -> Self::IntoIter {
370        self.inner.into_iter()
371    }
372}
373
374impl<'a> IntoIterator for &'a Message {
375    type Item = (&'a String, &'a Value);
376    type IntoIter = Iter<'a, String, Value>;
377
378    fn into_iter(self) -> Self::IntoIter {
379        self.inner.iter()
380    }
381}
382
383impl<'a> IntoIterator for &'a mut Message {
384    type Item = (&'a String, &'a mut Value);
385    type IntoIter = IterMut<'a, String, Value>;
386
387    fn into_iter(self) -> Self::IntoIter {
388        self.inner.iter_mut()
389    }
390}
391
392impl FromIterator<(String, Value)> for Message {
393    fn from_iter<I: IntoIterator<Item=(String, Value)>>(iter: I) -> Self {
394        let mut msg = Message::with_capacity(8);
395
396        for (k, v) in iter {
397            msg.insert(k, v);
398        }
399
400        msg
401    }
402}
403
404impl From<IndexMap<String, Value>> for Message {
405    fn from(map: IndexMap<String, Value>) -> Message {
406        Message { inner: map }
407    }
408}
409
410#[cfg(test)]
411mod test {
412    use crate::Message;
413    use crate::msg;
414
415    #[test]
416    fn to_vec() {
417        let msg = msg!{"aa": "bb"};
418
419        let vec = msg.to_bytes().unwrap();
420
421        let msg2 = Message::from_bytes(&vec).unwrap();
422
423        assert_eq!(msg, msg2);
424    }
425
426    #[test]
427    fn extend() {
428        let msg1 = msg!{"aa": "bb"};
429
430        let mut msg2 = msg!{"cc": "dd"};
431        msg2.extend(msg1);
432
433        let msg3 = msg!{"aa": "bb", "cc": "dd"};
434
435        assert_eq!(msg2, msg3);
436    }
437}