sacp-cbor 0.6.0

SACP-CBOR/1: strict deterministic CBOR validation and canonical encoding (hot-path optimized, no_std-capable).
Documentation
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// src/macros.rs

//! CBOR construction macro.
//!
//! This module provides [`cbor!`], a convenient macro to build [`crate::CborValue`] trees.
//!
//! Design notes:
//! - The macro is **fallible** and returns `Result<CborValue, CborError>`.
//! - Integers outside the "safe integer" range are automatically encoded as CBOR bignums (tag 2/3).
//! - `NaN` is canonicalized; negative zero is rejected.
//! - Map keys are always text strings and the resulting map is sorted into canonical order via
//!   [`crate::CborMap::new`].
//!
//! Map key rules (same ergonomics as `serde_json::json!`):
//! - `{ a: 1 }` uses the literal key `"a"` (identifier stringized)
//! - `{ "a": 1 }` uses the literal string key `"a"`
//! - `{ (k): 1 }` uses the expression `k` as the key (must be `&str`, `String`, or `char`)
//!
//! ```ignore
//! # use your_crate_name::cbor;
//! # fn demo() -> Result<(), your_crate_name::CborError> {
//! let user_key = "dynamic";
//! let v = cbor!({
//!     a: 1,
//!     (user_key): [true, null, 1.5],
//! })?;
//! # Ok(()) }
//! ```

/// Construct a [`crate::CborValue`] using a JSON-like literal syntax.
///
/// This macro returns `Result<crate::CborValue, crate::CborError>`.
///
/// Supported forms:
/// - `cbor!(null)`
/// - `cbor!(true)` / `cbor!(false)`
/// - `cbor!("text")`
/// - `cbor!(b"bytes")`
/// - `cbor!([ ... ])`
/// - `cbor!({ key: value, "key": value, (expr_key): value, ... })`
/// - `cbor!(expr)` where `expr` implements the internal conversion trait
///   (covers primitives, `String`, `Vec<u8>`, `BigInt`, `F64Bits`, `CborMap`, etc.).
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[macro_export]
macro_rules! cbor {
    (null) => {
        ::core::result::Result::<$crate::CborValue, $crate::CborError>::Ok(
            $crate::CborValue::null(),
        )
    };
    (true) => {
        ::core::result::Result::<$crate::CborValue, $crate::CborError>::Ok(
            $crate::CborValue::bool(true),
        )
    };
    (false) => {
        ::core::result::Result::<$crate::CborValue, $crate::CborError>::Ok(
            $crate::CborValue::bool(false),
        )
    };

    // Array literal: cbor!([ ... ])
    ([ $($elem:tt),* $(,)? ]) => {{
        (|| -> ::core::result::Result<$crate::CborValue, $crate::CborError> {
            let mut items = $crate::__cbor_macro::Vec::new();
            $crate::__cbor_macro::try_reserve_exact(
                &mut items,
                0usize $(+ { let _ = stringify!($elem); 1usize })*,
            )?;

            $(
                items.push($crate::cbor!($elem)?);
            )*

            ::core::result::Result::Ok($crate::CborValue::array(items))
        })()
    }};

    // Map literal: cbor!({ ... })
    ({ $($key:tt : $value:tt),* $(,)? }) => {{
        (|| -> ::core::result::Result<$crate::CborValue, $crate::CborError> {
            let mut entries = $crate::__cbor_macro::Vec::new();
            $crate::__cbor_macro::try_reserve_exact(
                &mut entries,
                0usize $(+ { let _ = stringify!($key); let _ = stringify!($value); 1usize })*,
            )?;

            $(
                let k = $crate::__cbor_key!($key)?;
                let v = $crate::cbor!($value)?;
                entries.push((k, v));
            )*

            let map = $crate::CborMap::new(entries)?;
            ::core::result::Result::Ok($crate::CborValue::map(map))
        })()
    }};

    // Fallback: convert an expression into CborValue
    ($other:expr) => {{
        $crate::__cbor_macro::IntoCborValue::into_cbor_value($other)
    }};
}

/// Construct canonical CBOR bytes directly using a JSON-like literal syntax.
///
/// This macro returns `Result<crate::CborBytes, crate::CborError>`.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[macro_export]
macro_rules! cbor_bytes {
    ($($tt:tt)+) => {{
        (|| -> ::core::result::Result<$crate::CborBytes, $crate::CborError> {
            let mut __enc = $crate::Encoder::new();
            $crate::__cbor_bytes_into!(&mut __enc, $($tt)+)?;
            __enc.into_canonical()
        })()
    }};
}

