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