Debian Codegraph @

src/raw/mod.rs

raw
1 //! An API for interacting with raw BSON bytes.
2 //!
3 //! This module provides two document types, [`RawDocumentBuf`] and [`RawDocument`] (akin to
4 //! [`std::string::String`] and [`str`]), for working with raw BSON documents. These types differ
5 //! from the regular [`crate::Document`] type in that their storage is BSON bytes rather than a
6 //! hash-map like Rust type. In certain circumstances, these types can be leveraged for increased
7 //! performance.
8 //!
9 //! This module also provides a [`RawBson`] type for modeling any borrowed BSON element and a
10 //! [`RawArray`] type for modeling a borrowed slice of a document containing a BSON array element.
11 //!
12 //! A [`RawDocumentBuf`] can be created from a `Vec<u8>` containing raw BSON data. A
13 //! [`RawDocument`] can be created from anything that can be borrowed as a `&[u8]`. Both types
14 //! can access elements via methods similar to those available on the [`crate::Document`] type.
15 //! Note that [`RawDocument::get`] (which [`RawDocument`] calls through to via its
16 //! [`Deref`](std::ops::Deref) implementation) returns a [`Result`], since the bytes contained in
17 //! the document are not fully validated until trying to access the contained data.
18 //!
19 //! ```rust
20 //! use bson::raw::{
21 //! RawBson,
22 //! RawDocumentBuf,
23 //! };
24 //!
25 //! // See http://bsonspec.org/spec.html for details on the binary encoding of BSON.
26 //! let doc = RawDocumentBuf::from_bytes(b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00".to_vec())?;
27 //! let elem = doc.get("hi")?.unwrap();
28 //!
29 //! assert_eq!(
30 //! elem.as_str(),
31 //! Some("y'all"),
32 //! );
33 //! # Ok::<(), bson::raw::Error>(())
34 //! ```
35 //!
36 //! ### [`crate::Document`] interop
37 //!
38 //! A [`RawDocument`] can be created from a [`crate::Document`]. Internally, this
39 //! serializes the [`crate::Document`] to a `Vec<u8>`, and then includes those bytes in the
40 //! [`RawDocument`].
41 //!
42 //! ```rust
43 //! use bson::{
44 //! raw::RawDocumentBuf,
45 //! doc,
46 //! };
47 //!
48 //! let document = doc! {
49 //! "goodbye": {
50 //! "cruel": "world"
51 //! }
52 //! };
53 //!
54 //! let raw = RawDocumentBuf::from_document(&document)?;
55 //! let value = raw
56 //! .get_document("goodbye")?
57 //! .get_str("cruel")?;
58 //!
59 //! assert_eq!(
60 //! value,
61 //! "world",
62 //! );
63 //! # Ok::<(), Box<dyn std::error::Error>>(())
64 //! ```
65 //!
66 //! ### Reference type ([`RawDocument`])
67 //!
68 //! A BSON document can also be accessed with the [`RawDocument`] type, which is an
69 //! unsized type that represents the BSON payload as a `[u8]`. This allows accessing nested
70 //! documents without reallocation. [`RawDocument`] must always be accessed via a pointer type,
71 //! similar to `[T]` and `str`.
72 //!
73 //! The below example constructs a bson document in a stack-based array,
74 //! and extracts a `&str` from it, performing no heap allocation.
75 //! ```rust
76 //! use bson::raw::RawDocument;
77 //!
78 //! let bytes = b"\x13\x00\x00\x00\x02hi\x00\x06\x00\x00\x00y'all\x00\x00";
79 //! assert_eq!(RawDocument::from_bytes(bytes)?.get_str("hi")?, "y'all");
80 //! # Ok::<(), Box<dyn std::error::Error>>(())
81 //! ```
82 //!
83 //! ### Iteration
84 //!
85 //! [`RawDocument`] implements [`IntoIterator`], which can also be
86 //! accessed via [`RawDocumentBuf::iter`].
87
88 //! ```rust
89 //! use bson::{
90 //! raw::{
91 //! RawBsonRef,
92 //! RawDocumentBuf,
93 //! },
94 //! doc,
95 //! };
96 //!
97 //! let original_doc = doc! {
98 //! "crate": "bson",
99 //! "year": "2021",
100 //! };
101 //!
102 //! let doc = RawDocumentBuf::from_document(&original_doc)?;
103 //! let mut doc_iter = doc.iter();
104 //!
105 //! let (key, value): (&str, RawBsonRef) = doc_iter.next().unwrap()?;
106 //! assert_eq!(key, "crate");
107 //! assert_eq!(value.as_str(), Some("bson"));
108 //!
109 //! let (key, value): (&str, RawBsonRef) = doc_iter.next().unwrap()?;
110 //! assert_eq!(key, "year");
111 //! assert_eq!(value.as_str(), Some("2021"));
112 //! # Ok::<(), bson::raw::Error>(())
113 //! ```
114
115 mod array;
116 mod array_buf;
117 mod bson;
118 mod bson_ref;
119 mod document;
120 mod document_buf;
121 mod error;
122 mod iter;
123 pub(crate) mod serde;
124 #[cfg(test)]
125 mod test;
126
127 use std::convert::{TryFrom, TryInto};
128
129 use crate::de::MIN_BSON_STRING_SIZE;
130
131 pub use self::{
132 array::{RawArray, RawArrayIter},
133 array_buf::RawArrayBuf,
134 bson::{RawBson, RawJavaScriptCodeWithScope},
135 bson_ref::{
136 RawBinaryRef,
137 RawBsonRef,
138 RawDbPointerRef,
139 RawJavaScriptCodeWithScopeRef,
140 RawRegexRef,
141 },
142 document::RawDocument,
143 document_buf::RawDocumentBuf,
144 error::{Error, ErrorKind, Result, ValueAccessError, ValueAccessErrorKind, ValueAccessResult},
145 iter::{RawElement, RawIter},
146 };
147
148 /// Special newtype name indicating that the type being (de)serialized is a raw BSON document.
149 pub(crate) const RAW_DOCUMENT_NEWTYPE: &str = "$__private__bson_RawDocument";
150
151 /// Special newtype name indicating that the type being (de)serialized is a raw BSON array.
152 pub(crate) const RAW_ARRAY_NEWTYPE: &str = "$__private__bson_RawArray";
153
154 /// Special newtype name indicating that the type being (de)serialized is a raw BSON value.
155 pub(crate) const RAW_BSON_NEWTYPE: &str = "$__private__bson_RawBson";
156
157 /// Given a u8 slice, return an i32 calculated from the first four bytes in
158 /// little endian order.
159 fn f64_from_slice(val: &[u8]) -> Result<f64> {
160 let arr = val
161 .get(0..8)
162 .and_then(|s| s.try_into().ok())
163 .ok_or_else(|| {
164 Error::new_without_key(ErrorKind::MalformedValue {
165 message: format!("expected 8 bytes to read double, instead got {}", val.len()),
166 })
167 })?;
168 Ok(f64::from_le_bytes(arr))
169 }
170
171 /// Given a u8 slice, return an i32 calculated from the first four bytes in
172 /// little endian order.
173 fn i32_from_slice(val: &[u8]) -> Result<i32> {
174 let arr: [u8; 4] = val
175 .get(0..4)
176 .and_then(|s| s.try_into().ok())
177 .ok_or_else(|| {
178 Error::new_without_key(ErrorKind::MalformedValue {
179 message: format!("expected 4 bytes to read i32, instead got {}", val.len()),
180 })
181 })?;
182 Ok(i32::from_le_bytes(arr))
183 }
184
185 /// Given an u8 slice, return an i64 calculated from the first 8 bytes in
186 /// little endian order.
187 fn i64_from_slice(val: &[u8]) -> Result<i64> {
188 let arr = val
189 .get(0..8)
190 .and_then(|s| s.try_into().ok())
191 .ok_or_else(|| {
192 Error::new_without_key(ErrorKind::MalformedValue {
193 message: format!("expected 8 bytes to read i64, instead got {}", val.len()),
194 })
195 })?;
196 Ok(i64::from_le_bytes(arr))
197 }
198
199 fn read_len(buf: &[u8]) -> Result<usize> {
200 if buf.len() < 4 {
201 return Err(Error::new_without_key(ErrorKind::MalformedValue {
202 message: format!(
203 "expected buffer with string to contain at least 4 bytes, but it only has {}",
204 buf.len()
205 ),
206 }));
207 }
208
209 let length = i32_from_slice(&buf[..4])?;
210 let end = checked_add(usize_try_from_i32(length)?, 4)?;
211
212 if end < MIN_BSON_STRING_SIZE as usize {
213 return Err(Error::new_without_key(ErrorKind::MalformedValue {
214 message: format!(
215 "BSON length encoded string needs to be at least {} bytes, instead got {}",
216 MIN_BSON_STRING_SIZE, end
217 ),
218 }));
219 }
220
221 if buf.len() < end {
222 return Err(Error::new_without_key(ErrorKind::MalformedValue {
223 message: format!(
224 "expected buffer to contain at least {} bytes, but it only has {}",
225 end,
226 buf.len()
227 ),
228 }));
229 }
230
231 if buf[end - 1] != 0 {
232 return Err(Error::new_without_key(ErrorKind::MalformedValue {
233 message: "expected string to be null-terminated".to_string(),
234 }));
235 }
236
237 Ok(length as usize + 4)
238 }
239
240 fn read_lenencode(buf: &[u8]) -> Result<&str> {
241 let end = read_len(buf)?;
242
243 // exclude length-prefix and null byte suffix
244 try_to_str(&buf[4..(end - 1)])
245 }
246
247 fn try_to_str(data: &[u8]) -> Result<&str> {
248 std::str::from_utf8(data).map_err(|e| Error::new_without_key(ErrorKind::Utf8EncodingError(e)))
249 }
250
251 fn usize_try_from_i32(i: i32) -> Result<usize> {
252 usize::try_from(i).map_err(|e| {
253 Error::new_without_key(ErrorKind::MalformedValue {
254 message: e.to_string(),
255 })
256 })
257 }
258
259 fn checked_add(lhs: usize, rhs: usize) -> Result<usize> {
260 lhs.checked_add(rhs).ok_or_else(|| {
261 Error::new_without_key(ErrorKind::MalformedValue {
262 message: "attempted to add with overflow".to_string(),
263 })
264 })
265 }