#[doc(hidden)]
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! __cbor_bytes_into {
    ($enc:expr, null) => { $enc.null() };
    ($enc:expr, true) => { $enc.bool(true) };
    ($enc:expr, false) => { $enc.bool(false) };

    ($enc:expr, [ $($elem:tt),* $(,)? ]) => {{
        let __len = 0usize $(+ { let _ = stringify!($elem); 1usize })*;
        $enc.array(__len, |__arr| {
            $( $crate::__cbor_bytes_into!(__arr, $elem)?; )*
            ::core::result::Result::Ok(())
        })
    }};

    ($enc:expr, { $($key:tt : $value:tt),* $(,)? }) => {{
        let __len = 0usize $(+ { let _ = stringify!($key); let _ = stringify!($value); 1usize })*;
        $enc.map(__len, |__map| {
            $( $crate::__cbor_bytes_map_entry!(__map, $key, $value)?; )*
            ::core::result::Result::Ok(())
        })
    }};

    // fallback: encode arbitrary expression types via IntoCborBytes
    ($enc:expr, $other:expr) => {{
        $enc.__encode_any($other)
    }};
}

#[doc(hidden)]
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! __cbor_bytes_map_entry {
    ($map:expr, $key:ident, $value:tt) => {{
        $map.entry(::core::stringify!($key), |__enc| {
            $crate::__cbor_bytes_into!(__enc, $value)
        })?;
        ::core::result::Result::Ok(())
    }};
    ($map:expr, $key:literal, $value:tt) => {{
        $map.entry($key, |__enc| $crate::__cbor_bytes_into!(__enc, $value))?;
        ::core::result::Result::Ok(())
    }};
    ($map:expr, (($key:expr)), $value:tt) => {{
        let __k = $crate::__cbor_macro::IntoCborKey::into_cbor_key($key)?;
        $map.entry(__k.as_ref(), |__enc| {
            $crate::__cbor_bytes_into!(__enc, $value)
        })?;
        ::core::result::Result::Ok(())
    }};
}

/// Internal helper for map keys.
///
/// - `ident` becomes `"ident"`
/// - `"literal"` must be a string literal
/// - `(expr)` uses the runtime expression as key
#[doc(hidden)]
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! __cbor_key {
    ($key:ident) => {{
        $crate::__cbor_macro::boxed_str_from_str(::core::stringify!($key))
    }};
    (($key:expr)) => {{
        $crate::__cbor_macro::IntoCborKey::into_cbor_key($key)
    }};
    ($key:literal) => {{
        // Intentionally requires a string literal type (`&'static str`).
        // Non-string literals will fail to type-check here.
        $crate::__cbor_macro::boxed_str_from_str($key)
    }};
}

/// Hidden support module used by `cbor!` expansions.
///
/// This is re-exported at crate root as `__cbor_macro` (see `lib.rs` change below).
#[doc(hidden)]
#[allow(missing_docs)]
pub mod __cbor_macro {
    use alloc::boxed::Box;
    use alloc::string::String;
    use core::convert::TryFrom;

    pub use alloc::vec::Vec;

    use crate::{
        BigInt, CborBytes, CborBytesRef, CborError, CborInteger, CborMap, CborValue, CborValueRef,
        Encoder, ErrorCode, F64Bits, MAX_SAFE_INTEGER, MAX_SAFE_INTEGER_I64, MIN_SAFE_INTEGER,
    };

    #[inline]
    const fn overflow() -> CborError {
        CborError::new(ErrorCode::LengthOverflow, 0)
    }

    pub fn try_reserve_exact<T>(v: &mut Vec<T>, additional: usize) -> Result<(), CborError> {
        crate::alloc_util::try_reserve_exact(v, additional, 0)
    }

    pub fn boxed_str_from_str(s: &str) -> Result<Box<str>, CborError> {
        crate::alloc_util::try_box_str_from_str(s, 0)
    }

    pub fn bytes_from_slice(b: &[u8]) -> Result<Vec<u8>, CborError> {
        crate::alloc_util::try_vec_from_slice(b, 0)
    }

    fn u128_to_min_be_bytes_nonzero(n: u128) -> Result<Vec<u8>, CborError> {
        debug_assert!(n != 0);
        let leading_bytes = (n.leading_zeros() / 8) as usize;
        let raw = n.to_be_bytes();
        // For n != 0, leading_bytes is at most 15, so slice is non-empty.
        bytes_from_slice(&raw[leading_bytes..])
    }

