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