bincode_purplecoin/
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?|Supported types for Encode/Decode|Enabled methods                                                  |Other|
19//! |------|--------|-----------------------------------------|-----------------------------------------------------------------|-----|
20//! |std   | Yes    |`HashMap` and `HashSet`|`decode_from_std_read` and `encode_into_std_write`|
21//! |alloc | Yes    |All common containers in alloc, like `Vec`, `String`, `Box`|`encode_to_vec`|
22//! |atomic| Yes    |All `Atomic*` integer types, e.g. `AtomicUsize`, and `AtomicBool`||
23//! |derive| Yes    |||Enables the `BorrowDecode`, `Decode` and `Encode` derive macros|
24//! |serde | No     |`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](de::read::Reader) and [writer](enc::write::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//! let mut slice = [0u8; 100];
43//!
44//! // You can encode any type that implements `Encode`.
45//! // You can automatically implement this trait on custom types with the `derive` feature.
46//! let input = (
47//!     0u8,
48//!     10u32,
49//!     10000i128,
50//!     'a',
51//!     [0u8, 1u8, 2u8, 3u8]
52//! );
53//!
54//! let length = bincode::encode_into_slice(
55//!     input,
56//!     &mut slice,
57//!     bincode::config::standard()
58//! ).unwrap();
59//!
60//! let slice = &slice[..length];
61//! println!("Bytes written: {:?}", slice);
62//!
63//! // Decoding works the same as encoding.
64//! // The trait used is `Decode`, and can also be automatically implemented with the `derive` feature.
65//! let decoded: (u8, u32, i128, char, [u8; 4]) = bincode::decode_from_slice(slice, bincode::config::standard()).unwrap().0;
66//!
67//! assert_eq!(decoded, input);
68//! ```
69//!
70//! [`fs::File`]: std::fs::File
71//! [`net::TcpStream`]: std::net::TcpStream
72//!
73
74#![doc(html_root_url = "https://docs.rs/bincode/2.0.0-rc.1")]
75#![crate_name = "bincode_purplecoin"]
76#![crate_type = "rlib"]
77
78#[cfg(feature = "alloc")]
79extern crate alloc;
80#[cfg(any(feature = "std", test))]
81extern crate std;
82
83mod features;
84pub(crate) mod utils;
85pub(crate) mod varint;
86
87use de::{read::Reader, Decoder};
88use enc::write::Writer;
89pub use features::*;
90
91pub mod config;
92pub mod de;
93pub mod enc;
94pub mod error;
95
96pub use de::{BorrowDecode, Decode};
97pub use enc::Encode;
98
99use config::Config;
100
101/// Encode the given value into the given slice. Returns the amount of bytes that have been written.
102///
103/// See the [config] module for more information on configurations.
104///
105/// [config]: config/index.html
106pub fn encode_into_slice<E: enc::Encode, C: Config>(
107    val: E,
108    dst: &mut [u8],
109    config: C,
110) -> Result<usize, error::EncodeError> {
111    let writer = enc::write::SliceWriter::new(dst);
112    let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
113    val.encode(&mut encoder)?;
114    Ok(encoder.into_writer().bytes_written())
115}
116
117/// Encode the given value into a custom [Writer].
118///
119/// See the [config] module for more information on configurations.
120///
121/// [config]: config/index.html
122pub fn encode_into_writer<E: enc::Encode, W: Writer, C: Config>(
123    val: E,
124    writer: W,
125    config: C,
126) -> Result<(), error::EncodeError> {
127    let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
128    val.encode(&mut encoder)?;
129    Ok(())
130}
131
132/// Attempt to decode a given type `D` from the given slice.
133///
134/// See the [config] module for more information on configurations.
135///
136/// [config]: config/index.html
137pub fn decode_from_slice<'a, D: de::BorrowDecode<'a>, C: Config>(
138    src: &'a [u8],
139    config: C,
140) -> Result<(D, usize), error::DecodeError> {
141    let reader = de::read::SliceReader::new(src);
142    let mut decoder = de::DecoderImpl::<_, C>::new(reader, config);
143    let result = D::borrow_decode(&mut decoder)?;
144    let bytes_read = src.len() - decoder.reader().slice.len();
145    Ok((result, bytes_read))
146}
147
148/// Attempt to decode a given type `D` from the given [Reader].
149///
150/// See the [config] module for more information on configurations.
151///
152/// [config]: config/index.html
153pub fn decode_from_reader<D: de::Decode, R: Reader, C: Config>(
154    reader: R,
155    config: C,
156) -> Result<D, error::DecodeError> {
157    let mut decoder = de::DecoderImpl::<_, C>::new(reader, config);
158    D::decode(&mut decoder)
159}
160
161// TODO: Currently our doctests fail when trying to include the specs because the specs depend on `derive` and `alloc`.
162// But we want to have the specs in the docs always
163#[cfg(all(feature = "alloc", feature = "derive", doc))]
164pub mod spec {
165    #![doc = include_str!("../docs/spec.md")]
166}
167
168#[cfg(doc)]
169pub mod migration_guide {
170    #![doc = include_str!("../docs/migration_guide.md")]
171}
172
173// Test the examples in readme.md
174#[cfg(all(feature = "alloc", feature = "derive", doctest))]
175mod readme {
176    #![doc = include_str!("../readme.md")]
177}