Skip to main content

cu_bincode/
lib.rs

1#![no_std]
2#![warn(missing_docs, unused_lifetimes)]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5//! Bincode is a crate for encoding and decoding using a tiny binary
6//! serialization strategy.  Using it, you can easily go from having
7//! an object in memory, quickly serialize it to bytes, and then
8//! deserialize it back just as fast!
9//!
10//! If you're coming from bincode 1, check out our [migration guide](migration_guide/index.html)
11//!
12//! # Serde
13//!
14//! Starting from bincode 2, serde is now an optional dependency. If you want to use serde, please enable the `serde` feature. See [Features](#features) for more information.
15//!
16//! # Features
17//!
18//! |Name  |Default?|Affects MSRV?|Supported types for Encode/Decode|Enabled methods                                                  |Other|
19//! |------|--------|-------------|-----------------------------------------|-----------------------------------------------------------------|-----|
20//! |std   | Yes    | No          |`HashMap` and `HashSet`|`decode_from_std_read` and `encode_into_std_write`|
21//! |alloc | Yes    | No          |All common containers in alloc, like `Vec`, `String`, `Box`|`encode_to_vec`|
22//! |atomic| Yes    | No          |All `Atomic*` integer types, e.g. `AtomicUsize`, and `AtomicBool`||
23//! |derive| Yes    | No          |||Enables the `BorrowDecode`, `Decode` and `Encode` derive macros|
24//! |serde | No     | Yes (MSRV reliant on serde)|`Compat` and `BorrowCompat`, which will work for all types that implement serde's traits|serde-specific encode/decode functions in the [serde] module|Note: There are several [known issues](serde/index.html#known-issues) when using serde and bincode|
25//!
26//! # Which functions to use
27//!
28//! Bincode has a couple of pairs of functions that are used in different situations.
29//!
30//! |Situation|Encode|Decode|
31//! |---|---|---
32//! |You're working with [`fs::File`] or [`net::TcpStream`]|[`encode_into_std_write`]|[`decode_from_std_read`]|
33//! |you're working with in-memory buffers|[`encode_to_vec`]|[`decode_from_slice`]|
34//! |You want to use a custom [Reader] and [Writer]|[`encode_into_writer`]|[`decode_from_reader`]|
35//! |You're working with pre-allocated buffers or on embedded targets|[`encode_into_slice`]|[`decode_from_slice`]|
36//!
37//! **Note:** If you're using `serde`, use `bincode::serde::...` instead of `bincode::...`
38//!
39//! # Example
40//!
41//! ```rust
42//! # extern crate cu_bincode as bincode;
43//! let mut slice = [0u8; 100];
44//!
45//! // You can encode any type that implements `Encode`.
46//! // You can automatically implement this trait on custom types with the `derive` feature.
47//! let input = (
48//!     0u8,
49//!     10u32,
50//!     10000i128,
51//!     'a',
52//!     [0u8, 1u8, 2u8, 3u8]
53//! );
54//!
55//! let length = bincode::encode_into_slice(
56//!     input,
57//!     &mut slice,
58//!     bincode::config::standard()
59//! ).unwrap();
60//!
61//! let slice = &slice[..length];
62//! println!("Bytes written: {:?}", slice);
63//!
64//! // Decoding works the same as encoding.
65//! // The trait used is `Decode`, and can also be automatically implemented with the `derive` feature.
66//! let decoded: (u8, u32, i128, char, [u8; 4]) = bincode::decode_from_slice(slice, bincode::config::standard()).unwrap().0;
67//!
68//! assert_eq!(decoded, input);
69//! ```
70//!
71//! [`fs::File`]: std::fs::File
72//! [`net::TcpStream`]: std::net::TcpStream
73//!
74
75#![doc(html_root_url = "https://docs.rs/cu-bincode/2.1.0")]
76#![crate_name = "cu_bincode"]
77#![crate_type = "rlib"]
78
79#[cfg(feature = "alloc")]
80extern crate alloc;
81#[cfg(any(feature = "std", test))]
82extern crate std;
83
84mod atomic;
85mod uleb128;
86
87pub use uleb128::Uleb128;
88mod features;
89pub(crate) mod utils;
90pub(crate) mod varint;
91
92use de::{Decoder, read::Reader};
93use enc::write::Writer;
94
95#[cfg(any(
96    feature = "alloc",
97    feature = "std",
98    feature = "derive",
99    feature = "serde"
100))]
101pub use features::*;
102
103pub mod config;
104#[macro_use]
105pub mod de;
106pub mod enc;
107pub mod error;
108
109pub use de::{BorrowDecode, Decode};
110pub use enc::Encode;
111
112use config::Config;
113
114/// Encode the given value into the given slice. Returns the amount of bytes that have been written.
115///
116/// See the [config] module for more information on configurations.
117///
118/// [config]: config/index.html
119pub fn encode_into_slice<E: enc::Encode, C: Config>(
120    val: E,
121    dst: &mut [u8],
122    config: C,
123) -> Result<usize, error::EncodeError> {
124    let writer = enc::write::SliceWriter::new(dst);
125    let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
126    val.encode(&mut encoder)?;
127    Ok(encoder.into_writer().bytes_written())
128}
129
130/// Encode the given value into a custom [Writer].
131///
132/// See the [config] module for more information on configurations.
133///
134/// [config]: config/index.html
135pub fn encode_into_writer<E: enc::Encode, W: Writer, C: Config>(
136    val: E,
137    writer: W,
138    config: C,
139) -> Result<(), error::EncodeError> {
140    let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
141    val.encode(&mut encoder)?;
142    Ok(())
143}
144
145/// Attempt to decode a given type `D` from the given slice. Returns the decoded output and the amount of bytes read.
146///
147/// Note that this does not work with borrowed types like `&str` or `&[u8]`. For that use [borrow_decode_from_slice].
148///
149/// See the [config] module for more information on configurations.
150///
151/// [config]: config/index.html
152pub fn decode_from_slice<D: de::Decode<()>, C: Config>(
153    src: &[u8],
154    config: C,
155) -> Result<(D, usize), error::DecodeError> {
156    decode_from_slice_with_context(src, config, ())
157}
158
159/// Attempt to decode a given type `D` from the given slice with `Context`. Returns the decoded output and the amount of bytes read.
160///
161/// Note that this does not work with borrowed types like `&str` or `&[u8]`. For that use [borrow_decode_from_slice].
162///
163/// See the [config] module for more information on configurations.
164///
165/// [config]: config/index.html
166pub fn decode_from_slice_with_context<Context, D: de::Decode<Context>, C: Config>(
167    src: &[u8],
168    config: C,
169    context: Context,
170) -> Result<(D, usize), error::DecodeError> {
171    let reader = de::read::SliceReader::new(src);
172    let mut decoder = de::DecoderImpl::<_, C, Context>::new(reader, config, context);
173    let result = D::decode(&mut decoder)?;
174    let bytes_read = src.len() - decoder.reader().slice.len();
175    Ok((result, bytes_read))
176}
177
178/// Attempt to decode a given type `D` from the given slice. Returns the decoded output and the amount of bytes read.
179///
180/// See the [config] module for more information on configurations.
181///
182/// [config]: config/index.html
183pub fn borrow_decode_from_slice<'a, D: de::BorrowDecode<'a, ()>, C: Config>(
184    src: &'a [u8],
185    config: C,
186) -> Result<(D, usize), error::DecodeError> {
187    borrow_decode_from_slice_with_context(src, config, ())
188}
189
190/// Attempt to decode a given type `D` from the given slice with `Context`. Returns the decoded output and the amount of bytes read.
191///
192/// See the [config] module for more information on configurations.
193///
194/// [config]: config/index.html
195pub fn borrow_decode_from_slice_with_context<
196    'a,
197    Context,
198    D: de::BorrowDecode<'a, Context>,
199    C: Config,
200>(
201    src: &'a [u8],
202    config: C,
203    context: Context,
204) -> Result<(D, usize), error::DecodeError> {
205    let reader = de::read::SliceReader::new(src);
206    let mut decoder = de::DecoderImpl::<_, C, Context>::new(reader, config, context);
207    let result = D::borrow_decode(&mut decoder)?;
208    let bytes_read = src.len() - decoder.reader().slice.len();
209    Ok((result, bytes_read))
210}
211
212/// Attempt to decode a given type `D` from the given [Reader].
213///
214/// See the [config] module for more information on configurations.
215///
216/// [config]: config/index.html
217pub fn decode_from_reader<D: de::Decode<()>, R: Reader, C: Config>(
218    reader: R,
219    config: C,
220) -> Result<D, error::DecodeError> {
221    let mut decoder = de::DecoderImpl::<_, C, ()>::new(reader, config, ());
222    D::decode(&mut decoder)
223}
224
225// TODO: Currently our doctests fail when trying to include the specs because the specs depend on `derive` and `alloc`.
226// But we want to have the specs in the docs always
227#[cfg(all(feature = "alloc", feature = "derive", doc))]
228pub mod spec {
229    #![doc = include_str!("../docs/spec.md")]
230}
231
232#[cfg(doc)]
233pub mod migration_guide {
234    #![doc = include_str!("../docs/migration_guide.md")]
235}
236
237// Test the examples in readme.md
238#[cfg(all(feature = "alloc", feature = "derive", doctest))]
239mod readme {
240    #![doc = include_str!("../README.md")]
241}