bincode_next/lib.rs
1#![no_std]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![allow(internal_features)]
4#![cfg_attr(is_nightly, feature(core_intrinsics))]
5
6//! Bincode-next is a crate for encoding and decoding using a tiny binary
7//! serialization strategy. Using it, you can easily go from having
8//! an object in memory, quickly serialize it to bytes, and then
9//! deserialize it back just as fast!
10//!
11//! If you're coming from bincode 1, check out our [migration guide](migration_guide/index.html)
12//!
13//! # Serde
14//!
15//! 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.
16//!
17//! # Features
18//!
19//! |Name |Default?|Affects MSRV?|Supported types for Encode/Decode|Enabled methods |Other|
20//! |------|--------|-------------|-----------------------------------------|-----------------------------------------------------------------|-----|
21//! |std | Yes | No |`HashMap` and `HashSet`|`decode_from_std_read` and `encode_into_std_write`|
22//! |alloc | Yes | No |All common containers in alloc, like `Vec`, `String`, `Box`|`encode_to_vec`|
23//! |derive| Yes | No |||Enables the `BorrowDecode`, `Decode`, `Encode`, `Fingerprint` and `BitPacked` 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//! |zero-copy| No | No |`RelativePtr`, `ZeroArray`, `ZeroSlice`, `ZeroStr`, `ZeroString`|Enables the `relative_ptr` module and the `ZeroCopy` derive macro|Zero-copy nested structures using offsets|
26//! |static-size| No | No |||Enables the `static_size` module, the `bounded` module and the `StaticSize` derive macro|Compile-time size verification|
27//! |async-fiber| No | No |||Enables the `async_fiber` module and async decoding|Async fiber-based encoding/decoding|
28//!
29//! # Which functions to use
30//!
31//! Bincode-next has a couple of pairs of functions that are used in different situations.
32//!
33//! |Situation|Encode|Decode|
34//! |---|---|---
35//! |You're working with [`fs::File`\] or [`net::TcpStream`\]|[`encode_into_std_write`\]|[`decode_from_std_read`\]|
36//! |you're working with in-memory buffers|[`encode_to_vec`\]|[`decode_from_slice`\]|
37//! |You want to use a custom [Reader] and [Writer]|[`encode_into_writer`\]|[`decode_from_reader`\]|
38//! |You're working with pre-allocated buffers or on embedded targets|[`encode_into_slice`\]|[`decode_from_slice`\]|
39//! |You're working with tokio| - |[`decode_async_tokio_with_context`\][`decode_async_tokio`\]|
40//! |You're working with futures-io| - |[`decode_async_with_context`\][`decode_async`\]|
41//!
42//! **Note:** If you're using `serde`, use `bincode_next::serde::...` instead of `bincode_next::...`
43//!
44//! ## Getting Started
45//!
46//! Add `bincode-next` to your `Cargo.toml`:
47//!
48//! ```toml
49//! [dependencies]
50//! bincode-next = "3.1.1"
51//! ```
52//!
53//! ### Basic Encode / Decode
54//!
55//! ```rust
56//! let mut slice = [0u8; 100];
57//!
58//! // You can encode any type that implements `Encode`.
59//! // You can automatically implement this trait on custom types with the `derive` feature.
60//! let input = (
61//! 0u8,
62//! 10u32,
63//! 10000i128,
64//! 'a',
65//! [0u8, 1u8, 2u8, 3u8]
66//! );
67//!
68//! let length = bincode_next::encode_into_slice(
69//! input,
70//! &mut slice,
71//! bincode_next::config::standard()
72//! ).unwrap();
73//!
74//! let slice = &slice[..length];
75//! println!("Bytes written: {:?}", slice);
76//!
77//! // Decoding works the same as encoding.
78//! // The trait used is `Decode`, and can also be automatically implemented with the `derive` feature.
79//! let decoded: (u8, u32, i128, char, [u8; 4]) = bincode_next::decode_from_slice(slice, bincode_next::config::standard()).unwrap().0;
80//!
81//! assert_eq!(decoded, input);
82//! ```
83//!
84//! ```rust
85//! use bincode_next::Decode;
86//! use bincode_next::Encode;
87//! use bincode_next::config;
88//!
89//! #[derive(Encode, Decode, PartialEq, Debug)]
90//! struct Entity {
91//! x: f32,
92//! y: f32,
93//! }
94//!
95//! #[derive(Encode, Decode, PartialEq, Debug)]
96//! struct World(Vec<Entity>);
97//!
98//! fn main() {
99//! let config = config::standard();
100//! let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);
101//!
102//! let encoded: Vec<u8> = bincode_next::encode_to_vec(&world, config).unwrap();
103//! let (decoded, len): (World, usize) =
104//! bincode_next::decode_from_slice(&encoded[..], config).unwrap();
105//!
106//! assert_eq!(world, decoded);
107//! assert_eq!(len, encoded.len());
108//! }
109//! ```
110//!
111//! ---
112//!
113//! ### Serde Compatibility
114//!
115//! Bincode-Next works with any type that already derives `serde::Serialize` /
116//! `serde::Deserialize` — no need to re-derive `Encode`/`Decode` at all. Enable the
117//! `serde` feature and use the `bincode_next::serde::*` entry points.
118//!
119//! ```toml
120//! [dependencies]
121//! bincode-next = { version = "3.1.1", features = ["serde"] }
122//! serde = { version = "1", features = ["derive"] }
123//! ```
124//!
125//! ```rust
126//! # #[cfg(feature = "serde")] {
127//! use serde::Deserialize;
128//! use serde::Serialize;
129//!
130//! // Only serde derives — no Encode/Decode needed.
131//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
132//! struct Config {
133//! host: String,
134//! port: u16,
135//! #[serde(default)]
136//! retries: u8,
137//! }
138//!
139//! fn main() {
140//! let cfg = Config {
141//! host: "localhost".into(),
142//! port: 8080,
143//! retries: 3,
144//! };
145//!
146//! // Encode via serde — honours all #[serde(...)] attributes
147//! let bytes =
148//! bincode_next::serde::encode_to_vec(&cfg, bincode_next::config::standard()).unwrap();
149//!
150//! let (decoded, _): (Config, usize) =
151//! bincode_next::serde::decode_from_slice(&bytes, bincode_next::config::standard())
152//! .unwrap();
153//! assert_eq!(cfg, decoded);
154//! }
155//! # }
156//! ```
157//!
158//! You can also mix: derive both `Serialize` and `Encode` on the same type, then use
159//! `#[bincode(with_serde)]` on individual fields to route specific fields through their
160//! serde impl (useful for types that only implement `Serialize`, not `Encode`).
161//!
162//! ---
163//!
164//! ### Bit-Packing
165//!
166//! Enable bit-packing in your configuration to pack fields at bit granularity. Consecutive
167//! `#[bincode(bits = N)]` fields share bytes — 3 bits + 5 bits = exactly 1 byte on the wire.
168//!
169//! ```rust
170//! use bincode_next::BitPacked;
171//! use bincode_next::config;
172//!
173//! #[derive(BitPacked, PartialEq, Debug)]
174//! struct Telemetry {
175//! #[bincode(bits = 1)]
176//! is_active: bool,
177//! #[bincode(bits = 1)]
178//! has_error: bool,
179//! #[bincode(bits = 3)]
180//! mode: u8,
181//! // ↑ 5 bits total → 1 byte on the wire when bit-packing is enabled
182//! }
183//!
184//! fn main() {
185//! let config = config::standard().with_bit_packing();
186//! let t = Telemetry {
187//! is_active: true,
188//! has_error: false,
189//! mode: 5,
190//! };
191//!
192//! let encoded = bincode_next::encode_to_vec(&t, config).unwrap();
193//! assert_eq!(encoded.len(), 1); // 5 bits packed into 1 byte
194//!
195//! let (decoded, _): (Telemetry, usize) =
196//! bincode_next::decode_from_slice(&encoded, config).unwrap();
197//! assert_eq!(decoded, t);
198//! }
199//! ```
200//!
201//! ---
202//!
203//! ### Zero-Copy Structures
204//!
205//! The `zero-copy` feature lets you build flat byte blobs that can be accessed as typed
206//! Rust references **without any deserialization step** — ideal for memory-mapped files,
207//! shared memory, and IPC.
208//!
209//! `#[derive(ZeroCopy)]` on a `#[repr(C, u8)]` enum generates a companion `*Builder`
210//! type that mirrors every variant. Use `ZeroBuilder` to accumulate bytes, `reserve::<T>()`
211//! to claim space, and `build_to_target()` to write and get back a live typed reference
212//! directly into the buffer.
213//!
214//! ```rust
215//! #[cfg(all(feature = "zero-copy", feature = "alloc"))]
216//! use bincode_next::DeepValidator;
217//! #[cfg(all(feature = "zero-copy", feature = "alloc"))]
218//! use bincode_next::ZeroBuilder;
219//! #[cfg(all(feature = "zero-copy", feature = "alloc"))]
220//! use bincode_next::ZeroCopyBuilder;
221//!
222//! /// Packet layout stored verbatim in the byte blob.
223//! #[cfg(all(feature = "zero-copy", feature = "alloc"))]
224//! #[derive(bincode_derive_next::ZeroCopy, Debug, PartialEq, Eq)]
225//! #[repr(C, u8)]
226//! enum Packet {
227//! Ping,
228//! Data { seq: u32, value: u64 },
229//! Error(u32),
230//! }
231//!
232//! #[cfg(all(feature = "zero-copy", feature = "alloc"))]
233//! fn main() {
234//! let mut builder = ZeroBuilder::new();
235//!
236//! // — Ping ----------------------------------------------------------------
237//! let ping_offset = builder.reserve::<Packet>();
238//! let ping_view = PacketBuilder::Ping.build_to_target(&mut builder, ping_offset);
239//! assert_eq!(ping_view, Packet::Ping);
240//!
241//! // — Data ----------------------------------------------------------------
242//! let data_offset = builder.reserve::<Packet>();
243//! let data_view = PacketBuilder::Data {
244//! seq: 7,
245//! value: 0xDEAD_BEEF,
246//! }
247//! .build_to_target(&mut builder, data_offset);
248//!
249//! match data_view {
250//! | Packet::Data { seq, value } => {
251//! assert_eq!(seq, 7);
252//! assert_eq!(value, 0xDEAD_BEEF);
253//! },
254//! | _ => unreachable!(),
255//! }
256//!
257//! // — Error ---------------------------------------------------------------
258//! let err_offset = builder.reserve::<Packet>();
259//! let err_view = PacketBuilder::Error(404).build_to_target(&mut builder, err_offset);
260//!
261//! match err_view {
262//! | Packet::Error(code) => assert_eq!(code, 404),
263//! | _ => unreachable!(),
264//! }
265//!
266//! // All three packets live in one contiguous allocation — no heap per variant.
267//! let _bytes = builder.finish();
268//! }
269//!
270//! #[cfg(not(all(feature = "zero-copy", feature = "alloc")))]
271//! fn main() {}
272//! ```
273//!
274//! For lower-level use, `RelativePtr<T, OFFSET_SIZE>` lets you embed self-relative
275//! pointers inside any `#[repr(C)]` struct:
276//!
277//! ```rust
278//! #[cfg(feature = "zero-copy")]
279//! use bincode_next::DeepValidator;
280//! #[cfg(feature = "zero-copy")]
281//! use bincode_next::RelativePtr;
282//!
283//! #[repr(align(8))]
284//! struct AlignedBuf<const N: usize>(pub [u8; N]);
285//!
286//! #[cfg(feature = "zero-copy")]
287//! fn relative_ptr_example() {
288//! let mut buf = AlignedBuf([0u8; 12]);
289//! let b = &mut buf.0;
290//!
291//! b[0..4].copy_from_slice(&8i32.to_ne_bytes()); // 4-byte signed offset stored at position 0
292//! b[8..12].copy_from_slice(&42u32.to_ne_bytes()); // target value at position 8
293//!
294//! let ptr = unsafe { &*(b.as_ptr() as *const RelativePtr<u32, 4>) };
295//! // is_valid_deep also validates any nested relative pointers recursively
296//! assert!(ptr.is_valid_deep(b));
297//! assert_eq!(*ptr.get(b).unwrap(), 42);
298//! }
299//! ```
300//!
301//! ---
302//!
303//! ### Compile-time Memory Bounds (`StaticSize`)
304//!
305//! `StaticSize` gives a compile-time upper bound on encoded size — useful for stack
306//! allocation and `no_std` fixed-size buffers. Enable with the `static-size` feature.
307//!
308//! `MAX_SIZE` assumes worst-case varint encoding; `PACKED_MAX_SIZE` is tighter when
309//! bit-packing is active (consecutive `#[bincode(bits = N)]` fields share bytes).
310//!
311//! ```rust
312//! #[cfg(feature = "static-size")]
313//! use bincode_next::BitPacked;
314//! #[cfg(feature = "static-size")]
315//! use bincode_next::StaticSize;
316//!
317//! #[cfg(feature = "static-size")]
318//! #[derive(bincode_next::Encode, bincode_next::Decode, StaticSize, PartialEq, Debug)]
319//! struct Packet {
320//! seq: u32, // varint: up to 5 bytes
321//! data: u64, // varint: up to 9 bytes
322//! }
323//!
324//! #[cfg(feature = "static-size")]
325//! #[derive(BitPacked, StaticSize, PartialEq, Debug)]
326//! struct Flags {
327//! #[bincode(bits = 4)]
328//! kind: u8,
329//! #[bincode(bits = 4)]
330//! priority: u8,
331//! }
332//!
333//! #[cfg(feature = "static-size")]
334//! fn main() {
335//! // Packet: 5 (u32) + 9 (u64) = 14 bytes worst-case
336//! assert_eq!(Packet::MAX_SIZE, 14);
337//!
338//! // Flags without packing: two full u8s = 2 bytes
339//! assert_eq!(Flags::MAX_SIZE, 2);
340//! // Flags with packing: 4+4 bits = 1 byte
341//! assert_eq!(Flags::PACKED_MAX_SIZE, 1);
342//!
343//! // Use MAX_SIZE for a guaranteed-large-enough stack buffer
344//! let val = Packet { seq: 1, data: 42 };
345//! let mut buf = [0u8; Packet::MAX_SIZE];
346//! let _ = bincode_next::encode_into_slice(&val, &mut buf, bincode_next::config::standard())
347//! .unwrap();
348//!
349//! // decode_from_slice_static takes &[u8; N] — pass the whole fixed-size array
350//! let decoded: Packet =
351//! bincode_next::decode_from_slice_static(&buf, bincode_next::config::standard()).unwrap();
352//! assert_eq!(val, decoded);
353//! }
354//!
355//! #[cfg(not(feature = "static-size"))]
356//! fn main() {}
357//! ```
358//!
359//! ---
360//!
361//! ### Schema Fingerprinting
362//!
363//! Fingerprinting embeds a 64-bit schema hash into each encoded message. The hash covers
364//! field names, types, ordering, **and the full configuration** — including format
365//! (Bincode vs CBOR), endianness, integer encoding, and all CBOR options. Any mismatch
366//! between encoder and decoder returns a `DecodeError::SchemaHashMismatch`.
367//!
368//! ```rust
369//! use bincode_next::Decode;
370//! use bincode_next::Encode;
371//! use bincode_next::Fingerprint;
372//! use bincode_next::config;
373//!
374//! #[derive(Encode, Decode, Fingerprint, PartialEq, Debug, Clone)]
375//! struct PlayerV1 {
376//! id: u32,
377//! score: u64,
378//! }
379//!
380//! // Adding a field changes the schema hash → decode_from_slice returns an error
381//! #[derive(Encode, Decode, Fingerprint, PartialEq, Debug, Clone)]
382//! struct PlayerV2 {
383//! id: u32,
384//! score: u64,
385//! level: u32, // new field
386//! }
387//!
388//! fn main() {
389//! let config = config::standard().with_fingerprint();
390//! let player = PlayerV1 { id: 1, score: 9001 };
391//!
392//! let encoded = bincode_next::encode_to_vec(&player, config).unwrap();
393//!
394//! // Decoding as V1 succeeds
395//! let (decoded, _): (PlayerV1, usize) =
396//! bincode_next::decode_from_slice(&encoded, config).unwrap();
397//! assert_eq!(decoded, player);
398//!
399//! // Decoding as V2 fails — schema hashes differ
400//! let result = bincode_next::decode_from_slice::<PlayerV2, _>(&encoded, config);
401//! assert!(result.is_err());
402//!
403//! // Switching formats also changes the hash; cross-format decoding is caught too
404//! let cbor_config = config::standard().with_fingerprint().with_cbor_format();
405//! let result = bincode_next::decode_from_slice::<PlayerV1, _>(&encoded, cbor_config);
406//! assert!(result.is_err());
407//! }
408//! ```
409//!
410//! ---
411//!
412//! ### CBOR Format
413//!
414//! Bincode-Next implements full RFC 8949 CBOR encoding. Switch formats with a single
415//! config call; all existing derives work unchanged.
416//!
417//! ```rust
418//! use bincode_next::Decode;
419//! use bincode_next::Encode;
420//! use bincode_next::config;
421//!
422//! #[derive(Encode, Decode, PartialEq, Debug)]
423//! struct Event {
424//! timestamp: u64,
425//! value: f32,
426//! }
427//!
428//! fn main() {
429//! let config = config::standard().with_cbor_format();
430//! let event = Event {
431//! timestamp: 1_700_000_000,
432//! value: 3.14,
433//! };
434//!
435//! let encoded = bincode_next::encode_to_vec(&event, config).unwrap();
436//! let (decoded, _): (Event, usize) =
437//! bincode_next::decode_from_slice(&encoded, config).unwrap();
438//! assert_eq!(event, decoded);
439//!
440//! // Deterministic (canonical) CBOR for hashing or signing
441//! let det_config = config::standard().with_deterministic_cbor();
442//! let det_encoded = bincode_next::encode_to_vec(&event, det_config).unwrap();
443//! let (det_decoded, _): (Event, usize) =
444//! bincode_next::decode_from_slice(&det_encoded, det_config).unwrap();
445//! assert_eq!(event, det_decoded);
446//! }
447//! ```
448//!
449//! ---
450//!
451//! ### Async Fiber Decoding
452//!
453//! Bincode-Next supports true zero-cost asynchronous decoding using **Unified Fiber-backed
454//! Async (UFA)**. Synchronous `Decode` traits run on a dedicated lightweight fiber stack,
455//! avoiding state-machine code generation overhead entirely.
456//!
457//! ```rust
458//! #[cfg(feature = "async-fiber")]
459//! use bincode_next::Decode;
460//! #[cfg(feature = "async-fiber")]
461//! use bincode_next::Encode;
462//! #[cfg(feature = "async-fiber")]
463//! use bincode_next::config;
464//! #[cfg(feature = "async-fiber")]
465//! use bincode_next::decode_async;
466//! #[cfg(feature = "async-fiber")]
467//! use bincode_next::encode_to_vec;
468//!
469//! #[cfg(feature = "async-fiber")]
470//! #[derive(Encode, Decode, PartialEq, Debug)]
471//! struct Entity {
472//! x: f32,
473//! y: f32,
474//! }
475//!
476//! #[cfg(feature = "async-fiber")]
477//! #[tokio::main]
478//! #[cfg_attr(miri, ignore)]
479//! async fn main() {
480//! if cfg!(miri) {
481//! return;
482//! }
483//!
484//! let entity = Entity { x: 1.0, y: 2.0 };
485//! let encoded = encode_to_vec(&entity, config::standard()).unwrap();
486//!
487//! // Any type implementing `futures_io::AsyncRead` works here.
488//! let mut reader: &[u8] = &encoded;
489//! let decoded: Entity = decode_async(config::standard(), &mut reader).await.unwrap();
490//! assert_eq!(entity, decoded);
491//! }
492//!
493//! #[cfg(not(feature = "async-fiber"))]
494//! fn main() {}
495//! ```
496
497// =========================================================================
498// RUST LINT CONFIGURATION: bincode-next
499// =========================================================================
500
501// -------------------------------------------------------------------------
502// LEVEL 1: CRITICAL ERRORS (Deny)
503// -------------------------------------------------------------------------
504#![deny(
505 // Rust Compiler Errors
506 unreachable_code,
507 improper_ctypes_definitions,
508 future_incompatible,
509 nonstandard_style,
510 rust_2018_idioms,
511 clippy::perf,
512 clippy::correctness,
513 clippy::suspicious,
514 clippy::unwrap_used,
515 clippy::expect_used,
516 clippy::indexing_slicing,
517 clippy::arithmetic_side_effects,
518 clippy::missing_safety_doc,
519 clippy::same_item_push,
520 clippy::implicit_clone,
521 clippy::all,
522 clippy::pedantic,
523 missing_docs,
524 clippy::nursery,
525 clippy::single_call_fn,
526)]
527// -------------------------------------------------------------------------
528// LEVEL 2: STYLE WARNINGS (Warn)
529// -------------------------------------------------------------------------
530#![warn(
531 // For `no-std` Situation Issues
532 dead_code,
533 warnings,
534 unsafe_code,
535 clippy::dbg_macro,
536 clippy::todo,
537 clippy::unnecessary_safety_comment
538)]
539// -------------------------------------------------------------------------
540// LEVEL 3: ALLOW/IGNORABLE (Allow)
541// -------------------------------------------------------------------------
542#![allow(
543 clippy::restriction,
544 clippy::inline_always,
545 unused_doc_comments,
546 clippy::cast_possible_truncation,
547 clippy::cast_sign_loss,
548 clippy::cast_possible_wrap,
549 clippy::empty_line_after_doc_comments
550)]
551#![crate_name = "bincode_next"]
552#![crate_type = "rlib"]
553
554#[cfg(feature = "alloc")]
555extern crate alloc;
556#[cfg(any(feature = "std", test))]
557extern crate std;
558
559mod atomic;
560#[doc(hidden)]
561pub mod error_path;
562mod features;
563#[doc(hidden)]
564pub mod utils;
565pub(crate) mod varint;
566
567use de::Decoder;
568use de::read::Reader;
569use enc::write::Writer;
570
571#[cfg(any(
572 feature = "alloc",
573 feature = "std",
574 feature = "derive",
575 feature = "serde",
576 feature = "zero-copy",
577 feature = "static-size"
578))]
579pub use features::*;
580
581/// The major version of the bincode library.
582pub const BINCODE_MAJOR_VERSION: u64 = 3;
583
584#[doc(hidden)]
585pub use rapidhash;
586
587pub mod config;
588/// Fingerprinting support for schema verification.
589pub mod fingerprint;
590
591#[macro_use]
592pub mod de;
593pub mod enc;
594#[macro_use]
595pub mod error;
596
597#[cfg(feature = "static-size")]
598pub use static_size::StaticSize;
599
600pub use de::BorrowDecode;
601pub use de::Decode;
602pub use enc::Encode;
603pub use fingerprint::Fingerprint;
604/// Relative pointer system for zero-copy nested structures
605#[cfg(feature = "zero-copy")]
606pub mod zero_copy {
607 pub use crate::relative_ptr::*;
608}
609#[cfg(feature = "zero-copy")]
610#[doc(hidden)]
611pub use crate::relative_ptr::*;
612
613use config::Config;
614use config::internal::InternalFingerprintGuard;
615
616/// Encode the given value into the given slice. Returns the amount of bytes that have been written.
617///
618/// See the [config] module for more information on configurations.
619///
620/// # Errors
621///
622/// Returns an `EncodeError` if the slice is too small or the value cannot be encoded.
623///
624/// [config]: config/index.html
625#[inline]
626pub fn encode_into_slice<E: enc::Encode, C: Config>(
627 val: E,
628 dst: &mut [u8],
629 config: C,
630) -> Result<usize, error::EncodeError>
631where
632 C::Mode: config::InternalFingerprintGuard<E, C>,
633{
634 let mut writer = enc::write::SliceWriter::new(dst);
635 C::Mode::encode_check(&config, &mut writer)?;
636 let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
637 val.encode(&mut encoder)?;
638 Ok(encoder.into_writer().bytes_written())
639}
640
641/// Encode the given value into a custom [`Writer`\].
642///
643/// See the [config] module for more information on configurations.
644///
645/// # Errors
646///
647/// Returns an `EncodeError` if the writer fails or the value cannot be encoded.
648///
649/// [config]: config/index.html
650#[inline]
651pub fn encode_into_writer<E: enc::Encode, W: Writer, C: Config>(
652 val: E,
653 mut writer: W,
654 config: C,
655) -> Result<(), error::EncodeError>
656where
657 C::Mode: config::InternalFingerprintGuard<E, C>,
658{
659 C::Mode::encode_check(&config, &mut writer)?;
660 let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
661 val.encode(&mut encoder)?;
662 Ok(())
663}
664
665/// Attempt to decode a given type `D` from the given slice. Returns the decoded output and the amount of bytes read.
666///
667/// Note that this does not work with borrowed types like `&str` or `&[u8]`. For that use [`borrow_decode_from_slice`\].
668///
669/// See the [config] module for more information on configurations.
670///
671/// # Errors
672///
673/// Returns a `DecodeError` if the slice is too small or the data is invalid.
674///
675/// [config]: config/index.html
676#[inline(always)]
677pub fn decode_from_slice<D: de::Decode<()>, C: Config>(
678 src: &[u8],
679 config: C,
680) -> Result<(D, usize), error::DecodeError>
681where
682 C::Mode: config::InternalFingerprintGuard<D, C>,
683{
684 decode_from_slice_with_context(src, config, ())
685}
686
687/// Attempt to decode a given type `D` from the given slice with `Context`. Returns the decoded output and the amount of bytes read.
688///
689/// Note that this does not work with borrowed types like `&str` or `&[u8]`. For that use [`borrow_decode_from_slice`\].
690///
691/// See the [config] module for more information on configurations.
692///
693/// # Errors
694///
695/// Returns a `DecodeError` if the slice is too small or the data is invalid.
696///
697/// [config]: config/index.html
698#[inline]
699pub fn decode_from_slice_with_context<Context, D: de::Decode<Context>, C: Config>(
700 src: &[u8],
701 config: C,
702 context: Context,
703) -> Result<(D, usize), error::DecodeError>
704where
705 C::Mode: config::InternalFingerprintGuard<D, C>,
706{
707 let mut reader = de::read::SliceReader::new(src);
708 C::Mode::decode_check(&config, &mut reader)?;
709 let mut decoder = de::DecoderImpl::<_, C, Context>::new(reader, config, context);
710 let result = D::decode(&mut decoder)?;
711 let bytes_read = src.len() - decoder.reader().slice.len();
712 Ok((result, bytes_read))
713}
714
715/// Attempt to decode a given type `D` from the given slice. Returns the decoded output and the amount of bytes read.
716///
717/// See the [config] module for more information on configurations.
718///
719/// # Errors
720///
721/// Returns a `DecodeError` if the slice is too small or the data is invalid.
722///
723/// [config]: config/index.html
724#[inline(always)]
725pub fn borrow_decode_from_slice<'a, D: de::BorrowDecode<'a, ()>, C: Config>(
726 src: &'a [u8],
727 config: C,
728) -> Result<(D, usize), error::DecodeError>
729where
730 C::Mode: config::InternalFingerprintGuard<D, C>,
731{
732 borrow_decode_from_slice_with_context(src, config, ())
733}
734
735/// Attempt to decode a given type `D` from the given slice with `Context`. Returns the decoded output and the amount of bytes read.
736///
737/// See the [config] module for more information on configurations.
738///
739/// # Errors
740///
741/// Returns a `DecodeError` if the slice is too small or the data is invalid.
742///
743/// [config]: config/index.html
744#[inline]
745pub fn borrow_decode_from_slice_with_context<
746 'a,
747 Context,
748 D: de::BorrowDecode<'a, Context>,
749 C: Config,
750>(
751 src: &'a [u8],
752 config: C,
753 context: Context,
754) -> Result<(D, usize), error::DecodeError>
755where
756 C::Mode: config::InternalFingerprintGuard<D, C>,
757{
758 let mut reader = de::read::SliceReader::new(src);
759 C::Mode::decode_check(&config, &mut reader)?;
760 let mut decoder = de::DecoderImpl::<_, C, Context>::new(reader, config, context);
761 let result = D::borrow_decode(&mut decoder)?;
762 let bytes_read = src.len() - decoder.reader().slice.len();
763 Ok((result, bytes_read))
764}
765
766/// Attempt to decode a given type `D` from the given slice with a compile-time bound check.
767///
768/// This function ensures that the target type `D` cannot exceed the provided buffer capacity `CAP` at compile-time.
769///
770/// # Errors
771///
772/// Returns a `DecodeError` if the slice contains invalid data.
773#[cfg(feature = "static-size")]
774#[inline(always)]
775pub fn decode_from_slice_static<D, const CAP: usize, C>(
776 src: &[u8; CAP],
777 config: C,
778) -> Result<D, error::DecodeError>
779where
780 D: de::Decode<()> + static_size::StaticSize,
781 C: Config,
782 C::Mode: config::InternalFingerprintGuard<D, C>,
783{
784 const {
785 assert!(D::MAX_SIZE <= CAP, "Buffer too small for target type");
786 }
787 let (val, _) = decode_from_slice(src, config)?;
788 Ok(val)
789}
790
791/// Attempt to decode a given type `D` from the given slice with a compile-time bound check and a
792/// decoding context.
793///
794/// This function ensures that the target type `D` cannot exceed the provided buffer capacity `CAP`
795/// at compile-time.
796///
797/// # Errors
798///
799/// Returns a `DecodeError` if the slice contains invalid data.
800#[cfg(feature = "static-size")]
801#[inline(always)]
802pub fn decode_from_slice_static_with_context<Context, D, const CAP: usize, C>(
803 src: &[u8; CAP],
804 config: C,
805 context: Context,
806) -> Result<D, error::DecodeError>
807where
808 D: de::Decode<Context> + static_size::StaticSize,
809 C: Config,
810 C::Mode: config::InternalFingerprintGuard<D, C>,
811{
812 const {
813 assert!(D::MAX_SIZE <= CAP, "Buffer too small for target type");
814 }
815 let (val, _) = decode_from_slice_with_context(src, config, context)?;
816 Ok(val)
817}
818
819/// Attempt to decode a given type `D` from the given slice with a compile-time bound check.
820///
821/// This function ensures that the target type `D` cannot exceed the provided buffer capacity `CAP`
822/// at compile-time.
823///
824/// # Errors
825///
826/// Returns a `DecodeError` if the slice contains invalid data.
827#[cfg(feature = "static-size")]
828#[inline(always)]
829pub fn borrow_decode_from_slice_static<'a, D, const CAP: usize, C>(
830 src: &'a [u8; CAP],
831 config: C,
832) -> Result<D, error::DecodeError>
833where
834 D: de::BorrowDecode<'a, ()> + static_size::StaticSize,
835 C: Config,
836 C::Mode: config::InternalFingerprintGuard<D, C>,
837{
838 const {
839 assert!(D::MAX_SIZE <= CAP, "Buffer too small for target type");
840 }
841 let (val, _) = borrow_decode_from_slice(src, config)?;
842 Ok(val)
843}
844
845/// Attempt to borrow-decode a given type `D` from the given slice with a compile-time bound check
846/// and a decoding context.
847///
848/// This function ensures that the target type `D` cannot exceed the provided buffer capacity `CAP`
849/// at compile-time.
850///
851/// # Errors
852///
853/// Returns a `DecodeError` if the slice contains invalid data.
854#[cfg(feature = "static-size")]
855#[inline(always)]
856pub fn borrow_decode_from_slice_static_with_context<'a, Context, D, const CAP: usize, C>(
857 src: &'a [u8; CAP],
858 config: C,
859 context: Context,
860) -> Result<D, error::DecodeError>
861where
862 D: de::BorrowDecode<'a, Context> + static_size::StaticSize,
863 C: Config,
864 C::Mode: config::InternalFingerprintGuard<D, C>,
865{
866 const {
867 assert!(D::MAX_SIZE <= CAP, "Buffer too small for target type");
868 }
869 let (val, _) = borrow_decode_from_slice_with_context(src, config, context)?;
870 Ok(val)
871}
872
873/// Attempt to decode a given type `D` from the given [`Reader`\].
874///
875/// See the [config] module for more information on configurations.
876///
877/// # Errors
878///
879/// Returns a `DecodeError` if the reader fails or the data is invalid.
880///
881/// [config]: config/index.html
882#[inline]
883pub fn decode_from_reader<D: de::Decode<()>, R: Reader, C: Config>(
884 mut reader: R,
885 config: C,
886) -> Result<D, error::DecodeError>
887where
888 C::Mode: config::InternalFingerprintGuard<D, C>,
889{
890 C::Mode::decode_check(&config, &mut reader)?;
891 let mut decoder = de::DecoderImpl::<_, C, ()>::new(reader, config, ());
892 D::decode(&mut decoder)
893}
894
895/// Attempt to decode a given type `T` from the given async reader safely using a non-blocking fiber.
896///
897/// Requires the `async-fiber` feature.
898///
899/// # Errors
900///
901/// Returns a `DecodeError` if the reader fails or the data is invalid.
902///
903/// [config]: config/index.html
904#[cfg(feature = "async-fiber")]
905#[inline(always)]
906pub async fn decode_async<T, R, C>(
907 config: C,
908 reader: R,
909) -> Result<T, crate::error::DecodeError>
910where
911 T: crate::Decode<()>,
912 R: futures_io::AsyncRead + std::marker::Unpin,
913 C: crate::config::Config,
914 C::Mode: crate::config::InternalFingerprintGuard<T, C>,
915{
916 decode_async_with_context::<T, R, C, ()>(config, reader, ()).await
917}
918
919/// Attempt to decode a given type `T` from the given async reader using a non-blocking fiber and a context.
920///
921/// This is the primary implementation for runtimes that use the `futures-io` traits (e.g. `async-std`, `smol`).
922///
923/// Requires the `async-fiber` feature.
924///
925/// # Errors
926///
927/// Returns a `DecodeError` if the reader fails or the data is invalid.
928///
929/// [config]: config/index.html
930#[cfg(feature = "async-fiber")]
931#[inline]
932pub async fn decode_async_with_context<T, R, C, Context>(
933 config: C,
934 reader: R,
935 context: Context,
936) -> Result<T, crate::error::DecodeError>
937where
938 T: crate::Decode<Context>,
939 R: futures_io::AsyncRead + std::marker::Unpin,
940 C: crate::config::Config,
941 C::Mode: crate::config::InternalFingerprintGuard<T, C>,
942{
943 let bridge = crate::de::async_fiber::AsyncFiberBridge::new(reader);
944 bridge
945 .run(move |fiber_reader| {
946 C::Mode::decode_check(&config, fiber_reader)?;
947 let mut decoder =
948 crate::de::DecoderImpl::<_, C, Context>::new(fiber_reader, config, context);
949 T::decode(&mut decoder)
950 })
951 .await
952}
953
954/// Attempt to decode a given type `T` from the given tokio async reader safely using a non-blocking fiber.
955///
956/// Requires the `tokio` and `async-fiber` features.
957///
958/// # Errors
959///
960/// Returns a `DecodeError` if the reader fails or the data is invalid.
961///
962/// [config]: config/index.html
963#[cfg(all(feature = "tokio", feature = "async-fiber"))]
964#[inline(always)]
965pub async fn decode_async_tokio<T, R, C>(
966 config: C,
967 reader: R,
968) -> Result<T, crate::error::DecodeError>
969where
970 T: crate::Decode<()>,
971 R: tokio::io::AsyncRead + std::marker::Unpin,
972 C: crate::config::Config,
973 C::Mode: crate::config::InternalFingerprintGuard<T, C>,
974{
975 decode_async_tokio_with_context::<T, R, C, ()>(config, reader, ()).await
976}
977
978/// Attempt to decode a given type `T` from the given tokio async reader using a non-blocking fiber and a context.
979///
980/// Requires the `tokio` and `async-fiber` features.
981///
982/// # Errors
983///
984/// Returns a `DecodeError` if the reader fails or the data is invalid.
985///
986/// [config]: config/index.html
987#[cfg(all(feature = "tokio", feature = "async-fiber"))]
988#[inline(always)]
989pub async fn decode_async_tokio_with_context<T, R, C, Context>(
990 config: C,
991 reader: R,
992 context: Context,
993) -> Result<T, crate::error::DecodeError>
994where
995 T: crate::Decode<Context>,
996 R: tokio::io::AsyncRead + std::marker::Unpin,
997 C: crate::config::Config,
998 C::Mode: crate::config::InternalFingerprintGuard<T, C>,
999{
1000 let reader = crate::de::async_fiber::TokioReader(reader);
1001 decode_async_with_context::<T, _, C, Context>(config, reader, context).await
1002}
1003
1004/// Attempt to decode a given serde-compatible type `T` from the given async reader safely using a non-blocking fiber.
1005///
1006/// Requires the `async-fiber` and `serde` features.
1007///
1008/// # Errors
1009///
1010/// Returns a `DecodeError` if the reader fails or the data is invalid.
1011///
1012/// [config]: config/index.html
1013#[cfg(all(feature = "async-fiber", feature = "serde"))]
1014#[inline(always)]
1015#[doc(hidden)]
1016pub async fn decode_serde_async<'de, T, R, C>(
1017 config: C,
1018 reader: R,
1019) -> Result<T, crate::error::DecodeError>
1020where
1021 T: ::serde::Deserialize<'de>,
1022 R: futures_io::AsyncRead + std::marker::Unpin,
1023 C: crate::config::Config,
1024{
1025 decode_serde_async_with_context::<'de, T, R, C, ()>(config, reader, ()).await
1026}
1027
1028/// Attempt to decode a given serde-compatible type `T` from the given async reader using a non-blocking fiber and a context.
1029///
1030/// Requires the `async-fiber` and `serde` features.
1031///
1032/// # Errors
1033///
1034/// Returns a `DecodeError` if the reader fails or the data is invalid.
1035///
1036/// [config]: config/index.html
1037#[cfg(all(feature = "async-fiber", feature = "serde"))]
1038#[inline]
1039#[doc(hidden)]
1040pub async fn decode_serde_async_with_context<'de, T, R, C, Context>(
1041 config: C,
1042 reader: R,
1043 context: Context,
1044) -> Result<T, crate::error::DecodeError>
1045where
1046 T: ::serde::Deserialize<'de>,
1047 R: futures_io::AsyncRead + std::marker::Unpin,
1048 C: crate::config::Config,
1049{
1050 let bridge = crate::de::async_fiber::AsyncFiberBridge::new(reader);
1051 bridge
1052 .run(move |fiber_reader| {
1053 let decoder =
1054 crate::de::DecoderImpl::<_, C, Context>::new(fiber_reader, config, context);
1055 let mut serde_decoder = crate::features::serde::OwnedSerdeDecoder { de: decoder };
1056 T::deserialize(serde_decoder.as_deserializer())
1057 })
1058 .await
1059}
1060
1061/// Attempt to decode a given serde-compatible type `T` from the given tokio async reader safely using a non-blocking fiber.
1062///
1063/// Requires the `tokio`, `async-fiber` and `serde` features.
1064///
1065/// # Errors
1066///
1067/// Returns a `DecodeError` if the reader fails or the data is invalid.
1068///
1069/// [config]: config/index.html
1070#[cfg(all(feature = "tokio", feature = "async-fiber", feature = "serde"))]
1071#[inline(always)]
1072#[doc(hidden)]
1073pub async fn decode_serde_tokio_async<'de, T, R, C>(
1074 config: C,
1075 reader: R,
1076) -> Result<T, crate::error::DecodeError>
1077where
1078 T: ::serde::Deserialize<'de>,
1079 R: tokio::io::AsyncRead + std::marker::Unpin,
1080 C: crate::config::Config,
1081{
1082 decode_serde_tokio_async_with_context::<'de, T, R, C, ()>(config, reader, ()).await
1083}
1084
1085/// Attempt to decode a given serde-compatible type `T` from the given tokio async reader using a non-blocking fiber and a context.
1086///
1087/// Requires the `tokio`, `async-fiber` and `serde` features.
1088///
1089/// # Errors
1090///
1091/// Returns a `DecodeError` if the reader fails or the data is invalid.
1092///
1093/// [config]: config/index.html
1094#[cfg(all(feature = "tokio", feature = "async-fiber", feature = "serde"))]
1095#[inline(always)]
1096#[doc(hidden)]
1097pub async fn decode_serde_tokio_async_with_context<'de, T, R, C, Context>(
1098 config: C,
1099 reader: R,
1100 context: Context,
1101) -> Result<T, crate::error::DecodeError>
1102where
1103 T: ::serde::Deserialize<'de>,
1104 R: tokio::io::AsyncRead + std::marker::Unpin,
1105 C: crate::config::Config,
1106{
1107 let reader = crate::de::async_fiber::TokioReader(reader);
1108 decode_serde_async_with_context::<'de, T, _, C, Context>(config, reader, context).await
1109}
1110
1111#[cfg(all(feature = "alloc", feature = "derive", doc))]
1112pub mod spec {
1113 #![doc = include_str!("../docs/spec.md")]
1114}
1115
1116#[cfg(doc)]
1117pub mod migration_guide {
1118 #![doc = include_str!("../docs/migration_guide.md")]
1119}
1120
1121// Test the examples in readme.md
1122#[cfg(all(
1123 feature = "std",
1124 feature = "derive",
1125 feature = "serde",
1126 feature = "async-fiber",
1127 feature = "zero-copy",
1128 feature = "static-size",
1129 doctest
1130))]
1131#[cfg_attr(miri, ignore)]
1132mod readme {
1133 #![doc = include_str!("../README.md")]
1134 #![doc = include_str!("../derive/readme.md")]
1135}