Skip to main content

rustbinary/
config.rs

1use alloc::vec::Vec;
2#[cfg(feature = "std")]
3use std::io::{Read, Write};
4
5use crate::{decoder, error::Result, ser, tags::MAX_DEPTH};
6
7/// Conservative default byte limit for one encoded or decoded Core value.
8pub const DEFAULT_SIZE_LIMIT: u64 = 64 * 1024 * 1024;
9
10/// Conservative default element limit for one sequence or map.
11pub const DEFAULT_COLLECTION_LIMIT: u64 = 1_000_000;
12
13#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
14/// Byte order for fixed-width values and varint payloads.
15pub enum Endian {
16    /// Least-significant byte first.
17    #[default]
18    Little,
19    /// Most-significant byte first.
20    Big,
21    /// The compilation target's byte order.
22    Native,
23}
24
25impl Endian {
26    pub(crate) const fn little(self) -> bool {
27        match self {
28            Self::Little => true,
29            Self::Big => false,
30            Self::Native => cfg!(target_endian = "little"),
31        }
32    }
33}
34
35#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
36/// Integer representation used by the codec.
37pub enum IntEncoding {
38    /// Always use the integer type's full width.
39    Fixed,
40    /// Use compact marker-prefixed widths and ZigZag signed values.
41    #[default]
42    Variable,
43}
44
45#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
46/// Policy for bytes following a decoded top-level value.
47pub enum TrailingBytes {
48    /// Leave unread bytes untouched.
49    Allow,
50    /// Report unread bytes as an error.
51    #[default]
52    Reject,
53}
54
55/// The three wire profiles the codec offers for the same Rust value.
56///
57/// They coexist and compose; the profile is a property of the chosen
58/// configuration, never of the type itself.
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60pub enum BinaryProfile {
61    /// Field-name-bearing, type-tagged, terminator-delimited stream.
62    ///
63    /// Backs dynamic [`nextjson::Value`]s, untagged enums, and
64    /// `FormatEncoder`-driven types. Compactness is secondary to flexibility.
65    SelfDescribing,
66    /// Schema-guided compact stream.
67    ///
68    /// No per-value tags, no field names, length-prefixed containers. See
69    /// [`crate::compact`] for the wire layout. Enabled with
70    /// [`Config::with_compact_format`].
71    CompactSchema,
72    /// Stable numeric field IDs with per-field lengths for forward compatibility.
73    ///
74    /// Enabled with [`Config::with_schema_evolution`].
75    Evolution,
76}
77
78#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79/// Copyable configuration describing a complete wire profile.
80pub struct Config {
81    pub(crate) endian: Endian,
82    pub(crate) integers: IntEncoding,
83    pub(crate) trailing: TrailingBytes,
84    pub(crate) limit: Option<u64>,
85    pub(crate) collection_limit: Option<u64>,
86    pub(crate) depth_limit: usize,
87    pub(crate) value_limit: Option<u64>,
88    pub(crate) decode_work_limit: Option<u64>,
89}
90
91impl Default for Config {
92    fn default() -> Self {
93        Self::standard()
94    }
95}
96
97impl Config {
98    /// Creates the self-describing profile with variable integers and strict trailing bytes.
99    pub const fn standard() -> Self {
100        Self {
101            endian: Endian::Little,
102            integers: IntEncoding::Variable,
103            trailing: TrailingBytes::Reject,
104            limit: Some(DEFAULT_SIZE_LIMIT),
105            collection_limit: Some(DEFAULT_COLLECTION_LIMIT),
106            depth_limit: MAX_DEPTH,
107            value_limit: Some(DEFAULT_COLLECTION_LIMIT),
108            decode_work_limit: Some(DEFAULT_SIZE_LIMIT),
109        }
110    }
111    /// Creates the historical unbounded fixed-width RustBinary profile.
112    ///
113    /// This profile has no byte or collection limits, so it must only be used
114    /// with trusted, in-memory data. It is not a safe default for network
115    /// input. Decompression remains bounded even here: the compression wrapper
116    /// caps the decompressed size at [`DEFAULT_SIZE_LIMIT`] when no explicit
117    /// limit is configured. Prefer [`Config::standard`] and set explicit
118    /// [`Config::with_limit`] / [`Config::with_collection_limit`] values at
119    /// every trust boundary.
120    pub const fn legacy() -> Self {
121        Self {
122            endian: Endian::Little,
123            integers: IntEncoding::Fixed,
124            trailing: TrailingBytes::Allow,
125            limit: None,
126            collection_limit: None,
127            depth_limit: MAX_DEPTH,
128            value_limit: None,
129            decode_work_limit: None,
130        }
131    }
132    /// Selects little endian.
133    pub const fn with_little_endian(mut self) -> Self {
134        self.endian = Endian::Little;
135        self
136    }
137    /// Selects big endian.
138    pub const fn with_big_endian(mut self) -> Self {
139        self.endian = Endian::Big;
140        self
141    }
142    /// Selects the compilation target's native byte order.
143    pub const fn with_native_endian(mut self) -> Self {
144        self.endian = Endian::Native;
145        self
146    }
147    /// Selects fixed-width integer encoding.
148    pub const fn with_fixint_encoding(mut self) -> Self {
149        self.integers = IntEncoding::Fixed;
150        self
151    }
152    /// Selects variable-width integer encoding.
153    pub const fn with_varint_encoding(mut self) -> Self {
154        self.integers = IntEncoding::Variable;
155        self
156    }
157    /// Limits one encoded or decoded value to `limit` consumed bytes.
158    pub const fn with_limit(mut self, limit: u64) -> Self {
159        self.limit = Some(limit);
160        self.collection_limit = Some(match self.collection_limit {
161            Some(current) if current < limit => current,
162            _ => limit,
163        });
164        self
165    }
166    /// Removes the consumed-byte limit.
167    ///
168    /// # Security
169    ///
170    /// Other parser limits remain enabled. The LZ compression wrapper retains
171    /// a [`DEFAULT_SIZE_LIMIT`] output cap; other profiles have their own
172    /// policies. Keep an explicit byte limit for untrusted inputs.
173    pub const fn with_no_limit(mut self) -> Self {
174        self.limit = None;
175        self
176    }
177    /// Limits the number of elements in one sequence or map.
178    pub const fn with_collection_limit(mut self, limit: u64) -> Self {
179        self.collection_limit = Some(limit);
180        self
181    }
182    /// Removes the collection element limit.
183    pub const fn with_no_collection_limit(mut self) -> Self {
184        self.collection_limit = None;
185        self
186    }
187    /// Caps tokens read across the entire self-describing decode, including
188    /// object keys, skipped fields and speculative retries. Terminators do not
189    /// count. This is independent of the per-collection limit and heap usage.
190    pub const fn with_value_limit(mut self, limit: u64) -> Self {
191        self.value_limit = Some(limit);
192        self
193    }
194    /// Caps bytes examined by the self-describing decoder, counting rereads
195    /// after backtracking again. Custom trait computation is outside this limit.
196    pub const fn with_decode_work_limit(mut self, limit: u64) -> Self {
197        self.decode_work_limit = Some(limit);
198        self
199    }
200    /// Returns the self-describing decoder's global token limit.
201    pub const fn value_limit(self) -> Option<u64> {
202        self.value_limit
203    }
204    /// Returns the self-describing decoder's cumulative byte-read limit.
205    pub const fn decode_work_limit(self) -> Option<u64> {
206        self.decode_work_limit
207    }
208    /// Caps the maximum container nesting depth for one encoded or decoded value.
209    ///
210    /// Both the encoder and the decoder fail fast when a container is entered
211    /// at the limit, so hostile deep-nesting input is rejected instead of
212    /// walked. The value is clamped to the crate-wide `MAX_DEPTH` ceiling
213    /// (currently 128), which also sizes the internal per-depth accounting
214    /// tables, so a caller-supplied larger limit cannot cause out-of-bounds
215    /// indexing.
216    pub const fn with_depth_limit(mut self, limit: usize) -> Self {
217        let clamped = if limit > MAX_DEPTH { MAX_DEPTH } else { limit };
218        self.depth_limit = clamped;
219        self
220    }
221    /// Returns the configured container nesting depth cap.
222    pub const fn depth_limit(self) -> usize {
223        self.depth_limit
224    }
225    /// Returns the configured consumed-byte limit, if any.
226    pub const fn limit(self) -> Option<u64> {
227        self.limit
228    }
229    /// Returns the configured per-collection element limit, if any.
230    pub const fn collection_limit(self) -> Option<u64> {
231        self.collection_limit
232    }
233    /// Adds a versioned schema fingerprint header to every value.
234    #[cfg(feature = "fingerprint")]
235    pub const fn with_fingerprint(self) -> crate::FingerprintedConfig {
236        crate::FingerprintedConfig::new(self)
237    }
238    /// Selects the schema-guided compact profile.
239    ///
240    /// Carries over this config's resource policies (`limit`,
241    /// `collection_limit`, `depth_limit`, `trailing`). The compact wire is
242    /// always little-endian marker-varint; `Endian` and `IntEncoding` do not
243    /// alter it. Returns [`BinaryProfile::CompactSchema`].
244    #[cfg(feature = "compact")]
245    pub const fn with_compact_format(self) -> crate::CompactConfig {
246        crate::CompactConfig::new(self)
247    }
248    /// Returns the wire profile this configuration produces.
249    pub const fn profile(self) -> BinaryProfile {
250        BinaryProfile::SelfDescribing
251    }
252    /// Switches to the RFC 8949 CBOR format while retaining resource policies.
253    #[cfg(feature = "cbor")]
254    pub const fn with_cbor_format(self) -> crate::CborConfig {
255        crate::CborConfig::new(self)
256    }
257    /// Wraps binary payloads in an in-tree LZ77 compression frame.
258    #[cfg(feature = "compression")]
259    pub const fn with_compression(self, level: i32) -> crate::CompressedConfig {
260        crate::CompressedConfig::binary(self, level)
261    }
262    /// Legacy name for [`Config::with_compression`].
263    ///
264    /// The frame is the in-tree LZ77 codec, not Zstandard; the old name is
265    /// kept only for source compatibility and will not change bytes.
266    #[cfg(feature = "compression")]
267    #[deprecated(note = "use `with_compression`; the frame is the in-tree LZ77 codec")]
268    pub const fn with_zstd_compression(self, level: i32) -> crate::CompressedConfig {
269        crate::CompressedConfig::binary(self, level)
270    }
271    /// Encrypts binary payloads using XChaCha20-Poly1305 and random nonces.
272    #[cfg(feature = "encryption")]
273    pub fn with_encryption(self, key: crate::EncryptionKey) -> crate::EncryptedConfig {
274        crate::EncryptedConfig::binary(self, key)
275    }
276    /// Selects the generated bit-packed representation for [`crate::BitPack`] types.
277    #[cfg(feature = "bit-packing")]
278    pub const fn with_bit_packing(self) -> crate::BitPackedConfig {
279        crate::BitPackedConfig::new(self)
280    }
281    /// Enables data-aware integer, string, and numeric-collection encodings.
282    #[cfg(feature = "adaptive")]
283    pub const fn with_adaptive_encoding(self) -> crate::AdaptiveConfig {
284        crate::AdaptiveConfig::new(self.with_varint_encoding().with_little_endian())
285    }
286    /// Enables framed static-model rANS entropy coding.
287    #[cfg(feature = "entropy")]
288    pub const fn with_entropy_encoding(self) -> crate::EntropyConfig {
289        crate::EntropyConfig::new(self.with_varint_encoding().with_little_endian())
290    }
291    /// Enables baseline-relative differential frames for state exchange.
292    #[cfg(feature = "reconcile")]
293    pub const fn with_delta_encoding(self) -> crate::DeltaConfig {
294        crate::DeltaConfig::new(self.with_varint_encoding().with_little_endian())
295    }
296    /// Enables ordered parallel batch serialization and deserialization.
297    #[cfg(feature = "parallel")]
298    pub fn with_parallel_serialization(self) -> crate::ParallelConfig {
299        crate::ParallelConfig::new(self)
300    }
301    /// Wraps values in a stable-field-ID schema evolution frame.
302    #[cfg(feature = "schema-evolution")]
303    pub const fn with_schema_evolution(self) -> crate::EvolutionConfig {
304        crate::EvolutionConfig::new(self)
305    }
306    /// Rejects bytes left after a top-level value.
307    pub const fn reject_trailing_bytes(mut self) -> Self {
308        self.trailing = TrailingBytes::Reject;
309        self
310    }
311    /// Allows bytes left after a top-level value.
312    pub const fn allow_trailing_bytes(mut self) -> Self {
313        self.trailing = TrailingBytes::Allow;
314        self
315    }
316    /// Serializes a value into a new vector.
317    pub fn serialize<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<Vec<u8>> {
318        ser::to_vec(value, self)
319    }
320    /// Serializes a value directly into `writer`.
321    #[cfg(feature = "std")]
322    pub fn serialize_into<W: Write, T: nextjson::NsonSerialize + ?Sized>(
323        self,
324        writer: W,
325        value: &T,
326    ) -> Result<()> {
327        crate::adapters::serialize_into(self, writer, value)
328    }
329    /// Serializes into a caller-owned slice without codec-owned heap allocation.
330    ///
331    /// If capacity is insufficient, the error reports the exact required size.
332    /// The prefix that fits in `output` is written before that error is returned.
333    /// A user-provided [`nextjson::NsonSerialize`] implementation may still allocate internally.
334    pub fn serialize_into_slice<T: nextjson::NsonSerialize + ?Sized>(
335        self,
336        output: &mut [u8],
337        value: &T,
338    ) -> Result<usize> {
339        ser::to_slice(output, value, self)
340    }
341    /// Calculates the exact encoded size without retaining encoded bytes.
342    pub fn serialized_size<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<u64> {
343        ser::size(value, self)
344    }
345    /// Deserializes a value that may borrow from `input`.
346    pub fn deserialize<'de, T: nextjson::NsonDeserialize<'de>>(
347        self,
348        input: &'de [u8],
349    ) -> Result<T> {
350        decoder::from_slice(input, self)
351    }
352    /// Reads and deserializes an owned value.
353    #[cfg(feature = "std")]
354    pub fn deserialize_from<R: Read, T: for<'de> nextjson::NsonDeserialize<'de>>(
355        self,
356        reader: R,
357    ) -> Result<T> {
358        crate::adapters::deserialize_from(self, reader)
359    }
360    /// Probes the exact structural footprint of the next value in `input`
361    /// without materializing it.
362    ///
363    /// Returns the exact byte length, container count, element count, and
364    /// maximum nesting depth of one value, honoring the same limits and
365    /// malformed-input rejection as [`Config::deserialize`]. The walk performs
366    /// no allocation, so it is a safe preflight probe for hostile frames.
367    pub fn probe(self, input: &[u8]) -> Result<crate::Probe> {
368        crate::probe::probe(self, input)
369    }
370}
371
372/// Fluent compatibility facade implemented by concrete option values.
373#[allow(missing_docs)]
374pub trait Options: Sized {
375    fn config(self) -> Config;
376    fn with_little_endian(self) -> Config {
377        self.config().with_little_endian()
378    }
379    fn with_big_endian(self) -> Config {
380        self.config().with_big_endian()
381    }
382    fn with_native_endian(self) -> Config {
383        self.config().with_native_endian()
384    }
385    fn with_fixint_encoding(self) -> Config {
386        self.config().with_fixint_encoding()
387    }
388    fn with_varint_encoding(self) -> Config {
389        self.config().with_varint_encoding()
390    }
391    fn with_limit(self, limit: u64) -> Config {
392        self.config().with_limit(limit)
393    }
394    fn with_no_limit(self) -> Config {
395        self.config().with_no_limit()
396    }
397    fn with_collection_limit(self, limit: u64) -> Config {
398        self.config().with_collection_limit(limit)
399    }
400    fn with_no_collection_limit(self) -> Config {
401        self.config().with_no_collection_limit()
402    }
403    fn with_depth_limit(self, limit: usize) -> Config {
404        self.config().with_depth_limit(limit)
405    }
406    /// Selects the schema-guided compact profile.
407    #[cfg(feature = "compact")]
408    fn with_compact_format(self) -> crate::CompactConfig {
409        crate::CompactConfig::new(self.config())
410    }
411    /// Returns the wire profile this configuration produces.
412    fn profile(self) -> BinaryProfile {
413        BinaryProfile::SelfDescribing
414    }
415    fn reject_trailing_bytes(self) -> Config {
416        self.config().reject_trailing_bytes()
417    }
418    fn allow_trailing_bytes(self) -> Config {
419        self.config().allow_trailing_bytes()
420    }
421    fn serialize<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<Vec<u8>> {
422        self.config().serialize(value)
423    }
424    #[cfg(feature = "std")]
425    fn serialize_into<W: Write, T: nextjson::NsonSerialize + ?Sized>(
426        self,
427        writer: W,
428        value: &T,
429    ) -> Result<()> {
430        self.config().serialize_into(writer, value)
431    }
432    fn serialize_into_slice<T: nextjson::NsonSerialize + ?Sized>(
433        self,
434        output: &mut [u8],
435        value: &T,
436    ) -> Result<usize> {
437        self.config().serialize_into_slice(output, value)
438    }
439    fn serialized_size<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<u64> {
440        self.config().serialized_size(value)
441    }
442    fn deserialize<'de, T: nextjson::NsonDeserialize<'de>>(self, input: &'de [u8]) -> Result<T> {
443        self.config().deserialize(input)
444    }
445    #[cfg(feature = "std")]
446    fn deserialize_from<R: Read, T: for<'de> nextjson::NsonDeserialize<'de>>(
447        self,
448        reader: R,
449    ) -> Result<T> {
450        self.config().deserialize_from(reader)
451    }
452    /// Probes the exact structural footprint of the next value without
453    /// materializing it.
454    fn probe(self, input: &[u8]) -> Result<crate::Probe> {
455        self.config().probe(input)
456    }
457}
458
459impl Options for Config {
460    fn config(self) -> Config {
461        self
462    }
463}