| 1 | //! CBOR and serialization. |
| 2 | //! |
| 3 | //! # Usage |
| 4 | //! |
| 5 | //! Serde CBOR 2 supports Rust 1.62 and up. Add this to your `Cargo.toml`: |
| 6 | //! |
| 7 | //! ```toml |
| 8 | //! [dependencies] |
| 9 | //! serde_cbor_2 = "0.12" |
| 10 | //! ``` |
| 11 | //! |
| 12 | //! Serde CBOR 2 can be used as a 'drop in' replacement of `serde_cbor` |
| 13 | //! |
| 14 | //! ```toml |
| 15 | //! [dependencies] |
| 16 | //! serde_cbor = { version = "0.12", package = "serde_cbor_2" } |
| 17 | //! ``` |
| 18 | //! |
| 19 | //! Storing and loading Rust types is easy and requires only |
| 20 | //! minimal modifications to the program code. |
| 21 | //! |
| 22 | //! ```rust |
| 23 | //! # use serde::{Deserialize, Serialize}; |
| 24 | //! use std::error::Error; |
| 25 | //! use std::fs::File; |
| 26 | //! |
| 27 | //! // Types annotated with `Serialize` can be stored as CBOR. |
| 28 | //! // To be able to load them again add `Deserialize`. |
| 29 | //! #[derive(Debug, Serialize, Deserialize)] |
| 30 | //! struct Mascot { |
| 31 | //! name: String, |
| 32 | //! species: String, |
| 33 | //! year_of_birth: u32, |
| 34 | //! } |
| 35 | //! |
| 36 | //! fn main() -> Result<(), Box<dyn Error>> { |
| 37 | //! let ferris = Mascot { |
| 38 | //! name: "Ferris".to_owned(), |
| 39 | //! species: "crab".to_owned(), |
| 40 | //! year_of_birth: 2015, |
| 41 | //! }; |
| 42 | //! |
| 43 | //! let ferris_file = File::create("examples/ferris.cbor")?; |
| 44 | //! // Write Ferris to the given file. |
| 45 | //! // Instead of a file you can use any type that implements `io::Write` |
| 46 | //! // like a HTTP body, database connection etc. |
| 47 | //! serde_cbor_2::to_writer(ferris_file, &ferris)?; |
| 48 | //! |
| 49 | //! let tux_file = File::open("examples/tux.cbor")?; |
| 50 | //! // Load Tux from a file. |
| 51 | //! // Serde CBOR performs roundtrip serialization meaning that |
| 52 | //! // the data will not change in any way. |
| 53 | //! let tux: Mascot = serde_cbor_2::from_reader(tux_file)?; |
| 54 | //! |
| 55 | //! println!("{:?}", tux); |
| 56 | //! // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 } |
| 57 | //! |
| 58 | //! Ok(()) |
| 59 | //! } |
| 60 | //! ``` |
| 61 | //! |
| 62 | //! There are a lot of options available to customize the format. |
| 63 | //! To operate on untyped CBOR values have a look at the `Value` type. |
| 64 | //! |
| 65 | //! # Type-based Serialization and Deserialization |
| 66 | //! Serde provides a mechanism for low boilerplate serialization & deserialization of values to and |
| 67 | //! from CBOR via the serialization API. To be able to serialize a piece of data, it must implement |
| 68 | //! the `serde::Serialize` trait. To be able to deserialize a piece of data, it must implement the |
| 69 | //! `serde::Deserialize` trait. Serde provides an annotation to automatically generate the |
| 70 | //! code for these traits: `#[derive(Serialize, Deserialize)]`. |
| 71 | //! |
| 72 | //! The CBOR API also provides an enum `serde_cbor_2::Value`. |
| 73 | //! |
| 74 | //! # Packed Encoding |
| 75 | //! When serializing structs or enums in CBOR the keys or enum variant names will be serialized |
| 76 | //! as string keys to a map. Especially in embedded environments this can increase the file |
| 77 | //! size too much. In packed encoding all struct keys, as well as any enum variant that has no data, |
| 78 | //! will be serialized as variable sized integers. The first 24 entries in any struct consume only a |
| 79 | //! single byte! Packed encoding uses serde's preferred [externally tagged enum |
| 80 | //! format](https://serde.rs/enum-representations.html) and therefore serializes enum variant names |
| 81 | //! as string keys when that variant contains data. So, in the packed encoding example, `FirstVariant` |
| 82 | //! encodes to a single byte, but encoding `SecondVariant` requires 16 bytes. |
| 83 | //! |
| 84 | //! To serialize a document in this format use `Serializer::new(writer).packed_format()` or |
| 85 | //! the shorthand `ser::to_vec_packed`. The deserialization works without any changes. |
| 86 | //! |
| 87 | //! If you would like to omit the enum variant encoding for all variants, including ones that |
| 88 | //! contain data, you can add `legacy_enums()` in addition to `packed_format()`, as can seen |
| 89 | //! in the Serialize using minimal encoding example. |
| 90 | //! |
| 91 | //! # Self describing documents |
| 92 | //! In some contexts different formats are used but there is no way to declare the format used |
| 93 | //! out of band. For this reason CBOR has a magic number that may be added before any document. |
| 94 | //! Self describing documents are created with `serializer.self_describe()`. |
| 95 | //! |
| 96 | //! # Examples |
| 97 | //! Read a CBOR value that is known to be a map of string keys to string values and print it. |
| 98 | //! |
| 99 | //! ```rust |
| 100 | //! use std::collections::BTreeMap; |
| 101 | //! use serde_cbor_2::from_slice; |
| 102 | //! |
| 103 | //! let slice = b"\xa5aaaAabaBacaCadaDaeaE"; |
| 104 | //! let value: BTreeMap<String, String> = from_slice(slice).unwrap(); |
| 105 | //! println!("{:?}", value); // {"e": "E", "d": "D", "a": "A", "c": "C", "b": "B"} |
| 106 | //! ``` |
| 107 | //! |
| 108 | //! Read a general CBOR value with an unknown content. |
| 109 | //! |
| 110 | //! ```rust |
| 111 | //! use serde_cbor_2::from_slice; |
| 112 | //! use serde_cbor_2::value::Value; |
| 113 | //! |
| 114 | //! let slice = b"\x82\x01\xa1aaab"; |
| 115 | //! let value: Value = from_slice(slice).unwrap(); |
| 116 | //! println!("{:?}", value); // Array([U64(1), Object({String("a"): String("b")})]) |
| 117 | //! ``` |
| 118 | //! |
| 119 | //! Serialize an object. |
| 120 | //! |
| 121 | //! ```rust |
| 122 | //! use std::collections::BTreeMap; |
| 123 | //! use serde_cbor_2::to_vec; |
| 124 | //! |
| 125 | //! let mut programming_languages = BTreeMap::new(); |
| 126 | //! programming_languages.insert("rust", vec!["safe", "concurrent", "fast"]); |
| 127 | //! programming_languages.insert("python", vec!["powerful", "friendly", "open"]); |
| 128 | //! programming_languages.insert("js", vec!["lightweight", "interpreted", "object-oriented"]); |
| 129 | //! let encoded = to_vec(&programming_languages); |
| 130 | //! assert_eq!(encoded.unwrap().len(), 103); |
| 131 | //! ``` |
| 132 | //! |
| 133 | //! Deserializing data in the middle of a slice |
| 134 | //! ``` |
| 135 | //! use serde_cbor_2::Deserializer; |
| 136 | //! |
| 137 | //! # fn main() { |
| 138 | //! let data: Vec<u8> = vec![ |
| 139 | //! 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x66, 0x66, 0x6f, 0x6f, 0x62, |
| 140 | //! 0x61, 0x72, |
| 141 | //! ]; |
| 142 | //! let mut deserializer = Deserializer::from_slice(&data); |
| 143 | //! let value: &str = serde::de::Deserialize::deserialize(&mut deserializer) |
| 144 | //! .unwrap(); |
| 145 | //! let rest = &data[deserializer.byte_offset()..]; |
| 146 | //! assert_eq!(value, "foobar"); |
| 147 | //! assert_eq!(rest, &[0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]); |
| 148 | //! # } |
| 149 | //! ``` |
| 150 | //! |
| 151 | //! Serialize using packed encoding |
| 152 | //! |
| 153 | //! ```rust |
| 154 | //! # use serde::{Deserialize, Serialize}; |
| 155 | //! use serde_cbor_2::ser::to_vec_packed; |
| 156 | //! |
| 157 | //! #[derive(Debug, Serialize, Deserialize)] |
| 158 | //! enum WithTwoVariants { |
| 159 | //! FirstVariant, |
| 160 | //! SecondVariant(u8), |
| 161 | //! } |
| 162 | //! |
| 163 | //! use WithTwoVariants::*; |
| 164 | //! |
| 165 | //! let cbor = to_vec_packed(&FirstVariant).unwrap(); |
| 166 | //! assert_eq!(cbor.len(), 1); |
| 167 | //! |
| 168 | //! let cbor = to_vec_packed(&SecondVariant(0)).unwrap(); |
| 169 | //! assert_eq!(cbor.len(), 16); // Includes 13 bytes of "SecondVariant" |
| 170 | //! ``` |
| 171 | //! |
| 172 | //! Serialize using minimal encoding |
| 173 | //! |
| 174 | //! ```rust |
| 175 | //! # use serde::{Deserialize, Serialize}; |
| 176 | //! use serde_cbor_2::{Result, Serializer, ser::{self, IoWrite}}; |
| 177 | //! |
| 178 | //! fn to_vec_minimal<T>(value: &T) -> Result<Vec<u8>> |
| 179 | //! where |
| 180 | //! T: serde::Serialize, |
| 181 | //! { |
| 182 | //! let mut vec = Vec::new(); |
| 183 | //! value.serialize(&mut Serializer::new(&mut IoWrite::new(&mut vec)).packed_format().legacy_enums())?; |
| 184 | //! Ok(vec) |
| 185 | //! } |
| 186 | //! |
| 187 | //! #[derive(Debug, Serialize, Deserialize)] |
| 188 | //! enum WithTwoVariants { |
| 189 | //! FirstVariant, |
| 190 | //! SecondVariant(u8), |
| 191 | //! } |
| 192 | //! |
| 193 | //! use WithTwoVariants::*; |
| 194 | //! |
| 195 | //! let cbor = to_vec_minimal(&FirstVariant).unwrap(); |
| 196 | //! assert_eq!(cbor.len(), 1); |
| 197 | //! |
| 198 | //! let cbor = to_vec_minimal(&SecondVariant(0)).unwrap(); |
| 199 | //! assert_eq!(cbor.len(), 3); |
| 200 | //! ``` |
| 201 | //! |
| 202 | //! # `no-std` support |
| 203 | //! |
| 204 | //! Serde CBOR supports building in a `no_std` context, use the following lines |
| 205 | //! in your `Cargo.toml` dependencies: |
| 206 | //! ``` toml |
| 207 | //! [dependencies] |
| 208 | //! serde = { version = "1.0", default-features = false } |
| 209 | //! serde_cbor = { version = "0.10", default-features = false } |
| 210 | //! ``` |
| 211 | //! |
| 212 | //! Without the `std` feature the functions [from_reader], [from_slice], [to_vec], and [to_writer] |
| 213 | //! are not exported. To export [from_slice] and [to_vec] enable the `alloc` feature. The `alloc` |
| 214 | //! feature uses the [`alloc` library][alloc-lib] and requires at least version 1.36.0 of Rust. |
| 215 | //! |
| 216 | //! [alloc-lib]: https://doc.rust-lang.org/alloc/ |
| 217 | //! |
| 218 | //! *Note*: to use derive macros in serde you will need to declare `serde` |
| 219 | //! dependency like so: |
| 220 | //! ``` toml |
| 221 | //! serde = { version = "1.0", default-features = false, features = ["derive"] } |
| 222 | //! ``` |
| 223 | //! |
| 224 | //! Serialize an object with `no_std` and without `alloc`. |
| 225 | //! ``` rust |
| 226 | //! # fn main() -> Result<(), serde_cbor_2::Error> { |
| 227 | //! # use serde::Serialize; |
| 228 | //! use serde_cbor_2::Serializer; |
| 229 | //! use serde_cbor_2::ser::SliceWrite; |
| 230 | //! |
| 231 | //! #[derive(Serialize)] |
| 232 | //! struct User { |
| 233 | //! user_id: u32, |
| 234 | //! password_hash: [u8; 4], |
| 235 | //! } |
| 236 | //! |
| 237 | //! let mut buf = [0u8; 100]; |
| 238 | //! let writer = SliceWrite::new(&mut buf[..]); |
| 239 | //! let mut ser = Serializer::new(writer); |
| 240 | //! let user = User { |
| 241 | //! user_id: 42, |
| 242 | //! password_hash: [1, 2, 3, 4], |
| 243 | //! }; |
| 244 | //! user.serialize(&mut ser)?; |
| 245 | //! let writer = ser.into_inner(); |
| 246 | //! let size = writer.bytes_written(); |
| 247 | //! let expected = [ |
| 248 | //! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d, |
| 249 | //! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, |
| 250 | //! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4 |
| 251 | //! ]; |
| 252 | //! assert_eq!(&buf[..size], expected); |
| 253 | //! # Ok(()) |
| 254 | //! # } |
| 255 | //! ``` |
| 256 | //! |
| 257 | //! Deserialize an object. |
| 258 | //! ``` rust |
| 259 | //! # use serde::Deserialize; |
| 260 | //! # fn main() -> Result<(), serde_cbor_2::Error> { |
| 261 | //! #[derive(Debug, PartialEq, Deserialize)] |
| 262 | //! struct User { |
| 263 | //! user_id: u32, |
| 264 | //! password_hash: [u8; 4], |
| 265 | //! } |
| 266 | //! |
| 267 | //! let value = [ |
| 268 | //! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d, |
| 269 | //! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, |
| 270 | //! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4 |
| 271 | //! ]; |
| 272 | //! |
| 273 | //! // from_slice_with_scratch will not alter input data, use it whenever you |
| 274 | //! // borrow from somewhere else. |
| 275 | //! // You will have to size your scratch according to the input data you |
| 276 | //! // expect. |
| 277 | //! use serde_cbor_2::de::from_slice_with_scratch; |
| 278 | //! let mut scratch = [0u8; 32]; |
| 279 | //! let user: User = from_slice_with_scratch(&value[..], &mut scratch)?; |
| 280 | //! assert_eq!(user, User { |
| 281 | //! user_id: 42, |
| 282 | //! password_hash: [1, 2, 3, 4], |
| 283 | //! }); |
| 284 | //! |
| 285 | //! let mut value = [ |
| 286 | //! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d, |
| 287 | //! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, |
| 288 | //! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4 |
| 289 | //! ]; |
| 290 | //! |
| 291 | //! // from_mut_slice will move data around the input slice, you may only use it |
| 292 | //! // on data you may own or can modify. |
| 293 | //! use serde_cbor_2::de::from_mut_slice; |
| 294 | //! let user: User = from_mut_slice(&mut value[..])?; |
| 295 | //! assert_eq!(user, User { |
| 296 | //! user_id: 42, |
| 297 | //! password_hash: [1, 2, 3, 4], |
| 298 | //! }); |
| 299 | //! # Ok(()) |
| 300 | //! # } |
| 301 | //! ``` |
| 302 | //! |
| 303 | //! # Limitations |
| 304 | //! |
| 305 | //! While Serde CBOR strives to support all features of Serde and CBOR |
| 306 | //! there are a few limitations. |
| 307 | //! |
| 308 | //! * [Tags] are ignored during deserialization and can't be emitted during |
| 309 | //! serialization. This is because Serde has no concept of tagged |
| 310 | //! values. See: [#3] |
| 311 | //! * Unknown [simple values] cause an `UnassignedCode` error. |
| 312 | //! The simple values *False* and *True* are recognized and parsed as bool. |
| 313 | //! *Null* and *Undefined* are both deserialized as *unit*. |
| 314 | //! The *unit* type is serialized as *Null*. See: [#86] |
| 315 | //! * [128-bit integers] can't be directly encoded in CBOR. If you need them |
| 316 | //! store them as a byte string. See: [#77] |
| 317 | //! |
| 318 | //! [Tags]: https://tools.ietf.org/html/rfc7049#section-2.4.4 |
| 319 | //! [#3]: https://github.com/pyfisch/cbor/issues/3 |
| 320 | //! [simple values]: https://tools.ietf.org/html/rfc7049#section-3.5 |
| 321 | //! [#86]: https://github.com/pyfisch/cbor/issues/86 |
| 322 | //! [128-bit integers]: https://doc.rust-lang.org/std/primitive.u128.html |
| 323 | //! [#77]: https://github.com/pyfisch/cbor/issues/77 |
| 324 | |
| 325 | #![deny(missing_docs)] |
| 326 | #![cfg_attr(not(feature = "std"), no_std)] |
| 327 | |
| 328 | // When we are running tests in no_std mode we need to explicitly link std, because `cargo test` |
| 329 | // will not work without it. |
| 330 | #[cfg(all(not(feature = "std"), test))] |
| 331 | extern crate std; |
| 332 | |
| 333 | #[cfg(feature = "alloc")] |
| 334 | extern crate alloc; |
| 335 | |
| 336 | pub mod de; |
| 337 | pub mod error; |
| 338 | mod read; |
| 339 | pub mod ser; |
| 340 | pub mod tags; |
| 341 | mod write; |
| 342 | |
| 343 | #[cfg(feature = "std")] |
| 344 | pub mod value; |
| 345 | |
| 346 | // Re-export the [items recommended by serde](https://serde.rs/conventions.html). |
| 347 | #[doc(inline)] |
| 348 | pub use crate::de::{Deserializer, StreamDeserializer}; |
| 349 | |
| 350 | #[doc(inline)] |
| 351 | pub use crate::error::{Error, Result}; |
| 352 | |
| 353 | #[doc(inline)] |
| 354 | pub use crate::ser::Serializer; |
| 355 | |
| 356 | // Convenience functions for serialization and deserialization. |
| 357 | // These functions are only available in `std` mode. |
| 358 | #[cfg(feature = "std")] |
| 359 | #[doc(inline)] |
| 360 | pub use crate::de::from_reader; |
| 361 | |
| 362 | #[cfg(any(feature = "std", feature = "alloc"))] |
| 363 | #[doc(inline)] |
| 364 | pub use crate::de::from_slice; |
| 365 | |
| 366 | #[cfg(any(feature = "std", feature = "alloc"))] |
| 367 | #[doc(inline)] |
| 368 | pub use crate::ser::to_vec; |
| 369 | |
| 370 | #[cfg(feature = "std")] |
| 371 | #[doc(inline)] |
| 372 | pub use crate::ser::to_writer; |
| 373 | |
| 374 | // Re-export the value type like serde_json |
| 375 | #[cfg(feature = "std")] |
| 376 | #[doc(inline)] |
| 377 | pub use crate::value::Value; |