1use crate::node::Node;
5
6#[derive(Debug, Clone, PartialEq)]
8pub struct Value {
9 pub range: [usize; 2],
10 pub kind: ValueKind,
11 pub indefinite: bool,
13}
14
15#[derive(Debug, Clone, PartialEq)]
16pub enum ValueKind {
17 Uint(u64),
18 Nint(u64),
20 Float {
22 value: f64,
23 width: u8,
24 },
25 Bool(bool),
26 Null,
27 Undefined,
28 Simple(u8),
30 Bytes {
31 data: Vec<u8>,
32 decoded: Option<Box<Node>>,
34 },
35 Text(String),
36 Array(Vec<Value>),
37 Map(Vec<(Value, Value)>),
38 Tag(u64, Box<Value>),
39 Ext {
41 type_: i8,
42 data: Vec<u8>,
43 },
44}
45
46impl Value {
47 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 pub fn untagged(&self) -> &Value {
60 match &self.kind {
61 ValueKind::Tag(_, inner) => inner.untagged(),
62 _ => self,
63 }
64 }
65}
66
67pub(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
86pub(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
113pub(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
130pub(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
162pub(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
182pub(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
206pub(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
230pub(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
243pub(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
255fn in_year_range(epoch: i64) -> bool {
257 let (y, _, _) = civil_from_days(epoch.div_euclid(86_400));
258 (0..=9999).contains(&y)
259}
260
261pub(crate) fn iso_utc_checked(epoch: i64) -> Option<String> {
266 in_year_range(epoch).then(|| iso_utc(epoch))
267}
268
269fn 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
281pub(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
286pub(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
319fn 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; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; let y = yoe + era * 400;
326 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; 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 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 assert_eq!(
355 iso_utc_checked(253_402_300_799).unwrap(),
356 "9999-12-31T23:59:59Z"
357 );
358 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 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 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 assert!(keys_simple(&[map(v(ValueKind::Text("k".into())))], 23, 23));
384 assert!(!keys_simple(&[map(v(ValueKind::Bool(true)))], 127, 31));
385 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 assert_eq!(
397 bignum_decimal(&[1, 0, 0, 0, 0, 0, 0, 0, 0], false),
398 "18446744073709551616"
399 );
400 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}