Debian Codegraph @

README.md

raw
1 # bson
2
3 [![crates.io](https://img.shields.io/crates/v/bson.svg)](https://crates.io/crates/bson)
4 [![docs.rs](https://docs.rs/mongodb/badge.svg)](https://docs.rs/bson)
5 [![crates.io](https://img.shields.io/crates/l/bson.svg)](https://crates.io/crates/bson)
6
7 Encoding and decoding support for BSON in Rust
8
9 ## Index
10 - [Installation](#installation)
11 - [Requirements](#requirements)
12 - [Importing](#importing)
13 - [Feature flags](#feature-flags)
14 - [Useful links](#useful-links)
15 - [Overview of BSON Format](#overview-of-the-bson-format)
16 - [Usage](#usage)
17 - [BSON Values](#bson-values)
18 - [BSON Documents](#bson-documents)
19 - [Modeling BSON with strongly typed data structures](#modeling-bson-with-strongly-typed-data-structures)
20 - [Working with datetimes](#working-with-datetimes)
21 - [Working with UUIDs](#working-with-uuids)
22 - [WASM support](#wasm-support)
23 - [Contributing](#contributing)
24 - [Running the Tests](#running-the-tests)
25 - [Continuous Integration](#continuous-integration)
26
27 ## Useful links
28 - [API Documentation](https://docs.rs/bson/)
29 - [Serde Documentation](https://serde.rs/)
30
31 ## Installation
32 ### Requirements
33 - Rust 1.48+
34
35 ### Importing
36 This crate is available on [crates.io](https://crates.io/crates/bson). To use it in your application, simply add it to your project's `Cargo.toml`.
37
38 ```toml
39 [dependencies]
40 bson = "2.10.0"
41 ```
42
43 Note that if you are using `bson` through the `mongodb` crate, you do not need to specify it in your
44 `Cargo.toml`, since the `mongodb` crate already re-exports it.
45
46 #### Feature Flags
47
48 | Feature | Description | Extra dependencies | Default |
49 | :----------- | :---------------------------------------------------------------------------------------------------------- | :----------------- | :------ |
50 | `chrono-0_4` | Enable support for v0.4 of the [`chrono`](https://docs.rs/chrono/0.4) crate in the public API. | n/a | no |
51 | `uuid-0_8` | Enable support for v0.8 of the [`uuid`](https://docs.rs/uuid/0.8) crate in the public API. | n/a | no |
52 | `uuid-1` | Enable support for v1.x of the [`uuid`](https://docs.rs/uuid/1.0) crate in the public API. | n/a | no |
53 | `serde_with` | Enable [`serde_with`](https://docs.rs/serde_with/1.x) 1.x integrations for `bson::DateTime` and `bson::Uuid`.| serde_with | no |
54 | `serde_with-3` | Enable [`serde_with`](https://docs.rs/serde_with/3.x) 3.x integrations for `bson::DateTime` and `bson::Uuid`.| serde_with | no |
55 ## Overview of the BSON Format
56
57 BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents.
58 Like JSON, BSON supports the embedding of documents and arrays within other documents
59 and arrays. BSON also contains extensions that allow representation of data types that
60 are not part of the JSON spec. For example, BSON has a datetime type and a binary data type.
61
62 ```text
63 // JSON equivalent
64 {"hello": "world"}
65
66 // BSON encoding
67 \x16\x00\x00\x00 // total document size
68 \x02 // 0x02 = type String
69 hello\x00 // field name
70 \x06\x00\x00\x00world\x00 // field value
71 \x00 // 0x00 = type EOO ('end of object')
72 ```
73
74 BSON is the primary data representation for [MongoDB](https://www.mongodb.com/), and this crate is used in the
75 [`mongodb`](https://docs.rs/mongodb/latest/mongodb/) driver crate in its API and implementation.
76
77 For more information about BSON itself, see [bsonspec.org](http://bsonspec.org).
78
79 ## Usage
80
81 ### BSON values
82
83 Many different types can be represented as a BSON value, including 32-bit and 64-bit signed
84 integers, 64 bit floating point numbers, strings, datetimes, embedded documents, and more. To
85 see a full list of possible BSON values, see the [BSON specification](http://bsonspec.org/spec.html). The various
86 possible BSON values are modeled in this crate by the [`Bson`](https://docs.rs/bson/latest/bson/enum.Bson.html) enum.
87
88 #### Creating [`Bson`](https://docs.rs/bson/latest/bson/enum.Bson.html) instances
89
90 [`Bson`](https://docs.rs/bson/latest/bson/enum.Bson.html) values can be instantiated directly or via the
91 [`bson!`](https://docs.rs/bson/latest/bson/macro.bson.html) macro:
92
93 ```rust
94 let string = Bson::String("hello world".to_string());
95 let int = Bson::Int32(5);
96 let array = Bson::Array(vec![Bson::Int32(5), Bson::Boolean(false)]);
97
98 let string: Bson = "hello world".into();
99 let int: Bson = 5i32.into();
100
101 let string = bson!("hello world");
102 let int = bson!(5);
103 let array = bson!([5, false]);
104 ```
105 [`bson!`](https://docs.rs/bson/latest/bson/macro.bson.html) supports both array and object literals, and it automatically converts any values specified to [`Bson`](https://docs.rs/bson/latest/bson/enum.Bson.html), provided they are `Into<Bson>`.
106
107 #### [`Bson`](https://docs.rs/bson/latest/bson/enum.Bson.html) value unwrapping
108
109 [`Bson`](https://docs.rs/bson/latest/bson/enum.Bson.html) has a number of helper methods for accessing the underlying native Rust types. These helpers can be useful in circumstances in which the specific type of a BSON value
110 is known ahead of time.
111
112 e.g.:
113 ```rust
114 let value = Bson::Int32(5);
115 let int = value.as_i32(); // Some(5)
116 let bool = value.as_bool(); // None
117
118 let value = bson!([true]);
119 let array = value.as_array(); // Some(&Vec<Bson>)
120 ```
121
122 ### BSON documents
123
124 BSON documents are ordered maps of UTF-8 encoded strings to BSON values. They are logically similar to JSON objects in that they can contain subdocuments, arrays, and values of several different types. This crate models BSON documents via the
125 [`Document`](https://docs.rs/bson/latest/bson/document/struct.Document.html) struct.
126
127 #### Creating [`Document`](https://docs.rs/bson/latest/bson/document/struct.Document.html)s
128
129 [`Document`](https://docs.rs/bson/latest/bson/document/struct.Document.html)s can be created directly either from a byte
130 reader containing BSON data or via the `doc!` macro:
131 ```rust
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!`](https://docs.rs/bson/latest/bson/macro.doc.html) works similarly to [`bson!`](https://docs.rs/bson/latest/bson/macro.bson.html), except that it always
142 returns a [`Document`](https://docs.rs/bson/latest/bson/document/struct.Document.html) rather than a [`Bson`](https://docs.rs/bson/latest/bson/enum.Bson.html).
143
144 #### [`Document`](https://docs.rs/bson/latest/bson/document/struct.Document.html) member access
145
146 [`Document`](https://docs.rs/bson/latest/bson/document/struct.Document.html) has a number of methods on it to facilitate member
147 access:
148
149 ```rust
150 let doc = doc! {
151 "string": "string",
152 "bool": true,
153 "i32": 5,
154 "doc": { "x": true },
155 };
156
157 // attempt get values as untyped Bson
158 let none = doc.get("asdfadsf"); // None
159 let value = doc.get("string"); // Some(&Bson::String("string"))
160
161 // attempt to get values with explicit typing
162 let string = doc.get_str("string"); // Ok("string")
163 let subdoc = doc.get_document("doc"); // Some(Document({ "x": true }))
164 let error = doc.get_i64("i32"); // Err(...)
165 ```
166
167 ### Modeling BSON with strongly typed data structures
168
169 While it is possible to work with documents and BSON values directly, it will often introduce a
170 lot of boilerplate for verifying the necessary keys are present and their values are the correct
171 types. [`serde`](https://serde.rs/) provides a powerful way of mapping BSON data into Rust data structures largely
172 automatically, removing the need for all that boilerplate.
173
174 e.g.:
175 ```rust
176 #[derive(Serialize, Deserialize)]
177 struct Person {
178 name: String,
179 age: i32,
180 phones: Vec<String>,
181 }
182
183 // Some BSON input data as a `Bson`.
184 let bson_data: Bson = bson!({
185 "name": "John Doe",
186 "age": 43,
187 "phones": [
188 "+44 1234567",
189 "+44 2345678"
190 ]
191 });
192
193 // Deserialize the Person struct from the BSON data, automatically
194 // verifying that the necessary keys are present and that they are of
195 // the correct types.
196 let mut person: Person = bson::from_bson(bson_data).unwrap();
197
198 // Do things just like with any other Rust data structure.
199 println!("Redacting {}'s record.", person.name);
200 person.name = "REDACTED".to_string();
201
202 // Get a serialized version of the input data as a `Bson`.
203 let redacted_bson = bson::to_bson(&person).unwrap();
204 ```
205
206 Any types that implement `Serialize` and `Deserialize` can be used in this way. Doing so helps
207 separate the "business logic" that operates over the data from the (de)serialization logic that
208 translates the data to/from its serialized form. This can lead to more clear and concise code
209 that is also less error prone.
210
211 ### Working with datetimes
212
213 The BSON format includes a datetime type, which is modeled in this crate by the
214 [`bson::DateTime`](https://docs.rs/bson/latest/bson/struct.DateTime.html) struct, and the
215 `Serialize` and `Deserialize` implementations for this struct produce and parse BSON datetimes when
216 serializing to or deserializing from BSON. The popular crate [`chrono`](https://docs.rs/chrono) also
217 provides a `DateTime` type, but its `Serialize` and `Deserialize` implementations operate on strings
218 instead, so when using it with BSON, the BSON datetime type is not used. To work around this, the
219 `chrono-0_4` feature flag can be enabled. This flag exposes a number of convenient conversions
220 between `bson::DateTime` and `chrono::DateTime`, including the
221 [`chrono_datetime_as_bson_datetime`](https://docs.rs/bson/latest/bson/serde_helpers/chrono_datetime_as_bson_datetime/index.html)
222 serde helper, which can be used to (de)serialize `chrono::DateTime`s to/from BSON datetimes, and the
223 `From<chrono::DateTime>` implementation for `Bson`, which allows `chrono::DateTime` values to be
224 used in the `doc!` and `bson!` macros.
225
226 e.g.
227 ``` rust
228 use serde::{Serialize, Deserialize};
229
230 #[derive(Serialize, Deserialize)]
231 struct Foo {
232 // serializes as a BSON datetime.
233 date_time: bson::DateTime,
234
235 // serializes as an RFC 3339 / ISO-8601 string.
236 chrono_datetime: chrono::DateTime<chrono::Utc>,
237
238 // serializes as a BSON datetime.
239 // this requires the "chrono-0_4" feature flag
240 #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
241 chrono_as_bson: chrono::DateTime<chrono::Utc>,
242 }
243
244 // this automatic conversion also requires the "chrono-0_4" feature flag
245 let query = doc! {
246 "created_at": chrono::Utc::now(),
247 };
248 ```
249
250 ### Working with UUIDs
251
252 See the module-level documentation for the [`bson::uuid` module](https://docs.rs/bson/latest/bson/uuid).
253
254 ### WASM support
255
256 This crate compiles to the `wasm32-unknown-unknown` target; when doing so, the `js-sys` crate is used for the current timestamp component of `ObjectId` generation.
257
258 ## Minimum supported Rust version (MSRV)
259
260 The MSRV for this crate is currently 1.64.0. This will be rarely be increased, and if it ever is,
261 it will only happen in a minor or major version release.
262
263 ## Contributing
264
265 We encourage and would happily accept contributions in the form of GitHub pull requests. Before opening one, be sure to run the tests locally; check out the [testing section](#running-the-tests) for information on how to do that. Once you open a pull request, your branch will be run against the same testing matrix that we use for our [continuous integration](#continuous-integration) system, so it is usually sufficient to only run the integration tests locally against a standalone. Remember to always run the linter tests before opening a pull request.
266
267 ## Running the tests
268
269 ### Integration and unit tests
270
271 To actually run the tests, you can use `cargo` like you would in any other crate:
272 ```bash
273 cargo test --verbose # runs against localhost:27017
274 ```
275
276 ### Linter Tests
277 Our linter tests use the nightly version of `rustfmt` to verify that the source is formatted properly and the stable version of `clippy` to statically detect any common mistakes.
278 You can use `rustup` to install them both:
279 ```bash
280 rustup component add clippy --toolchain stable
281 rustup component add rustfmt --toolchain nightly
282 ```
283 To run the linter tests, run the `check-clippy.sh` and `check-rustfmt.sh` scripts in the `.evergreen` directory:
284 ```bash
285 bash .evergreen/check-clippy.sh && bash .evergreen/check-rustfmt.sh
286 ```
287
288 ## Continuous Integration
289 Commits to main are run automatically on [evergreen](https://evergreen.mongodb.com/waterfall/rust-bson).