    fn int_from_u128(v: u128) -> Result<CborValue, CborError> {
        let safe_max = u128::from(MAX_SAFE_INTEGER);
        if v <= safe_max {
            let i = i64::try_from(v).map_err(|_| overflow())?;
            return CborValue::int(i);
        }

        let magnitude = u128_to_min_be_bytes_nonzero(v)?;
        let big = BigInt::new(false, magnitude)?;
        Ok(CborValue::integer(CborInteger::from_bigint(big)))
    }

    fn int_from_i128(v: i128) -> Result<CborValue, CborError> {
        let min = i128::from(MIN_SAFE_INTEGER);
        let safe_max = i128::from(MAX_SAFE_INTEGER_I64);

        if v >= min && v <= safe_max {
            let i = i64::try_from(v).map_err(|_| overflow())?;
            return CborValue::int(i);
        }

        let negative = v < 0;
        let n_u128 = if negative {
            // CBOR negative integer / bignum semantics: value = -1 - n
            let n_i128 = -1_i128 - v;
            u128::try_from(n_i128).map_err(|_| overflow())?
        } else {
            u128::try_from(v).map_err(|_| overflow())?
        };

        // Outside safe range implies n_u128 != 0.
        let magnitude = u128_to_min_be_bytes_nonzero(n_u128)?;
        let big = BigInt::new(negative, magnitude)?;
        Ok(CborValue::integer(CborInteger::from_bigint(big)))
    }

    pub trait IntoCborKey {
        fn into_cbor_key(self) -> Result<Box<str>, CborError>;
    }

    impl IntoCborKey for String {
        fn into_cbor_key(self) -> Result<Box<str>, CborError> {
            Ok(self.into_boxed_str())
        }
    }

    impl IntoCborKey for &String {
        fn into_cbor_key(self) -> Result<Box<str>, CborError> {
            boxed_str_from_str(self.as_str())
        }
    }

    impl IntoCborKey for &str {
        fn into_cbor_key(self) -> Result<Box<str>, CborError> {
            boxed_str_from_str(self)
        }
    }

    impl IntoCborKey for char {
        fn into_cbor_key(self) -> Result<Box<str>, CborError> {
            let mut out = String::new();
            crate::alloc_util::try_reserve_exact_str(&mut out, 4, 0)?;
            out.push(self);
            Ok(out.into_boxed_str())
        }
    }

    pub trait IntoCborValue {
        fn into_cbor_value(self) -> Result<CborValue, CborError>;
    }

