Skip to main content

codec_cbor/
encode_dag_cbor.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use crate::{CborError, CborValue, MAX_DAG_CBOR_INPUT_LEN, MAX_NESTING_DEPTH};
6
7const MT_UINT: u8 = 0;
8const MT_NEGINT: u8 = 1;
9const MT_BYTES: u8 = 2;
10const MT_STRING: u8 = 3;
11const MT_ARRAY: u8 = 4;
12const MT_MAP: u8 = 5;
13
14/// Encode a value using canonical DAG-CBOR.
15///
16/// This encoding:
17/// - uses definite-length, shortest-form (canonical) integer headers only
18/// - orders map keys by RFC 8949 core deterministic rules: shorter encoded
19///   key first, then bytewise lexical order among equal lengths
20/// - contains no floats, tags, or indefinite-length items
21/// - is deterministic and cryptographically stable, so equal values always
22///   encode to identical bytes (a prerequisite for stable content IDs)
23pub fn encode_dag_cbor(value: &CborValue) -> Result<Vec<u8>, CborError> {
24    let mut out = Vec::new();
25    encode_value(value, &mut out, 0)?;
26    Ok(out)
27}
28
29fn encode_value(v: &CborValue, out: &mut Vec<u8>, depth: usize) -> Result<(), CborError> {
30    match v {
31        CborValue::Null => push_byte(out, 0xf6)?,
32        CborValue::Bool(false) => push_byte(out, 0xf4)?,
33        CborValue::Bool(true) => push_byte(out, 0xf5)?,
34
35        CborValue::Int(n) => {
36            if *n >= 0 {
37                write_header(MT_UINT, n.unsigned_abs(), out)?;
38            } else {
39                write_header(MT_NEGINT, n.unsigned_abs() - 1, out)?;
40            }
41        }
42
43        CborValue::Bytes(b) => {
44            write_header(MT_BYTES, len_as_u64(b.len())?, out)?;
45            extend_bytes(out, b)?;
46        }
47
48        CborValue::String(s) => {
49            let bytes = s.as_bytes();
50            write_header(MT_STRING, len_as_u64(bytes.len())?, out)?;
51            extend_bytes(out, bytes)?;
52        }
53
54        CborValue::Array(arr) => {
55            let child_depth = descend(depth)?;
56            ensure_minimum_encoded_len(arr.len(), 1)?;
57            write_header(MT_ARRAY, len_as_u64(arr.len())?, out)?;
58            for v in arr {
59                encode_value(v, out, child_depth)?;
60            }
61        }
62
63        CborValue::Map(entries) => {
64            let child_depth = descend(depth)?;
65            ensure_minimum_encoded_len(entries.len(), 2)?;
66            // RFC 8949 core deterministic ordering sorts text keys by the
67            // length of their encoded bytes first, then by bytewise lexical
68            // order. did:me vectors rely on this exact order for stable CIDs.
69            let mut sorted: Vec<(&String, &CborValue)> =
70                entries.iter().map(|(key, value)| (key, value)).collect();
71            sorted.sort_by(|(ka, _), (kb, _)| {
72                ka.len()
73                    .cmp(&kb.len())
74                    .then_with(|| ka.as_bytes().cmp(kb.as_bytes()))
75            });
76
77            write_header(MT_MAP, len_as_u64(sorted.len())?, out)?;
78
79            for (k, v) in sorted {
80                let kb = k.as_bytes();
81                write_header(MT_STRING, len_as_u64(kb.len())?, out)?;
82                extend_bytes(out, kb)?;
83                encode_value(v, out, child_depth)?;
84            }
85        }
86    }
87    Ok(())
88}
89
90/// Widens a container length to the `u64` argument width CBOR headers use.
91///
92/// This is a widening conversion — `usize` is at most 64 bits on every
93/// supported target — so it never loses information on supported platforms,
94/// while still returning a typed error if that assumption is violated.
95fn len_as_u64(len: usize) -> Result<u64, CborError> {
96    u64::try_from(len).map_err(|_| CborError::LengthTooLarge)
97}
98
99/// Writes a CBOR head byte plus the minimal big-endian argument encoding
100/// for `value`, following canonical (shortest-form) integer rules.
101///
102/// Each branch slices the exact low-order bytes of `value.to_be_bytes()`
103/// that its range guarantees are significant, so no narrowing cast or
104/// truncation is involved.
105fn write_header(mt: u8, value: u64, out: &mut Vec<u8>) -> Result<(), CborError> {
106    let be = value.to_be_bytes();
107    let head = mt << 5;
108    if value < 24 {
109        // The whole argument fits in the low 5 bits of the head byte.
110        push_byte(out, head | be[7])?;
111    } else if value < 0x100 {
112        push_byte(out, head | 24)?;
113        extend_bytes(out, &be[7..8])?;
114    } else if value < 0x1_0000 {
115        push_byte(out, head | 25)?;
116        extend_bytes(out, &be[6..8])?;
117    } else if value < 0x1_0000_0000 {
118        push_byte(out, head | 26)?;
119        extend_bytes(out, &be[4..8])?;
120    } else {
121        push_byte(out, head | 27)?;
122        extend_bytes(out, &be)?;
123    }
124    Ok(())
125}
126
127fn push_byte(out: &mut Vec<u8>, byte: u8) -> Result<(), CborError> {
128    let next_len = out.len().checked_add(1).ok_or(CborError::OffsetOverflow)?;
129    if next_len > MAX_DAG_CBOR_INPUT_LEN {
130        return Err(CborError::OutputTooLarge);
131    }
132    out.push(byte);
133    Ok(())
134}
135
136fn extend_bytes(out: &mut Vec<u8>, bytes: &[u8]) -> Result<(), CborError> {
137    let next_len = out
138        .len()
139        .checked_add(bytes.len())
140        .ok_or(CborError::OffsetOverflow)?;
141    if next_len > MAX_DAG_CBOR_INPUT_LEN {
142        return Err(CborError::OutputTooLarge);
143    }
144    out.extend_from_slice(bytes);
145    Ok(())
146}
147
148fn descend(depth: usize) -> Result<usize, CborError> {
149    let next = depth.checked_add(1).ok_or(CborError::OffsetOverflow)?;
150    if next > MAX_NESTING_DEPTH {
151        return Err(CborError::DepthExceeded);
152    }
153    Ok(next)
154}
155
156fn ensure_minimum_encoded_len(count: usize, min_element_len: usize) -> Result<(), CborError> {
157    let minimum = count
158        .checked_mul(min_element_len)
159        .ok_or(CborError::OffsetOverflow)?;
160    if minimum > MAX_DAG_CBOR_INPUT_LEN {
161        return Err(CborError::OutputTooLarge);
162    }
163    Ok(())
164}