Skip to main content

codec_cbor/general/
encode.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
6
7use super::error::{error, CborError, ErrorReason};
8use super::float::{Float, FloatWidth};
9use super::limits::{Budget, Limits};
10use super::profile::{Profile, Serialization};
11use super::read_header::{preferred_width, ArgumentWidth, MajorType};
12use super::receipt::Frame;
13use super::scan::{add, scan};
14
15/// Borrowed encoding input. Arrays and maps retain caller order. Scalar integer
16/// copies zeroize on drop; borrowed storage remains the caller's responsibility.
17/// No payload-printing or cloning traits are implemented.
18pub enum ValueRef<'a> {
19    /// Full unsigned 64-bit integer.
20    Unsigned(u64),
21    /// Full unsigned argument `n` for the negative integer `-1-n`.
22    Negative(u64),
23    /// Borrowed byte contents.
24    Bytes(&'a [u8]),
25    /// Borrowed UTF-8 text.
26    Text(&'a str),
27    /// Ordered array elements.
28    Array(&'a [ValueRef<'a>]),
29    /// Ordered unique map entries; equivalence is checked before returning output.
30    Map(&'a [MapEntry<'a>]),
31    /// Arbitrary tag and its child; application-specific semantics remain opaque.
32    Tag(u64, &'a ValueRef<'a>),
33    /// Borrowed protected floating-point value.
34    Float(&'a Float),
35    /// Boolean.
36    Bool(bool),
37    /// Null.
38    Null,
39    /// Undefined.
40    Undefined,
41    /// Simple value (0..23 or 32..255); codes 24..31 are reserved.
42    Simple(u8),
43    /// Embed the complete received encoding verbatim, subject to the selected
44    /// profile and remaining budgets. This variant never normalizes input.
45    Received(&'a Frame<'a>),
46}
47
48impl Drop for ValueRef<'_> {
49    fn drop(&mut self) {
50        match self {
51            Self::Unsigned(value) | Self::Negative(value) | Self::Tag(value, _) => value.zeroize(),
52            Self::Bool(value) => value.zeroize(),
53            Self::Simple(value) => value.zeroize(),
54            _ => {}
55        }
56    }
57}
58impl ZeroizeOnDrop for ValueRef<'_> {}
59
60/// One ordered pair of borrowed encoding inputs, without hidden key sorting.
61pub struct MapEntry<'a> {
62    key: ValueRef<'a>,
63    value: ValueRef<'a>,
64}
65
66impl<'a> MapEntry<'a> {
67    /// Construct a pair; the encoder validates key uniqueness across the map.
68    #[must_use]
69    pub const fn new(key: ValueRef<'a>, value: ValueRef<'a>) -> Self {
70        Self { key, value }
71    }
72}
73impl ZeroizeOnDrop for MapEntry<'_> {}
74
75/// Protected general CBOR output. The initialized allocation is wiped on drop,
76/// including partial output on every encoding or validation failure.
77pub struct EncodedCbor {
78    bytes: Zeroizing<Vec<u8>>,
79}
80
81impl EncodedCbor {
82    /// Borrow the protected encoding. Copies made by the caller need an owner
83    /// that provides the same memory hygiene as the original allocation.
84    #[must_use]
85    pub fn as_bytes(&self) -> &[u8] {
86        &self.bytes
87    }
88}
89impl ZeroizeOnDrop for EncodedCbor {}
90
91struct Encoder {
92    bytes: Zeroizing<Vec<u8>>,
93    length: usize,
94    measure: bool,
95    budget: Budget,
96    profile: Profile,
97}
98
99impl Encoder {
100    fn append(&mut self, bytes: &[u8]) -> Result<(), CborError> {
101        let end = add(self.length, bytes.len())?;
102        if end > self.budget.limits.output {
103            return Err(error(ErrorReason::OutputLimit));
104        }
105        self.budget.charge(bytes.len())?;
106        if !self.measure {
107            // Preflight reserves once before any payload is copied. Reallocating
108            // a populated Vec could leave sensitive bytes in the old allocation.
109            if end > self.bytes.capacity() {
110                return Err(error(ErrorReason::OutputLimit));
111            }
112            self.bytes.extend_from_slice(bytes);
113        }
114        self.length = end;
115        Ok(())
116    }
117
118    fn argument(&mut self, major: MajorType, value: u64) -> Result<(), CborError> {
119        let octets = Zeroizing::new(value.to_be_bytes());
120        let (info, start) = match preferred_width(value) {
121            ArgumentWidth::Inline => {
122                let inline =
123                    u8::try_from(value).map_err(|_| error(ErrorReason::ArithmeticOverflow))?;
124                return self.append(&[major.prefix() | inline]);
125            }
126            ArgumentWidth::One => (24, 7),
127            ArgumentWidth::Two => (25, 6),
128            ArgumentWidth::Four => (26, 4),
129            ArgumentWidth::Eight => (27, 0),
130            _ => return Err(error(ErrorReason::ArithmeticOverflow)),
131        };
132        self.append(&[major.prefix() | info])?;
133        self.append(
134            octets
135                .get(start..)
136                .ok_or(error(ErrorReason::ArithmeticOverflow))?,
137        )
138    }
139
140    fn count(&mut self, count: usize, map: bool) -> Result<u64, CborError> {
141        if count > self.budget.limits.entries {
142            return Err(error(ErrorReason::EntryLimit));
143        }
144        let children = if map {
145            count
146                .checked_mul(2)
147                .ok_or(error(ErrorReason::ArithmeticOverflow))?
148        } else {
149            count
150        };
151        self.budget.declared_nodes(children)?;
152        u64::try_from(count).map_err(|_| error(ErrorReason::ArithmeticOverflow))
153    }
154
155    fn value(&mut self, value: &ValueRef<'_>, depth: usize) -> Result<(), CborError> {
156        self.budget.charge(1)?;
157        if let ValueRef::Received(frame) = value {
158            // Account the original structure, not a second semantic tree. Final
159            // profile validation rejects incompatible widths rather than silently
160            // rebuilding bytes that may already be authenticated.
161            scan(
162                frame.received_bytes(),
163                &mut self.budget,
164                depth,
165                None,
166                true,
167                self.profile.lengths,
168            )?;
169            return self.append(frame.received_bytes());
170        }
171        self.budget.node()?;
172        match value {
173            ValueRef::Unsigned(value) => self.argument(MajorType::Unsigned, *value),
174            ValueRef::Negative(value) => self.argument(MajorType::Negative, *value),
175            ValueRef::Bytes(bytes) => {
176                self.budget.contents(bytes.len(), false)?;
177                self.argument(
178                    MajorType::Bytes,
179                    u64::try_from(bytes.len())
180                        .map_err(|_| error(ErrorReason::ArithmeticOverflow))?,
181                )?;
182                self.append(bytes)
183            }
184            ValueRef::Text(text) => {
185                self.budget.contents(text.len(), true)?;
186                self.argument(
187                    MajorType::Text,
188                    u64::try_from(text.len())
189                        .map_err(|_| error(ErrorReason::ArithmeticOverflow))?,
190                )?;
191                self.append(text.as_bytes())
192            }
193            ValueRef::Array(values) => {
194                let depth = self.budget.enter(depth)?;
195                let count = self.count(values.len(), false)?;
196                self.argument(MajorType::Array, count)?;
197                for value in *values {
198                    self.value(value, depth)?;
199                }
200                Ok(())
201            }
202            ValueRef::Map(entries) => {
203                let depth = self.budget.enter(depth)?;
204                let count = self.count(entries.len(), true)?;
205                self.argument(MajorType::Map, count)?;
206                for entry in *entries {
207                    self.value(&entry.key, depth)?;
208                    self.value(&entry.value, depth)?;
209                }
210                Ok(())
211            }
212            ValueRef::Tag(tag, child) => {
213                let depth = self.budget.enter(depth)?;
214                self.argument(MajorType::Tag, *tag)?;
215                self.value(child, depth)
216            }
217            ValueRef::Float(value) => {
218                value.check(self.profile.floats)?;
219                let width = if self.profile.serialization == Serialization::Preferred {
220                    value.shortest()
221                } else {
222                    value.width()
223                };
224                let bits = Zeroizing::new(value.at_width(width)?.to_be_bytes());
225                let (header, start) = match width {
226                    FloatWidth::Binary16 => (0xf9, 6),
227                    FloatWidth::Binary32 => (0xfa, 4),
228                    FloatWidth::Binary64 => (0xfb, 0),
229                };
230                self.append(&[header])?;
231                self.append(
232                    bits.get(start..)
233                        .ok_or(error(ErrorReason::ArithmeticOverflow))?,
234                )
235            }
236            ValueRef::Bool(value) => self.append(&[if *value { 0xf5 } else { 0xf4 }]),
237            ValueRef::Null => self.append(&[0xf6]),
238            ValueRef::Undefined => self.append(&[0xf7]),
239            ValueRef::Simple(value) => match value {
240                0..=23 => self.append(&[0xe0 | value]),
241                32..=255 => self.append(&[0xf8, *value]),
242                _ => Err(error(ErrorReason::InvalidSimpleValue)),
243            },
244            ValueRef::Received(_) => Err(error(ErrorReason::WrongType)),
245        }
246    }
247}
248
249/// Encode general CBOR into protected output, preserving map order and received
250/// items. Constructed arguments use shortest widths; the selected profile
251/// controls float shortening, validity, and optional key-order enforcement.
252pub fn encode(
253    value: &ValueRef<'_>,
254    profile: Profile,
255    limits: Limits,
256) -> Result<EncodedCbor, CborError> {
257    let mut measure = Encoder {
258        bytes: Zeroizing::new(Vec::new()),
259        length: 0,
260        measure: true,
261        budget: Budget::new(limits),
262        profile,
263    };
264    measure.value(value, 0)?;
265    let mut bytes = Zeroizing::new(Vec::new());
266    bytes
267        .try_reserve_exact(measure.length)
268        .map_err(|_| error(ErrorReason::AllocationFailure))?;
269    let mut budget = Budget::new(limits);
270    budget.work = measure.budget.work;
271    let mut encoder = Encoder {
272        bytes,
273        length: 0,
274        measure: false,
275        budget,
276        profile,
277    };
278    encoder.value(value, 0)?;
279    // All passes share work credits. Structural totals are checked separately
280    // per pass so the published node/content limits describe the actual output.
281    let mut validation = Budget::new(limits);
282    validation.work = encoder.budget.work;
283    scan(
284        &encoder.bytes,
285        &mut validation,
286        0,
287        Some(profile),
288        true,
289        profile.lengths,
290    )?;
291    Ok(EncodedCbor {
292        bytes: encoder.bytes,
293    })
294}