Debian Codegraph @

src/lib.rs

raw
1 // The MIT License (MIT)
2
3 // Copyright (c) 2015 Y. T. Chung <[email protected]>
4
5 // Permission is hereby granted, free of charge, to any person obtaining a copy of
6 // this software and associated documentation files (the "Software"), to deal in
7 // the Software without restriction, including without limitation the rights to
8 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 // the Software, and to permit persons to whom the Software is furnished to do so,
10 // subject to the following conditions:
11
12 // The above copyright notice and this permission notice shall be included in all
13 // copies or substantial portions of the Software.
14
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 //! BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents.
23 //! Like JSON, BSON supports the embedding of documents and arrays within other documents
24 //! and arrays. BSON also contains extensions that allow representation of data types that
25 //! are not part of the JSON spec. For example, BSON has a datetime type and a binary data type.
26 //!
27 //! ```text
28 //! // JSON equivalent
29 //! {"hello": "world"}
30 //!
31 //! // BSON encoding
32 //! \x16\x00\x00\x00 // total document size
33 //! \x02 // 0x02 = type String
34 //! hello\x00 // field name
35 //! \x06\x00\x00\x00world\x00 // field value
36 //! \x00 // 0x00 = type EOO ('end of object')
37 //! ```
38 //!
39 //! BSON is the primary data representation for [MongoDB](https://www.mongodb.com/), and this crate is used in the
40 //! [`mongodb`](https://docs.rs/mongodb/latest/mongodb/) driver crate in its API and implementation.
41 //!
42 //! For more information about BSON itself, see [bsonspec.org](http://bsonspec.org).
43 //!
44 //! ## Installation
45 //! ### Requirements
46 //! - Rust 1.64+
47 //!
48 //! ### Importing
49 //! This crate is available on [crates.io](https://crates.io/crates/bson). To use it in your application,
50 //! simply add it to your project's `Cargo.toml`.
51 //!
52 //! ```toml
53 //! [dependencies]
54 //! bson = "2.10.0"
55 //! ```
56 //!
57 //! Note that if you are using `bson` through the `mongodb` crate, you do not need to specify it in
58 //! your `Cargo.toml`, since the `mongodb` crate already re-exports it.
59 //!
60 //! #### Feature Flags
61 //!
62 //! | Feature | Description | Default |
63 //! |:-------------|:-----------------------------------------------------------------------------------------------------|:--------|
64 //! | `chrono-0_4` | Enable support for v0.4 of the [`chrono`](https://docs.rs/chrono/0.4) crate in the public API. | no |
65 //! | `uuid-0_8` | Enable support for v0.8 of the [`uuid`](https://docs.rs/uuid/0.8) crate in the public API. | no |
66 //! | `uuid-1` | Enable support for v1.x of the [`uuid`](https://docs.rs/uuid/1.x) crate in the public API. | no |
67 //! | `time-0_3` | Enable support for v0.3 of the [`time`](https://docs.rs/time/0.3) crate in the public API. | no |
68 //! | `serde_with` | Enable [`serde_with`](https://docs.rs/serde_with/latest) integrations for [`DateTime`] and [`Uuid`]. | no |
69 //!
70 //! ## BSON values
71 //!
72 //! Many different types can be represented as a BSON value, including 32-bit and 64-bit signed
73 //! integers, 64 bit floating point numbers, strings, datetimes, embedded documents, and more. To
74 //! see a full list of possible BSON values, see the [BSON specification](http://bsonspec.org/spec.html). The various
75 //! possible BSON values are modeled in this crate by the [`Bson`](enum.Bson.html) enum.
76 //!
77 //! ### Creating [`Bson`](enum.Bson.html) instances
78 //!
79 //! [`Bson`](enum.Bson.html) values can be instantiated directly or via the
80 //! [`bson!`](macro.bson.html) macro:
81 //!
82 //! ```rust
83 //! use bson::{bson, Bson};
84 //!
85 //! let string = Bson::String("hello world".to_string());
86 //! let int = Bson::Int32(5);
87 //! let array = Bson::Array(vec![Bson::Int32(5), Bson::Boolean(false)]);
88 //!
89 //! let string: Bson = "hello world".into();
90 //! let int: Bson = 5i32.into();
91 //!
92 //! let string = bson!("hello world");
93 //! let int = bson!(5);
94 //! let array = bson!([5, false]);
95 //! ```
96 //! [`bson!`](macro.bson.html) has supports both array and object literals, and it automatically
97 //! converts any values specified to [`Bson`](enum.Bson.html), provided they are `Into<Bson>`.
98 //!
99 //! ### [`Bson`](enum.Bson.html) value unwrapping
100 //!
101 //! [`Bson`](enum.Bson.html) has a number of helper methods for accessing the underlying native Rust
102 //! types. These helpers can be useful in circumstances in which the specific type of a BSON value
103 //! is known ahead of time.
104 //!
105 //! e.g.:
106 //! ```rust
107 //! use bson::{bson, Bson};
108 //!
109 //! let value = Bson::Int32(5);
110 //! let int = value.as_i32(); // Some(5)
111 //! let bool = value.as_bool(); // None
112 //!
113 //! let value = bson!([true]);
114 //! let array = value.as_array(); // Some(&Vec<Bson>)
115 //! ```
116 //!
117 //! ## BSON documents
118 //!
119 //! BSON documents are ordered maps of UTF-8 encoded strings to BSON values. They are logically
120 //! similar to JSON objects in that they can contain subdocuments, arrays, and values of several
121 //! different types. This crate models BSON documents via the
122 //! [`Document`](document/struct.Document.html) struct.
123 //!
124 //! ### Creating [`Document`](document/struct.Document.html)s
125 //!
126 //! [`Document`](document/struct.Document.html)s can be created directly either from a byte
127 //! reader containing BSON data or via the `doc!` macro:
128 //! ```rust
129 //! use bson::{doc, Document};
130 //! use std::io::Read;
131 //!
132 //! let mut bytes = hex::decode("0C0000001069000100000000").unwrap();
133 //! let doc = Document::from_reader(&mut bytes.as_slice()).unwrap(); // { "i": 1 }
134 //!
135 //! let doc = doc! {
136 //! "hello": "world",
137 //! "int": 5,
138 //! "subdoc": { "cat": true },
139 //! };
140 //! ```
141 //! [`doc!`](macro.doc.html) works similarly to [`bson!`](macro.bson.html), except that it always
142 //! returns a [`Document`](document/struct.Document.html) rather than a [`Bson`](enum.Bson.html).
143 //!
144 //! ### [`Document`](document/struct.Document.html) member access
145 //!
146 //! [`Document`](document/struct.Document.html) has a number of methods on it to facilitate member
147 //! access:
148 //!
149 //! ```rust
150 //! use bson::doc;
151 //!
152 //! let doc = doc! {
153 //! "string": "string",
154 //! "bool": true,
155 //! "i32": 5,
156 //! "doc": { "x": true },
157 //! };
158 //!
159 //! // attempt get values as untyped Bson
160 //! let none = doc.get("asdfadsf"); // None
161 //! let value = doc.get("string"); // Some(&Bson::String("string"))
162 //!
163 //! // attempt to get values with explicit typing
164 //! let string = doc.get_str("string"); // Ok("string")
165 //! let subdoc = doc.get_document("doc"); // Some(Document({ "x": true }))
166 //! let error = doc.get_i64("i32"); // Err(...)
167 //! ```
168 //!
169 //! ## Modeling BSON with strongly typed data structures
170 //!
171 //! While it is possible to work with documents and BSON values directly, it will often introduce a
172 //! lot of boilerplate for verifying the necessary keys are present and their values are the correct
173 //! types. [`serde`](https://serde.rs/) provides a powerful way of mapping BSON data into Rust data structures largely
174 //! automatically, removing the need for all that boilerplate.
175 //!
176 //! e.g.:
177 //! ```rust
178 //! use serde::{Deserialize, Serialize};
179 //! use bson::{bson, Bson};
180 //!
181 //! #[derive(Serialize, Deserialize)]
182 //! struct Person {
183 //! name: String,
184 //! age: i32,
185 //! phones: Vec<String>,
186 //! }
187 //!
188 //! // Some BSON input data as a [`Bson`].
189 //! let bson_data: Bson = bson!({
190 //! "name": "John Doe",
191 //! "age": 43,
192 //! "phones": [
193 //! "+44 1234567",
194 //! "+44 2345678"
195 //! ]
196 //! });
197 //!
198 //! // Deserialize the Person struct from the BSON data, automatically
199 //! // verifying that the necessary keys are present and that they are of
200 //! // the correct types.
201 //! let mut person: Person = bson::from_bson(bson_data).unwrap();
202 //!
203 //! // Do things just like with any other Rust data structure.
204 //! println!("Redacting {}'s record.", person.name);
205 //! person.name = "REDACTED".to_string();
206 //!
207 //! // Get a serialized version of the input data as a [`Bson`].
208 //! let redacted_bson = bson::to_bson(&person).unwrap();
209 //! ```
210 //!
211 //! Any types that implement [`Serialize`](serde::Serialize) and [`Deserialize`](serde::Deserialize)
212 //! can be used in this way. Doing so helps separate the "business logic" that operates over the
213 //! data from the (de)serialization logic that translates the data to/from its serialized form. This
214 //! can lead to more clear and concise code that is also less error prone.
215 //!
216 //! ## Working with datetimes
217 //!
218 //! The BSON format includes a datetime type, which is modeled in this crate by the
219 //! [`DateTime`] struct, and the
220 //! [`Serialize`](serde::Serialize) and [`Deserialize`](serde::Deserialize) implementations for this
221 //! struct produce and parse BSON datetimes when serializing to or deserializing from BSON. The
222 //! popular crate [`chrono`](docs.rs/chrono) also provides a [`DateTime`] type, but its
223 //! [`Serialize`](serde::Serialize) and [`Deserialize`](serde::Deserialize) implementations operate
224 //! on strings instead, so when using it with BSON, the BSON datetime type is not used. To work
225 //! around this, the `chrono-0_4` feature flag can be enabled. This flag exposes a number of
226 //! convenient conversions between [`bson::DateTime`](crate::DateTime) and [`chrono::DateTime`],
227 //! including the [`serde_helpers::chrono_datetime_as_bson_datetime`]
228 //! serde helper, which can be used to (de)serialize [`chrono::DateTime`]s to/from BSON datetimes,
229 //! and the `From<chrono::DateTime>` implementation for [`Bson`], which allows [`chrono::DateTime`]
230 //! values to be used in the `doc!` and `bson!` macros.
231 //!
232 //! e.g.
233 //! ``` rust
234 //! # #[cfg(feature = "chrono-0_4")]
235 //! # {
236 //! use serde::{Serialize, Deserialize};
237 //! use bson::doc;
238 //!
239 //! #[derive(Serialize, Deserialize)]
240 //! struct Foo {
241 //! // serializes as a BSON datetime.
242 //! date_time: bson::DateTime,
243 //!
244 //! // serializes as an RFC 3339 / ISO-8601 string.
245 //! chrono_datetime: chrono::DateTime<chrono::Utc>,
246 //!
247 //! // serializes as a BSON datetime.
248 //! // this requires the "chrono-0_4" feature flag
249 //! #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
250 //! chrono_as_bson: chrono::DateTime<chrono::Utc>,
251 //! }
252 //!
253 //! // this automatic conversion also requires the "chrono-0_4" feature flag
254 //! let query = doc! {
255 //! "created_at": chrono::Utc::now(),
256 //! };
257 //! # }
258 //! ```
259 //!
260 //! ## Working with UUIDs
261 //!
262 //! See the module level documentation for the [`uuid`] module.
263 //!
264 //! ## WASM support
265 //!
266 //! This crate compiles to the `wasm32-unknown-unknown` target; when doing so, the `js-sys` crate is
267 //! used for the current timestamp component of `ObjectId` generation.
268 //!
269 //! ## Minimum supported Rust version (MSRV)
270 //!
271 //! The MSRV for this crate is currently 1.64.0. This will be rarely be increased, and if it ever
272 //! is, it will only happen in a minor or major version release.
273
274 #![allow(clippy::cognitive_complexity, clippy::derive_partial_eq_without_eq)]
275 #![doc(html_root_url = "https://docs.rs/bson/2.6.0")]
276 #![cfg_attr(docsrs, feature(doc_cfg))]
277
278 #[doc(inline)]
279 pub use self::{
280 binary::Binary,
281 bson::{Array, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp},
282 datetime::DateTime,
283 de::{
284 from_bson,
285 from_bson_with_options,
286 from_document,
287 from_document_with_options,
288 from_reader,
289 from_reader_utf8_lossy,
290 from_slice,
291 from_slice_utf8_lossy,
292 Deserializer,
293 DeserializerOptions,
294 },
295 decimal128::Decimal128,
296 raw::{
297 RawArray,
298 RawArrayBuf,
299 RawBinaryRef,
300 RawBson,
301 RawBsonRef,
302 RawDbPointerRef,
303 RawDocument,
304 RawDocumentBuf,
305 RawJavaScriptCodeWithScope,
306 RawJavaScriptCodeWithScopeRef,
307 RawRegexRef,
308 },
309 ser::{
310 to_bson,
311 to_bson_with_options,
312 to_document,
313 to_document_with_options,
314 to_raw_document_buf,
315 to_vec,
316 Serializer,
317 SerializerOptions,
318 },
319 uuid::{Uuid, UuidRepresentation},
320 };
321
322 #[macro_use]
323 mod macros;
324 pub mod binary;
325 mod bson;
326 pub mod datetime;
327 pub mod de;
328 pub mod decimal128;
329 pub mod document;
330 pub mod extjson;
331 pub mod oid;
332 pub mod raw;
333 pub mod ser;
334 pub mod serde_helpers;
335 pub mod spec;
336 pub mod uuid;
337
338 #[cfg(test)]
339 mod tests;