Skip to main content

codec_cbor/
value.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe LLC
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use zeroize::{Zeroize, ZeroizeOnDrop};
6
7/// A decoded DAG-CBOR value.
8///
9/// Values wipe owned text and byte buffers on drop. Callers can also call
10/// [`Zeroize::zeroize`] to clear a value before its owner is dropped.
11#[derive(PartialEq)]
12#[non_exhaustive]
13pub enum CborValue {
14    /// CBOR null.
15    Null,
16    /// CBOR boolean.
17    Bool(bool),
18    /// A signed integer within the `i64` range.
19    Int(i64),
20    /// A UTF-8 text string.
21    String(String),
22    /// A byte string.
23    Bytes(Vec<u8>),
24    /// An array of values.
25    Array(Vec<CborValue>),
26    /// A map of text-string keys to values, in canonical key order.
27    Map(Vec<(String, CborValue)>),
28}
29
30impl core::fmt::Debug for CborValue {
31    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
32        let kind = match self {
33            Self::Null => "Null",
34            Self::Bool(_) => "Bool",
35            Self::Int(_) => "Int",
36            Self::String(_) => "String",
37            Self::Bytes(_) => "Bytes",
38            Self::Array(_) => "Array",
39            Self::Map(_) => "Map",
40        };
41        formatter.debug_tuple("CborValue").field(&kind).finish()
42    }
43}
44
45// Zeroize nested fields before the enum releases owned buffers.
46impl Zeroize for CborValue {
47    fn zeroize(&mut self) {
48        match self {
49            Self::Null => {}
50            Self::Bool(value) => value.zeroize(),
51            Self::Int(value) => value.zeroize(),
52            Self::String(value) => value.zeroize(),
53            Self::Bytes(value) => value.zeroize(),
54            Self::Array(values) => values.zeroize(),
55            Self::Map(entries) => entries.zeroize(),
56        }
57    }
58}
59
60impl Drop for CborValue {
61    fn drop(&mut self) {
62        self.zeroize();
63    }
64}
65
66impl ZeroizeOnDrop for CborValue {}