Skip to main content

bytepeel_core/
value.rs

1//! A codec-neutral value tree, shared by CBOR (RFC 8949) and
2//! MessagePack. Values carry byte ranges like the rest of the tree.
3
4use crate::node::Node;
5
6/// One decoded value: a byte range and its kind.
7#[derive(Debug, Clone, PartialEq)]
8pub struct Value {
9    pub range: [usize; 2],
10    pub kind: ValueKind,
11    /// True when this value used an indefinite-length form (CBOR).
12    pub indefinite: bool,
13}
14
15#[derive(Debug, Clone, PartialEq)]
16pub enum ValueKind {
17    Uint(u64),
18    /// `-1 - n` (CBOR major type 1).
19    Nint(u64),
20    /// A float, remembering its source width (16, 32 or 64 bits).
21    Float {
22        value: f64,
23        width: u8,
24    },
25    Bool(bool),
26    Null,
27    Undefined,
28    /// A CBOR simple value (0..=255).
29    Simple(u8),
30    Bytes {
31        data: Vec<u8>,
32        /// Set when the bytes are themselves CBOR/DER/protobuf/... .
33        decoded: Option<Box<Node>>,
34    },
35    Text(String),
36    Array(Vec<Value>),
37    Map(Vec<(Value, Value)>),
38    Tag(u64, Box<Value>),
39    /// A MessagePack extension: its signed type and raw data.
40    Ext {
41        type_: i8,
42        data: Vec<u8>,
43    },
44}
45
46impl Value {
47    /// The bytes `--format raw` writes: a byte string's or extension's bytes,
48    /// or a text string's UTF-8. `None` for everything else.
49    pub fn payload(&self) -> Option<Vec<u8>> {
50        match &self.kind {
51            ValueKind::Bytes { data, .. } => Some(data.clone()),
52            ValueKind::Text(t) => Some(t.as_bytes().to_vec()),
53            ValueKind::Ext { data, .. } => Some(data.clone()),
54            _ => None,
55        }
56    }
57
58    /// The innermost value, following tags.
59    pub fn untagged(&self) -> &Value {
60        match &self.kind {
61            ValueKind::Tag(_, inner) => inner.untagged(),
62            _ => self,
63        }
64    }
65}
66
67/// The JSON/tree discriminant for a value kind.
68pub(crate) fn type_name(k: &ValueKind) -> &'static str {
69    match k {
70        ValueKind::Uint(_) => "uint",
71        ValueKind::Nint(_) => "nint",
72        ValueKind::Float { .. } => "float",
73        ValueKind::Bool(_) => "bool",
74        ValueKind::Null => "null",
75        ValueKind::Undefined => "undefined",
76        ValueKind::Simple(_) => "simple",
77        ValueKind::Bytes { .. } => "bytes",
78        ValueKind::Text(_) => "text",
79        ValueKind::Array(_) => "array",
80        ValueKind::Map(_) => "map",
81        ValueKind::Tag(..) => "tag",
82        ValueKind::Ext { .. } => "ext",
83    }
84}
85
86/// Auto-detection confidence for a structurally valid CBOR/MessagePack tree.
87///
88/// Maps are the strong signal: 0.9 when every key is text or a small integer
89/// (at most `max_uint` / `-1 - max_nint`), 0.7 with other keys. A tree with no
90/// map at all (arrays of scalars) is weak evidence, since many protobuf
91/// messages whose first tag is for field 16+ also parse that way: 0.6, so a
92/// plausible protobuf reading (0.9) wins and the array shows up only in
93/// `AMBIGUOUS_FORMAT`.
94pub(crate) fn structure_confidence(values: &[Value], max_uint: u64, max_nint: u64) -> f64 {
95    if !values.iter().any(contains_map) {
96        0.6
97    } else if keys_simple(values, max_uint, max_nint) {
98        0.9
99    } else {
100        0.7
101    }
102}
103
104fn contains_map(v: &Value) -> bool {
105    match &v.kind {
106        ValueKind::Map(_) => true,
107        ValueKind::Array(items) => items.iter().any(contains_map),
108        ValueKind::Tag(_, inner) => contains_map(inner),
109        _ => false,
110    }
111}
112
113/// Every map key anywhere in `values` is a text string (CBOR tags are
114/// followed). A tie-break signal between detection candidates.
115pub(crate) fn keys_all_text(values: &[Value]) -> bool {
116    values.iter().all(value_keys_all_text)
117}
118
119fn value_keys_all_text(v: &Value) -> bool {
120    match &v.kind {
121        ValueKind::Map(entries) => entries.iter().all(|(k, val)| {
122            matches!(&k.untagged().kind, ValueKind::Text(_)) && value_keys_all_text(val)
123        }),
124        ValueKind::Array(items) => items.iter().all(value_keys_all_text),
125        ValueKind::Tag(_, inner) => value_keys_all_text(inner),
126        _ => true,
127    }
128}
129
130/// Every map key anywhere in `values` is a text string, a `Uint` `<= max_uint`,
131/// or a `Nint` whose stored `n` (value `-1 - n`) is `<= max_nint`.
132///
133/// Shared by CBOR (`23, 23`) and MessagePack (its fixint ranges, `127, 31`).
134pub(crate) fn keys_simple(values: &[Value], max_uint: u64, max_nint: u64) -> bool {
135    values
136        .iter()
137        .all(|v| value_keys_simple(v, max_uint, max_nint))
138}
139
140fn value_keys_simple(v: &Value, max_uint: u64, max_nint: u64) -> bool {
141    match &v.kind {
142        ValueKind::Map(entries) => entries.iter().all(|(k, val)| {
143            is_simple_key(k, max_uint, max_nint) && value_keys_simple(val, max_uint, max_nint)
144        }),
145        ValueKind::Array(items) => items
146            .iter()
147            .all(|x| value_keys_simple(x, max_uint, max_nint)),
148        ValueKind::Tag(_, inner) => value_keys_simple(inner, max_uint, max_nint),
149        _ => true,
150    }
151}
152
153fn is_simple_key(k: &Value, max_uint: u64, max_nint: u64) -> bool {
154    match &k.untagged().kind {
155        ValueKind::Text(_) => true,
156        ValueKind::Uint(n) => *n <= max_uint,
157        ValueKind::Nint(n) => *n <= max_nint,
158        _ => false,
159    }
160}
161
162/// Well-known CBOR tag names (RFC 8949 Appendix B and common registrations).
163pub(crate) fn tag_name(n: u64) -> Option<&'static str> {
164    Some(match n {
165        0 => "datetime",
166        1 => "epoch",
167        2 => "bignum",
168        3 => "negbignum",
169        4 => "decimal",
170        5 => "bigfloat",
171        21 => "base64url",
172        22 => "base64",
173        23 => "base16",
174        24 => "cbor",
175        32 => "uri",
176        37 => "uuid",
177        55799 => "self-describe",
178        _ => return None,
179    })
180}
181
182/// A tag-1 (epoch) value as an ISO-8601 UTC string, when it is a number.
183pub(crate) fn epoch_iso(v: &Value) -> Option<String> {
184    match &v.kind {
185        ValueKind::Uint(n) if *n <= i64::MAX as u64 => iso_utc_checked(*n as i64),
186        ValueKind::Nint(n) => {
187            let val = -(*n as i128) - 1;
188            if val >= i64::MIN as i128 {
189                iso_utc_checked(val as i64)
190            } else {
191                None
192            }
193        }
194        ValueKind::Float { value, .. } if value.is_finite() => {
195            let secs = value.trunc();
196            if (-9.223_372_036_854_776e18..=9.223_372_036_854_776e18).contains(&secs) {
197                iso_utc_checked(secs as i64)
198            } else {
199                None
200            }
201        }
202        _ => None,
203    }
204}
205
206/// A CBOR bignum (tag 2/3) as a decimal string. `data` is the big-endian
207/// unsigned magnitude; tag 3 means `-1 - magnitude`.
208pub(crate) fn bignum_decimal(data: &[u8], negative: bool) -> String {
209    let mut mag = data.to_vec();
210    if negative {
211        let mut carry = true;
212        for b in mag.iter_mut().rev() {
213            if !carry {
214                break;
215            }
216            let (v, c) = b.overflowing_add(1);
217            *b = v;
218            carry = c;
219        }
220        if carry {
221            mag.insert(0, 1);
222        }
223    }
224    let mut signed = vec![0u8];
225    signed.extend_from_slice(&mag);
226    let d = crate::der::int_decimal(&signed);
227    if negative { format!("-{d}") } else { d }
228}
229
230/// A 16-byte value as a canonical UUID string.
231pub(crate) fn uuid_string(data: &[u8]) -> String {
232    let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
233    format!(
234        "{}-{}-{}-{}-{}",
235        &hex[0..8],
236        &hex[8..12],
237        &hex[12..16],
238        &hex[16..20],
239        &hex[20..32]
240    )
241}
242
243/// Epoch seconds to `YYYY-MM-DDTHH:MM:SSZ` (Howard Hinnant's `civil_from_days`).
244///
245/// This is unchecked: a year outside `0000..=9999` is formatted with a wrong
246/// width. Callers that put the result in output use [`iso_utc_checked`].
247pub(crate) fn iso_utc(epoch: i64) -> String {
248    let days = epoch.div_euclid(86_400);
249    let secs = epoch.rem_euclid(86_400);
250    let (h, mi, s) = (secs / 3600, (secs % 3600) / 60, secs % 60);
251    let (y, m, d) = civil_from_days(days);
252    format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z")
253}
254
255/// True when epoch seconds fall in a year RFC 3339 can represent (0000..=9999).
256fn in_year_range(epoch: i64) -> bool {
257    let (y, _, _) = civil_from_days(epoch.div_euclid(86_400));
258    (0..=9999).contains(&y)
259}
260
261/// Like [`iso_utc`], but `None` when the year is outside `0000..=9999`.
262///
263/// Shared by CBOR tag 1, MessagePack timestamps and JWT `exp`/`nbf`/`iat`, so
264/// none of them emit an out-of-range (malformed) date.
265pub(crate) fn iso_utc_checked(epoch: i64) -> Option<String> {
266    in_year_range(epoch).then(|| iso_utc(epoch))
267}
268
269/// Epoch seconds plus nanoseconds to ISO-8601 UTC, trimming trailing zero
270/// digits from the fraction (so whole seconds get no fraction at all).
271fn iso_utc_nanos(secs: i64, nanos: u32) -> String {
272    let base = iso_utc(secs);
273    if nanos == 0 {
274        return base;
275    }
276    let frac = format!("{nanos:09}");
277    let frac = frac.trim_end_matches('0');
278    format!("{}.{}Z", &base[..base.len() - 1], frac)
279}
280
281/// Like [`iso_utc_nanos`], but `None` outside the `0000..=9999` year range.
282pub(crate) fn iso_utc_nanos_checked(secs: i64, nanos: u32) -> Option<String> {
283    in_year_range(secs).then(|| iso_utc_nanos(secs, nanos))
284}
285
286/// A MessagePack timestamp extension (type -1) as ISO-8601 UTC.
287///
288/// Handles the 4-byte (seconds), 8-byte (30-bit nanoseconds + 34-bit seconds)
289/// and 12-byte (nanoseconds + signed seconds, for dates before 1970) forms.
290pub(crate) fn ext_iso(type_: i8, data: &[u8]) -> Option<String> {
291    if type_ != -1 {
292        return None;
293    }
294    let (secs, nanos) = match data.len() {
295        4 => (
296            i64::from(u32::from_be_bytes([data[0], data[1], data[2], data[3]])),
297            0,
298        ),
299        8 => {
300            let v = u64::from_be_bytes([
301                data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
302            ]);
303            ((v & 0x3_FFFF_FFFF) as i64, (v >> 34) as u32)
304        }
305        12 => (
306            i64::from_be_bytes([
307                data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11],
308            ]),
309            u32::from_be_bytes([data[0], data[1], data[2], data[3]]),
310        ),
311        _ => return None,
312    };
313    if nanos >= 1_000_000_000 {
314        return None;
315    }
316    iso_utc_nanos_checked(secs, nanos)
317}
318
319/// Days since 1970-01-01 -> (year, month, day).
320fn civil_from_days(z: i64) -> (i64, u32, u32) {
321    let z = z + 719_468;
322    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
323    let doe = z - era * 146_097; // [0, 146096]
324    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // [0, 399]
325    let y = yoe + era * 400;
326    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
327    let mp = (5 * doy + 2) / 153; // [0, 11]
328    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
329    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
330    let y = if m <= 2 { y + 1 } else { y };
331    (y, m as u32, d as u32)
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn dates() {
340        assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z");
341        assert_eq!(iso_utc(-1), "1969-12-31T23:59:59Z");
342        assert_eq!(iso_utc(1_363_896_240), "2013-03-21T20:04:00Z");
343    }
344
345    #[test]
346    fn iso_year_range() {
347        // In range, including before 1970.
348        assert_eq!(iso_utc_checked(-1).unwrap(), "1969-12-31T23:59:59Z");
349        assert_eq!(
350            iso_utc_nanos_checked(-1, 500_000_000).unwrap(),
351            "1969-12-31T23:59:59.5Z"
352        );
353        // 9999-12-31T23:59:59Z is the last representable second.
354        assert_eq!(
355            iso_utc_checked(253_402_300_799).unwrap(),
356            "9999-12-31T23:59:59Z"
357        );
358        // Year 10000 and i64::MIN are out of RFC 3339 range.
359        assert!(iso_utc_checked(253_402_300_800).is_none());
360        assert!(iso_utc_checked(i64::MIN).is_none());
361        assert!(iso_utc_nanos_checked(i64::MIN, 0).is_none());
362    }
363
364    #[test]
365    fn key_thresholds() {
366        let v = |kind| Value {
367            range: [0, 0],
368            kind,
369            indefinite: false,
370        };
371        let map = |k| v(ValueKind::Map(vec![(k, v(ValueKind::Null))]));
372        // CBOR allows 23, MessagePack's fixint range allows 127.
373        assert!(keys_simple(&[map(v(ValueKind::Uint(23)))], 23, 23));
374        assert!(!keys_simple(&[map(v(ValueKind::Uint(24)))], 23, 23));
375        assert!(keys_simple(&[map(v(ValueKind::Uint(24)))], 127, 31));
376        assert!(!keys_simple(&[map(v(ValueKind::Uint(128)))], 127, 31));
377        // Nint stores -1 - value: 23 means -24.
378        assert!(keys_simple(&[map(v(ValueKind::Nint(23)))], 23, 23));
379        assert!(!keys_simple(&[map(v(ValueKind::Nint(24)))], 23, 23));
380        assert!(keys_simple(&[map(v(ValueKind::Nint(31)))], 127, 31));
381        assert!(!keys_simple(&[map(v(ValueKind::Nint(32)))], 127, 31));
382        // Non-integer keys.
383        assert!(keys_simple(&[map(v(ValueKind::Text("k".into())))], 23, 23));
384        assert!(!keys_simple(&[map(v(ValueKind::Bool(true)))], 127, 31));
385        // All-text is stricter, and recursion reaches nested maps.
386        assert!(keys_all_text(&[map(v(ValueKind::Text("k".into())))]));
387        assert!(!keys_all_text(&[map(v(ValueKind::Uint(1)))]));
388        let nested = v(ValueKind::Array(vec![map(v(ValueKind::Uint(1)))]));
389        assert!(keys_simple(std::slice::from_ref(&nested), 23, 23));
390        assert!(!keys_all_text(std::slice::from_ref(&nested)));
391    }
392
393    #[test]
394    fn bignums() {
395        // 2^64 = 18446744073709551616
396        assert_eq!(
397            bignum_decimal(&[1, 0, 0, 0, 0, 0, 0, 0, 0], false),
398            "18446744073709551616"
399        );
400        // -1 - 2^64 = -18446744073709551617
401        assert_eq!(
402            bignum_decimal(&[1, 0, 0, 0, 0, 0, 0, 0, 0], true),
403            "-18446744073709551617"
404        );
405        assert_eq!(bignum_decimal(&[], true), "-1");
406        assert_eq!(bignum_decimal(&[], false), "0");
407    }
408
409    #[test]
410    fn uuids() {
411        assert_eq!(
412            uuid_string(&[
413                0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
414                0x77, 0x88
415            ]),
416            "12345678-9abc-def0-1122-334455667788"
417        );
418    }
419}