rustbinary 0.1.7

A bounded nextjson binary codec with adaptive frames, zero-allocation paths, schema evolution, and authenticated pipelines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::io::{Read, Write};

use crate::{decoder, error::Result, ser, tags::MAX_DEPTH};

/// Conservative default byte limit for one encoded or decoded Core value.
pub const DEFAULT_SIZE_LIMIT: u64 = 64 * 1024 * 1024;

/// Conservative default element limit for one sequence or map.
pub const DEFAULT_COLLECTION_LIMIT: u64 = 1_000_000;

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
/// Byte order for fixed-width values and varint payloads.
pub enum Endian {
    /// Least-significant byte first.
    #[default]
    Little,
    /// Most-significant byte first.
    Big,
    /// The compilation target's byte order.
    Native,
}

impl Endian {
    pub(crate) const fn little(self) -> bool {
        match self {
            Self::Little => true,
            Self::Big => false,
            Self::Native => cfg!(target_endian = "little"),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
/// Integer representation used by the codec.
pub enum IntEncoding {
    /// Always use the integer type's full width.
    Fixed,
    /// Use compact marker-prefixed widths and ZigZag signed values.
    #[default]
    Variable,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
/// Policy for bytes following a decoded top-level value.
pub enum TrailingBytes {
    /// Leave unread bytes untouched.
    Allow,
    /// Report unread bytes as an error.
    #[default]
    Reject,
}

/// The three wire profiles the codec offers for the same Rust value.
///
/// They coexist and compose; the profile is a property of the chosen
/// configuration, never of the type itself.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BinaryProfile {
    /// Field-name-bearing, type-tagged, terminator-delimited stream.
    ///
    /// Backs dynamic [`nextjson::Value`]s, untagged enums, and
    /// `FormatEncoder`-driven types. Compactness is secondary to flexibility.
    SelfDescribing,
    /// Schema-guided compact stream.
    ///
    /// No per-value tags, no field names, length-prefixed containers. See
    /// [`crate::compact`] for the wire layout. Enabled with
    /// [`Config::with_compact_format`].
    CompactSchema,
    /// Stable numeric field IDs with per-field lengths for forward compatibility.
    ///
    /// Enabled with [`Config::with_schema_evolution`].
    Evolution,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
/// Copyable configuration describing a complete wire profile.
pub struct Config {
    pub(crate) endian: Endian,
    pub(crate) integers: IntEncoding,
    pub(crate) trailing: TrailingBytes,
    pub(crate) limit: Option<u64>,
    pub(crate) collection_limit: Option<u64>,
    pub(crate) depth_limit: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self::standard()
    }
}

impl Config {
    /// Creates the compact profile: variable integers, little endian, and strict trailing bytes.
    pub const fn standard() -> Self {
        Self {
            endian: Endian::Little,
            integers: IntEncoding::Variable,
            trailing: TrailingBytes::Reject,
            limit: Some(DEFAULT_SIZE_LIMIT),
            collection_limit: Some(DEFAULT_COLLECTION_LIMIT),
            depth_limit: MAX_DEPTH,
        }
    }
    /// Creates the historical unbounded fixed-width RustBinary profile.
    ///
    /// This profile has no byte or collection limits, so it must only be used
    /// with trusted, in-memory data. It is not a safe default for network
    /// input. Decompression remains bounded even here: the compression wrapper
    /// caps the decompressed size at [`DEFAULT_SIZE_LIMIT`] when no explicit
    /// limit is configured. Prefer [`Config::standard`] and set explicit
    /// [`Config::with_limit`] / [`Config::with_collection_limit`] values at
    /// every trust boundary.
    pub const fn legacy() -> Self {
        Self {
            endian: Endian::Little,
            integers: IntEncoding::Fixed,
            trailing: TrailingBytes::Allow,
            limit: None,
            collection_limit: None,
            depth_limit: MAX_DEPTH,
        }
    }
    /// Selects little endian.
    pub const fn with_little_endian(mut self) -> Self {
        self.endian = Endian::Little;
        self
    }
    /// Selects big endian.
    pub const fn with_big_endian(mut self) -> Self {
        self.endian = Endian::Big;
        self
    }
    /// Selects the compilation target's native byte order.
    pub const fn with_native_endian(mut self) -> Self {
        self.endian = Endian::Native;
        self
    }
    /// Selects fixed-width integer encoding.
    pub const fn with_fixint_encoding(mut self) -> Self {
        self.integers = IntEncoding::Fixed;
        self
    }
    /// Selects variable-width integer encoding.
    pub const fn with_varint_encoding(mut self) -> Self {
        self.integers = IntEncoding::Variable;
        self
    }
    /// Limits one encoded or decoded value to `limit` consumed bytes.
    pub const fn with_limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self.collection_limit = Some(match self.collection_limit {
            Some(current) if current < limit => current,
            _ => limit,
        });
        self
    }
    /// Removes the consumed-byte limit.
    ///
    /// # Security
    ///
    /// Without a byte limit the raw codec performs no size accounting, so this
    /// mode is only for trusted, in-memory data. Decompression is an exception
    /// that remains bounded: the compression wrapper (`with_zstd_compression`)
    /// always caps the decompressed size at the crate-wide
    /// [`DEFAULT_SIZE_LIMIT`] when no explicit limit is configured, so a
    /// hostile frame cannot expand without bound.
    pub const fn with_no_limit(mut self) -> Self {
        self.limit = None;
        self
    }
    /// Limits the number of elements in one sequence or map.
    pub const fn with_collection_limit(mut self, limit: u64) -> Self {
        self.collection_limit = Some(limit);
        self
    }
    /// Removes the collection element limit.
    pub const fn with_no_collection_limit(mut self) -> Self {
        self.collection_limit = None;
        self
    }
    /// Caps the maximum container nesting depth for one encoded or decoded value.
    ///
    /// Both the encoder and the decoder fail fast when a container is entered
    /// at the limit, so hostile deep-nesting input is rejected instead of
    /// walked. The value is clamped to the crate-wide `MAX_DEPTH` ceiling
    /// (currently 128), which also sizes the internal per-depth accounting
    /// tables, so a caller-supplied larger limit cannot cause out-of-bounds
    /// indexing.
    pub const fn with_depth_limit(mut self, limit: usize) -> Self {
        let clamped = if limit > MAX_DEPTH { MAX_DEPTH } else { limit };
        self.depth_limit = clamped;
        self
    }
    /// Returns the configured container nesting depth cap.
    pub const fn depth_limit(self) -> usize {
        self.depth_limit
    }
    /// Returns the configured consumed-byte limit, if any.
    pub const fn limit(self) -> Option<u64> {
        self.limit
    }
    /// Returns the configured per-collection element limit, if any.
    pub const fn collection_limit(self) -> Option<u64> {
        self.collection_limit
    }
    /// Adds a versioned schema fingerprint header to every value.
    #[cfg(feature = "fingerprint")]
    pub const fn with_fingerprint(self) -> crate::FingerprintedConfig {
        crate::FingerprintedConfig::new(self)
    }
    /// Selects the schema-guided compact profile.
    ///
    /// Carries over this config's resource policies (`limit`,
    /// `collection_limit`, `depth_limit`, `trailing`). The compact wire is
    /// always little-endian marker-varint; `Endian` and `IntEncoding` do not
    /// alter it. Returns [`BinaryProfile::CompactSchema`].
    #[cfg(feature = "compact")]
    pub const fn with_compact_format(self) -> crate::CompactConfig {
        crate::CompactConfig::new(self)
    }
    /// Returns the wire profile this configuration produces.
    pub const fn profile(self) -> BinaryProfile {
        BinaryProfile::SelfDescribing
    }
    /// Switches to the RFC 8949 CBOR format while retaining resource policies.
    #[cfg(feature = "cbor")]
    pub const fn with_cbor_format(self) -> crate::CborConfig {
        crate::CborConfig::new(self)
    }
    /// Wraps binary payloads in an adaptive Zstandard compression frame.
    #[cfg(feature = "compression")]
    pub const fn with_zstd_compression(self, level: i32) -> crate::CompressedConfig {
        crate::CompressedConfig::binary(self, level)
    }
    /// Encrypts binary payloads using XChaCha20-Poly1305 and random nonces.
    #[cfg(feature = "encryption")]
    pub fn with_encryption(self, key: crate::EncryptionKey) -> crate::EncryptedConfig {
        crate::EncryptedConfig::binary(self, key)
    }
    /// Selects the generated bit-packed representation for [`crate::BitPack`] types.
    #[cfg(feature = "bit-packing")]
    pub const fn with_bit_packing(self) -> crate::BitPackedConfig {
        crate::BitPackedConfig::new(self)
    }
    /// Enables data-aware integer, string, and numeric-collection encodings.
    #[cfg(feature = "adaptive")]
    pub const fn with_adaptive_encoding(self) -> crate::AdaptiveConfig {
        crate::AdaptiveConfig::new(self.with_varint_encoding().with_little_endian())
    }
    /// Enables framed static-model rANS entropy coding.
    #[cfg(feature = "entropy")]
    pub const fn with_entropy_encoding(self) -> crate::EntropyConfig {
        crate::EntropyConfig::new(self.with_varint_encoding().with_little_endian())
    }
    /// Enables baseline-relative differential frames for state exchange.
    #[cfg(feature = "reconcile")]
    pub const fn with_delta_encoding(self) -> crate::DeltaConfig {
        crate::DeltaConfig::new(self.with_varint_encoding().with_little_endian())
    }
    /// Enables ordered parallel batch serialization and deserialization.
    #[cfg(feature = "parallel")]
    pub fn with_parallel_serialization(self) -> crate::ParallelConfig {
        crate::ParallelConfig::new(self)
    }
    /// Wraps values in a stable-field-ID schema evolution frame.
    #[cfg(feature = "schema-evolution")]
    pub const fn with_schema_evolution(self) -> crate::EvolutionConfig {
        crate::EvolutionConfig::new(self)
    }
    /// Rejects bytes left after a top-level value.
    pub const fn reject_trailing_bytes(mut self) -> Self {
        self.trailing = TrailingBytes::Reject;
        self
    }
    /// Allows bytes left after a top-level value.
    pub const fn allow_trailing_bytes(mut self) -> Self {
        self.trailing = TrailingBytes::Allow;
        self
    }
    /// Serializes a value into a new vector.
    #[cfg(feature = "alloc")]
    pub fn serialize<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<Vec<u8>> {
        ser::to_vec(value, self)
    }
    /// Serializes a value directly into `writer`.
    #[cfg(feature = "std")]
    pub fn serialize_into<W: Write, T: nextjson::NsonSerialize + ?Sized>(
        self,
        writer: W,
        value: &T,
    ) -> Result<()> {
        crate::adapters::serialize_into(self, writer, value)
    }
    /// Serializes into a caller-owned slice without codec-owned heap allocation.
    ///
    /// If capacity is insufficient, the error reports the exact required size.
    /// The prefix that fits in `output` is written before that error is returned.
    /// A user-provided [`nextjson::NsonSerialize`] implementation may still allocate internally.
    pub fn serialize_into_slice<T: nextjson::NsonSerialize + ?Sized>(
        self,
        output: &mut [u8],
        value: &T,
    ) -> Result<usize> {
        ser::to_slice(output, value, self)
    }
    /// Calculates the exact encoded size without retaining encoded bytes.
    pub fn serialized_size<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<u64> {
        ser::size(value, self)
    }
    /// Deserializes a value that may borrow from `input`.
    pub fn deserialize<'de, T: nextjson::NsonDeserialize<'de>>(
        self,
        input: &'de [u8],
    ) -> Result<T> {
        decoder::from_slice(input, self)
    }
    /// Reads and deserializes an owned value.
    #[cfg(feature = "std")]
    pub fn deserialize_from<R: Read, T: for<'de> nextjson::NsonDeserialize<'de>>(
        self,
        reader: R,
    ) -> Result<T> {
        crate::adapters::deserialize_from(self, reader)
    }
}

/// Fluent compatibility facade implemented by concrete option values.
#[allow(missing_docs)]
pub trait Options: Sized {
    fn config(self) -> Config;
    fn with_little_endian(self) -> Config {
        self.config().with_little_endian()
    }
    fn with_big_endian(self) -> Config {
        self.config().with_big_endian()
    }
    fn with_native_endian(self) -> Config {
        self.config().with_native_endian()
    }
    fn with_fixint_encoding(self) -> Config {
        self.config().with_fixint_encoding()
    }
    fn with_varint_encoding(self) -> Config {
        self.config().with_varint_encoding()
    }
    fn with_limit(self, limit: u64) -> Config {
        self.config().with_limit(limit)
    }
    fn with_no_limit(self) -> Config {
        self.config().with_no_limit()
    }
    fn with_collection_limit(self, limit: u64) -> Config {
        self.config().with_collection_limit(limit)
    }
    fn with_no_collection_limit(self) -> Config {
        self.config().with_no_collection_limit()
    }
    fn with_depth_limit(self, limit: usize) -> Config {
        self.config().with_depth_limit(limit)
    }
    /// Selects the schema-guided compact profile.
    #[cfg(feature = "compact")]
    fn with_compact_format(self) -> crate::CompactConfig {
        crate::CompactConfig::new(self.config())
    }
    /// Returns the wire profile this configuration produces.
    fn profile(self) -> BinaryProfile {
        BinaryProfile::SelfDescribing
    }
    fn reject_trailing_bytes(self) -> Config {
        self.config().reject_trailing_bytes()
    }
    fn allow_trailing_bytes(self) -> Config {
        self.config().allow_trailing_bytes()
    }
    #[cfg(feature = "alloc")]
    fn serialize<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<Vec<u8>> {
        self.config().serialize(value)
    }
    #[cfg(feature = "std")]
    fn serialize_into<W: Write, T: nextjson::NsonSerialize + ?Sized>(
        self,
        writer: W,
        value: &T,
    ) -> Result<()> {
        self.config().serialize_into(writer, value)
    }
    fn serialize_into_slice<T: nextjson::NsonSerialize + ?Sized>(
        self,
        output: &mut [u8],
        value: &T,
    ) -> Result<usize> {
        self.config().serialize_into_slice(output, value)
    }
    fn serialized_size<T: nextjson::NsonSerialize + ?Sized>(self, value: &T) -> Result<u64> {
        self.config().serialized_size(value)
    }
    fn deserialize<'de, T: nextjson::NsonDeserialize<'de>>(self, input: &'de [u8]) -> Result<T> {
        self.config().deserialize(input)
    }
    #[cfg(feature = "std")]
    fn deserialize_from<R: Read, T: for<'de> nextjson::NsonDeserialize<'de>>(
        self,
        reader: R,
    ) -> Result<T> {
        self.config().deserialize_from(reader)
    }
}

impl Options for Config {
    fn config(self) -> Config {
        self
    }
}