    impl IntoCborValue for CborValue {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(self)
        }
    }

    impl IntoCborValue for &CborValue {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(self.clone())
        }
    }

    impl IntoCborValue for CborMap {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::map(self))
        }
    }

    impl IntoCborValue for &CborMap {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::map(self.clone()))
        }
    }

    impl IntoCborValue for BigInt {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::integer(CborInteger::from_bigint(self)))
        }
    }

    impl IntoCborValue for &BigInt {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::integer(CborInteger::from_bigint(self.clone())))
        }
    }

    impl IntoCborValue for F64Bits {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::float(self))
        }
    }

    impl IntoCborValue for bool {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::bool(self))
        }
    }

    impl IntoCborValue for () {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::null())
        }
    }

    impl<T: IntoCborValue> IntoCborValue for Option<T> {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            self.map_or(Ok(CborValue::null()), IntoCborValue::into_cbor_value)
        }
    }

    impl IntoCborValue for String {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::text(self))
        }
    }

    impl IntoCborValue for &String {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            let boxed = boxed_str_from_str(self.as_str())?;
            Ok(CborValue::text(boxed))
        }
    }

    impl IntoCborValue for &str {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            let boxed = boxed_str_from_str(self)?;
            Ok(CborValue::text(boxed))
        }
    }

    impl IntoCborValue for Vec<u8> {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::bytes(self))
        }
    }

    impl IntoCborValue for &Vec<u8> {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::bytes(bytes_from_slice(self.as_slice())?))
        }
    }

    impl IntoCborValue for &[u8] {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::bytes(bytes_from_slice(self)?))
        }
    }

    impl<const N: usize> IntoCborValue for &[u8; N] {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::bytes(bytes_from_slice(&self[..])?))
        }
    }

    impl IntoCborValue for Vec<CborValue> {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::array(self))
        }
    }

    impl IntoCborValue for &[CborValue] {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            let mut out: Vec<CborValue> = Vec::new();
            crate::alloc_util::try_reserve_exact(&mut out, self.len(), 0)?;
            out.extend_from_slice(self);
            Ok(CborValue::array(out))
        }
    }

    impl IntoCborValue for f64 {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::float(F64Bits::try_from_f64(self)?))
        }
    }

    impl IntoCborValue for f32 {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            Ok(CborValue::float(F64Bits::try_from_f64(f64::from(self))?))
        }
    }

    macro_rules! impl_into_int_signed {
        ($($t:ty),* $(,)?) => {$(
            impl IntoCborValue for $t {
                fn into_cbor_value(self) -> Result<CborValue, CborError> {
                    int_from_i128(i128::from(self))
                }
            }
        )*};
    }

    macro_rules! impl_into_int_unsigned {
        ($($t:ty),* $(,)?) => {$(
            impl IntoCborValue for $t {
                fn into_cbor_value(self) -> Result<CborValue, CborError> {
                    int_from_u128(u128::from(self))
                }
            }
        )*};
    }

    impl_into_int_signed!(i8, i16, i32, i64, i128);
    impl_into_int_unsigned!(u8, u16, u32, u64, u128);

    impl IntoCborValue for isize {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            int_from_i128(i128::try_from(self).map_err(|_| overflow())?)
        }
    }

    impl IntoCborValue for usize {
        fn into_cbor_value(self) -> Result<CborValue, CborError> {
            int_from_u128(u128::try_from(self).map_err(|_| overflow())?)
        }
    }

    pub trait IntoCborBytes {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError>;
    }

    impl IntoCborBytes for CborValue {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.value(&self)
        }
    }

    impl IntoCborBytes for &CborValue {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.value(self)
        }
    }

    impl IntoCborBytes for CborBytesRef<'_> {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.raw_cbor(self)
        }
    }

    impl IntoCborBytes for &CborBytes {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.raw_cbor(CborBytesRef::new(self.as_bytes()))
        }
    }

    impl IntoCborBytes for CborValueRef<'_> {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.raw_value_ref(self)
        }
    }

    impl IntoCborBytes for bool {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.bool(self)
        }
    }

    impl IntoCborBytes for () {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.null()
        }
    }

    impl<T: IntoCborBytes> IntoCborBytes for Option<T> {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            match self {
                None => enc.null(),
                Some(v) => v.into_cbor_bytes(enc),
            }
        }
    }

    impl IntoCborBytes for String {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.text(self.as_str())
        }
    }

    impl IntoCborBytes for &String {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.text(self.as_str())
        }
    }

    impl IntoCborBytes for &str {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.text(self)
        }
    }

    impl IntoCborBytes for Vec<u8> {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.bytes(self.as_slice())
        }
    }

    impl IntoCborBytes for &Vec<u8> {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.bytes(self.as_slice())
        }
    }

    impl IntoCborBytes for &[u8] {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.bytes(self)
        }
    }

    impl<const N: usize> IntoCborBytes for &[u8; N] {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.bytes(&self[..])
        }
    }

    impl IntoCborBytes for F64Bits {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.float(self)
        }
    }

    impl IntoCborBytes for f64 {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.float(F64Bits::try_from_f64(self)?)
        }
    }

    impl IntoCborBytes for f32 {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.float(F64Bits::try_from_f64(f64::from(self))?)
        }
    }

    macro_rules! impl_into_int_signed_bytes {
        ($($t:ty),* $(,)?) => {$(
            impl IntoCborBytes for $t {
                fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
                    enc.int_i128(i128::from(self))
                }
            }
        )*};
    }

    macro_rules! impl_into_int_unsigned_bytes {
        ($($t:ty),* $(,)?) => {$(
            impl IntoCborBytes for $t {
                fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
                    enc.int_u128(u128::from(self))
                }
            }
        )*};
    }

    impl_into_int_signed_bytes!(i8, i16, i32, i64, i128);
    impl_into_int_unsigned_bytes!(u8, u16, u32, u64, u128);

    impl IntoCborBytes for isize {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.int_i128(i128::try_from(self).map_err(|_| overflow())?)
        }
    }

    impl IntoCborBytes for usize {
        fn into_cbor_bytes(self, enc: &mut Encoder) -> Result<(), CborError> {
            enc.int_u128(u128::try_from(self).map_err(|_| overflow())?)
        }
    }
}