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, MajorTypeCode};
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) => self.bytes_value(bytes, false),
176            ValueRef::Text(text) => self.bytes_value(text.as_bytes(), true),
177            ValueRef::Array(values) => {
178                let depth = self.budget.enter(depth)?;
179                let count = self.count(values.len(), false)?;
180                self.argument(MajorType::Array, count)?;
181                for value in *values {
182                    self.value(value, depth)?;
183                }
184                Ok(())
185            }
186            ValueRef::Map(entries) => {
187                let depth = self.budget.enter(depth)?;
188                let count = self.count(entries.len(), true)?;
189                self.argument(MajorType::Map, count)?;
190                for entry in *entries {
191                    self.value(&entry.key, depth)?;
192                    self.value(&entry.value, depth)?;
193                }
194                Ok(())
195            }
196            ValueRef::Tag(tag, child) => {
197                let depth = self.budget.enter(depth)?;
198                self.argument(MajorType::Tag, *tag)?;
199                self.value(child, depth)
200            }
201            ValueRef::Float(value) => self.float_value(value),
202            ValueRef::Bool(value) => self.append(&[if *value { 0xf5 } else { 0xf4 }]),
203            ValueRef::Null => self.append(&[0xf6]),
204            ValueRef::Undefined => self.append(&[0xf7]),
205            ValueRef::Simple(value) => self.simple_value(*value),
206            ValueRef::Received(_) => Err(error(ErrorReason::WrongType)),
207        }
208    }
209    fn contract_value(
210        &mut self,
211        node: &codec_proto::generated::proto::reallyme::codec::v1::CodecGeneralCborValue,
212        depth: usize,
213    ) -> Result<(), CborError> {
214        use codec_proto::generated::proto::reallyme::codec::v1::codec_general_cbor_value::Value;
215
216        let value = node.value.as_ref().ok_or(error(ErrorReason::WrongType))?;
217        self.budget.charge(1)?;
218        if let Value::ReceivedValue(value) = value {
219            // Native Received holds a Frame, which proves exact framing and
220            // the hard input ceiling. Re-establish that proof for wire bytes
221            // before they can be embedded in a constructed container.
222            if value.value.is_empty() {
223                return Err(error(ErrorReason::EmptyInput));
224            }
225            if value.value.len() > super::limits::MAX_BYTES {
226                return Err(error(ErrorReason::InputLimit));
227            }
228            let received = scan(
229                &value.value,
230                &mut self.budget,
231                depth,
232                None,
233                true,
234                self.profile.lengths,
235            )?;
236            if received.received_bytes().len() != value.value.len() {
237                return Err(error(ErrorReason::TrailingData));
238            }
239            return self.append(&value.value);
240        }
241        self.budget.node()?;
242        match value {
243            Value::ArrayValue(array) => {
244                let depth = self.budget.enter(depth)?;
245                let count = self.count(array.values.len(), false)?;
246                self.argument(MajorType::Array, count)?;
247                for child in &array.values {
248                    self.contract_value(child, depth)?;
249                }
250                Ok(())
251            }
252            Value::MapValue(map) => {
253                let depth = self.budget.enter(depth)?;
254                let count = self.count(map.entries.len(), true)?;
255                self.argument(MajorType::Map, count)?;
256                for entry in &map.entries {
257                    self.contract_value(
258                        entry.key.as_option().ok_or(error(ErrorReason::WrongType))?,
259                        depth,
260                    )?;
261                    self.contract_value(
262                        entry
263                            .value
264                            .as_option()
265                            .ok_or(error(ErrorReason::WrongType))?,
266                        depth,
267                    )?;
268                }
269                Ok(())
270            }
271            Value::TagValue(tag) => {
272                let depth = self.budget.enter(depth)?;
273                self.argument(MajorType::Tag, tag.tag)?;
274                self.contract_value(
275                    tag.value.as_option().ok_or(error(ErrorReason::WrongType))?,
276                    depth,
277                )
278            }
279            // Scalar transport nodes enter the native scalar writer without
280            // charging a second structural node or introducing payload copies.
281            value => self.contract_scalar(value),
282        }
283    }
284
285    fn contract_scalar(
286        &mut self,
287        value: &codec_proto::generated::proto::reallyme::codec::v1::codec_general_cbor_value::Value,
288    ) -> Result<(), CborError> {
289        use super::encode_contract::float;
290        use codec_proto::generated::proto::reallyme::codec::v1::codec_general_cbor_value::Value;
291        match value {
292            Value::UnsignedValue(v) => self.argument(MajorType::Unsigned, v.argument),
293            Value::NegativeValue(v) => self.argument(MajorType::Negative, v.argument),
294            Value::BytesValue(v) => self.bytes_value(&v.value, false),
295            Value::TextValue(v) => self.bytes_value(v.value.as_bytes(), true),
296            Value::FloatValue(v) => self.float_value(&float(v)?),
297            Value::BoolValue(v) => self.append(&[if v.value { 0xf5 } else { 0xf4 }]),
298            Value::NullValue(_) => self.append(&[0xf6]),
299            Value::UndefinedValue(_) => self.append(&[0xf7]),
300            Value::SimpleValue(v) => self.simple_value(
301                u8::try_from(v.value).map_err(|_| error(ErrorReason::InvalidSimpleValue))?,
302            ),
303            _ => Err(error(ErrorReason::WrongType)),
304        }
305    }
306
307    fn bytes_value(&mut self, bytes: &[u8], text: bool) -> Result<(), CborError> {
308        self.budget.contents(bytes.len(), text)?;
309        self.argument(
310            if text {
311                MajorType::Text
312            } else {
313                MajorType::Bytes
314            },
315            u64::try_from(bytes.len()).map_err(|_| error(ErrorReason::ArithmeticOverflow))?,
316        )?;
317        self.append(bytes)
318    }
319
320    fn simple_value(&mut self, value: u8) -> Result<(), CborError> {
321        match value {
322            0..=23 => self.append(&[0xe0 | value]),
323            32..=255 => self.append(&[0xf8, value]),
324            _ => Err(error(ErrorReason::InvalidSimpleValue)),
325        }
326    }
327
328    fn float_value(&mut self, value: &Float) -> Result<(), CborError> {
329        value.check(self.profile.floats)?;
330        let width = if self.profile.serialization == Serialization::Preferred {
331            value.shortest()
332        } else {
333            value.width()
334        };
335        let bits = Zeroizing::new(value.at_width(width)?.to_be_bytes());
336        let (header, start) = match width {
337            FloatWidth::Binary16 => (0xf9, 6),
338            FloatWidth::Binary32 => (0xfa, 4),
339            FloatWidth::Binary64 => (0xfb, 0),
340            _ => return Err(error(ErrorReason::UnsupportedPolicy)),
341        };
342        self.append(&[header])?;
343        self.append(
344            bits.get(start..)
345                .ok_or(error(ErrorReason::ArithmeticOverflow))?,
346        )
347    }
348}
349
350/// Encode general CBOR into protected output, preserving map order and received
351/// items. Constructed arguments use shortest widths; the selected profile
352/// controls float shortening, validity, and optional key-order enforcement.
353pub fn encode(
354    value: &ValueRef<'_>,
355    profile: Profile,
356    limits: Limits,
357) -> Result<EncodedCbor, CborError> {
358    encode_with(profile, limits, |encoder| encoder.value(value, 0))
359}
360
361pub(super) fn encode_generated(
362    value: &codec_proto::generated::proto::reallyme::codec::v1::CodecGeneralCborValue,
363    profile: Profile,
364    limits: Limits,
365) -> Result<EncodedCbor, CborError> {
366    encode_with(profile, limits, |encoder| encoder.contract_value(value, 0))
367}
368
369fn encode_with(
370    profile: Profile,
371    limits: Limits,
372    visit: impl Fn(&mut Encoder) -> Result<(), CborError>,
373) -> Result<EncodedCbor, CborError> {
374    profile.ensure_supported()?;
375    let mut measure = Encoder {
376        bytes: Zeroizing::new(Vec::new()),
377        length: 0,
378        measure: true,
379        budget: Budget::new(limits),
380        profile,
381    };
382    visit(&mut measure)?;
383    let mut bytes = Zeroizing::new(Vec::new());
384    bytes
385        .try_reserve_exact(measure.length)
386        .map_err(|_| error(ErrorReason::AllocationFailure))?;
387    let mut budget = Budget::new(limits);
388    budget.work = measure.budget.work;
389    let mut encoder = Encoder {
390        bytes,
391        length: 0,
392        measure: false,
393        budget,
394        profile,
395    };
396    visit(&mut encoder)?;
397    // All passes share work credits. Structural totals are checked separately
398    // per pass so the published node/content limits describe the actual output.
399    let mut validation = Budget::new(limits);
400    validation.work = encoder.budget.work;
401    {
402        let validated = scan(
403            &encoder.bytes,
404            &mut validation,
405            0,
406            Some(profile),
407            true,
408            profile.lengths,
409        )?;
410        if validated.received_bytes().len() != encoder.bytes.len() {
411            return Err(error(ErrorReason::TrailingData));
412        }
413    }
414    Ok(EncodedCbor {
415        bytes: encoder.bytes,
416    })
417}