binyay 3.0.0

YAY command-line tool for parsing, formatting, and transcoding YAY documents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! CBOR transcoding: convert between YAY values and CBOR binary data.
//!
//! Mapping from CBOR to YAY:
//!   - CBOR null                  -> Value::Null
//!   - CBOR undefined             -> Value::Undefined
//!   - CBOR bool                  -> Value::Bool
//!   - CBOR unsigned/negative int -> Value::Integer (BigInt)
//!   - CBOR float (16/32/64)      -> Value::Float (promoted to f64)
//!   - CBOR text string           -> Value::String
//!   - CBOR byte string           -> Value::Bytes
//!   - CBOR array (det/indet)     -> Value::Array
//!   - CBOR map (det/indet)       -> Value::Object (text string keys only)
//!   - CBOR tag                   -> error (no YAY equivalent)
//!   - Any other CBOR value       -> error
//!
//! Mapping from YAY to CBOR:
//!   - Value::Null    -> CBOR null (simple value 22)
//!   - Value::Undefined -> CBOR undefined (simple value 23)
//!   - Value::Bool    -> CBOR bool (simple values 20/21)
//!   - Value::Integer -> CBOR integer (smallest encoding that fits)
//!   - Value::Float   -> CBOR float64 (always 9 bytes, never downgraded)
//!   - Value::String  -> CBOR text string (determinate length)
//!   - Value::Bytes   -> CBOR byte string (determinate length)
//!   - Value::Array   -> CBOR array (determinate length)
//!   - Value::Object  -> CBOR map (determinate length, text string keys)
//!
//! Integers outside CBOR's native range use standard bignum tags 2 and 3.

use ciborium_ll::{simple, Decoder, Header};
use libyay::Value;
use num_bigint::{BigInt, Sign};
use num_traits::ToPrimitive;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;

// ---------------------------------------------------------------------------
// Decode (CBOR -> YAY)
// ---------------------------------------------------------------------------

/// Decode CBOR bytes into a YAY Value.
pub fn decode(input: &[u8]) -> Result<Value, String> {
    raw_to_value(&decode_raw(input)?)
}

#[derive(Debug)]
enum RawValue {
    Undefined,
    Null,
    Bool(bool),
    Integer(BigInt),
    Float(f64),
    Text(String),
    Bytes(Vec<u8>),
    Array(Vec<RawValue>),
    Map(Vec<(RawValue, RawValue)>),
    Tag(u64, Box<RawValue>),
}

fn decode_raw(input: &[u8]) -> Result<RawValue, String> {
    let mut decoder = Decoder::from(input);
    let value = read_raw(&mut decoder)?;
    if decoder.offset() != input.len() {
        return Err("CBOR decode error: trailing data".to_string());
    }
    Ok(value)
}

fn read_raw(decoder: &mut Decoder<&[u8]>) -> Result<RawValue, String> {
    let header = decoder
        .pull()
        .map_err(|e| format!("CBOR decode error: {:?}", e))?;
    read_raw_header(decoder, header)
}

fn read_raw_header(decoder: &mut Decoder<&[u8]>, header: Header) -> Result<RawValue, String> {
    match header {
        Header::Positive(n) => Ok(RawValue::Integer(BigInt::from(n))),
        Header::Negative(n) => Ok(RawValue::Integer(-BigInt::from(n) - BigInt::from(1))),
        Header::Float(f) => Ok(RawValue::Float(f)),
        Header::Simple(simple::FALSE) => Ok(RawValue::Bool(false)),
        Header::Simple(simple::TRUE) => Ok(RawValue::Bool(true)),
        Header::Simple(simple::NULL) => Ok(RawValue::Null),
        Header::Simple(simple::UNDEFINED) => Ok(RawValue::Undefined),
        Header::Simple(n) => Err(format!("CBOR simple value {} has no YAY equivalent", n)),
        Header::Bytes(len) => Ok(RawValue::Bytes(read_bytes(decoder, len)?)),
        Header::Text(len) => {
            let bytes = read_bytes(decoder, len)?;
            let text = String::from_utf8(bytes)
                .map_err(|_| "CBOR text string is not valid UTF-8".to_string())?;
            Ok(RawValue::Text(text))
        }
        Header::Array(len) => {
            let mut values = Vec::new();
            match len {
                Some(len) => {
                    for _ in 0..len {
                        values.push(read_raw(decoder)?);
                    }
                }
                None => loop {
                    let header = decoder
                        .pull()
                        .map_err(|e| format!("CBOR decode error: {:?}", e))?;
                    if header == Header::Break {
                        break;
                    }
                    values.push(read_raw_header(decoder, header)?);
                },
            }
            Ok(RawValue::Array(values))
        }
        Header::Map(len) => {
            let mut pairs = Vec::new();
            match len {
                Some(len) => {
                    for _ in 0..len {
                        pairs.push((read_raw(decoder)?, read_raw(decoder)?));
                    }
                }
                None => loop {
                    let header = decoder
                        .pull()
                        .map_err(|e| format!("CBOR decode error: {:?}", e))?;
                    if header == Header::Break {
                        break;
                    }
                    let key = read_raw_header(decoder, header)?;
                    pairs.push((key, read_raw(decoder)?));
                },
            }
            Ok(RawValue::Map(pairs))
        }
        Header::Tag(tag) => Ok(RawValue::Tag(tag, Box::new(read_raw(decoder)?))),
        Header::Break => Err("CBOR decode error: unexpected break".to_string()),
    }
}

fn read_bytes(decoder: &mut Decoder<&[u8]>, len: Option<usize>) -> Result<Vec<u8>, String> {
    let mut output = Vec::new();
    let mut segments = decoder.bytes(len);
    while let Some(mut segment) = segments
        .pull()
        .map_err(|e| format!("CBOR decode error: {:?}", e))?
    {
        let mut buffer = [0u8; 1024];
        while let Some(chunk) = segment
            .pull(&mut buffer)
            .map_err(|e| format!("CBOR decode error: {:?}", e))?
        {
            output.extend_from_slice(chunk);
        }
    }
    Ok(output)
}

fn raw_to_value(raw: &RawValue) -> Result<Value, String> {
    match raw {
        RawValue::Undefined => Ok(Value::Undefined),
        RawValue::Null => Ok(Value::Null),
        RawValue::Bool(b) => Ok(Value::Bool(*b)),
        RawValue::Integer(n) => Ok(Value::Integer(n.clone())),
        RawValue::Float(f) => Ok(Value::Float(*f)),
        RawValue::Text(s) => Ok(Value::String(s.clone())),
        RawValue::Bytes(b) => Ok(Value::Bytes(b.clone())),
        RawValue::Array(values) => values
            .iter()
            .map(raw_to_value)
            .collect::<Result<Vec<_>, _>>()
            .map(Value::Array),
        RawValue::Map(pairs) => {
            let mut object = HashMap::new();
            for (key, value) in pairs {
                let key = match key {
                    RawValue::Text(s) => s.clone(),
                    _ => return Err(format!("CBOR map key must be a text string, got: {:?}", key)),
                };
                object.insert(key, raw_to_value(value)?);
            }
            Ok(Value::Object(object))
        }
        RawValue::Tag(2, inner) | RawValue::Tag(3, inner) => {
            let magnitude = match inner.as_ref() {
                RawValue::Bytes(bytes) => BigInt::from_bytes_be(Sign::Plus, bytes),
                _ => return Err("CBOR bignum tag 2 or 3 needs a byte string".to_string()),
            };
            if matches!(raw, RawValue::Tag(2, _)) {
                Ok(Value::Integer(magnitude))
            } else {
                Ok(Value::Integer(-magnitude - BigInt::from(1)))
            }
        }
        RawValue::Tag(280, inner) => match inner.as_ref() {
            RawValue::Text(name) => Ok(Value::Symbol(name.clone())),
            RawValue::Array(_) => Err("CBOR tag 280 over an array names an uninterned or packaged symbol; YAY symbols are interned by name".to_string()),
            _ => Err("CBOR tag 280 needs a text string".to_string()),
        },
        RawValue::Tag(tag, _) => Err(format!(
            "CBOR tagged value (tag {}) has no YAY equivalent",
            tag
        )),
    }
}

// ---------------------------------------------------------------------------
// Encode (YAY -> CBOR)
//
// We write CBOR directly rather than going through ciborium's Value type
// because ciborium unconditionally downgrades float64 to float16/float32
// when the value is representable in fewer bytes. The YAY-to-CBOR contract
// requires that all float64 values remain encoded as CBOR float64 (major
// type 7, additional info 27, 8-byte IEEE 754 payload).
// ---------------------------------------------------------------------------

/// Encode a YAY Value as CBOR bytes.
pub fn encode(value: &Value) -> Result<Vec<u8>, String> {
    let mut buf = Vec::new();
    write_value(&mut buf, value)?;
    Ok(buf)
}

fn write_value(buf: &mut Vec<u8>, value: &Value) -> Result<(), String> {
    match value {
        Value::Undefined => {
            buf.push(0xf7);
            Ok(())
        }
        Value::Reference(_) => {
            Err("CBOR has no reference mapping yet (its URI tag is ASCII only)".to_string())
        }
        Value::Tagged(_, _) => {
            Err("CBOR has no tagged value with a string tag (its tags are numbers)".to_string())
        }
        Value::Symbol(name) => {
            write_type_and_length(buf, 6, 280);
            let bytes = name.as_bytes();
            write_type_and_length(buf, 3, bytes.len() as u64);
            buf.extend_from_slice(bytes);
            Ok(())
        }
        Value::Null => {
            // CBOR simple value 22 = null
            buf.push(0xf6);
            Ok(())
        }
        Value::Bool(b) => {
            // CBOR simple value 20 = false, 21 = true
            buf.push(if *b { 0xf5 } else { 0xf4 });
            Ok(())
        }
        Value::Integer(n) => write_integer(buf, n),
        Value::Float(f) => {
            // Always encode as CBOR float64 (major 7, info 27)
            buf.push(0xfb);
            buf.extend_from_slice(&f.to_be_bytes());
            Ok(())
        }
        Value::String(s) => {
            let bytes = s.as_bytes();
            write_type_and_length(buf, 3, bytes.len() as u64); // major 3 = text string
            buf.extend_from_slice(bytes);
            Ok(())
        }
        Value::Bytes(b) => {
            write_type_and_length(buf, 2, b.len() as u64); // major 2 = byte string
            buf.extend_from_slice(b);
            Ok(())
        }
        Value::Array(arr) => {
            write_type_and_length(buf, 4, arr.len() as u64); // major 4 = array
            for item in arr {
                write_value(buf, item)?;
            }
            Ok(())
        }
        Value::Object(obj) => {
            let mut keys: Vec<&String> = obj.keys().collect();
            keys.sort();
            write_type_and_length(buf, 5, keys.len() as u64); // major 5 = map
            for k in keys {
                // Key: text string
                let key_bytes = k.as_bytes();
                write_type_and_length(buf, 3, key_bytes.len() as u64);
                buf.extend_from_slice(key_bytes);
                // Value
                write_value(buf, &obj[k])?;
            }
            Ok(())
        }
    }
}

/// Write a CBOR major type + length/value argument.
///
/// CBOR encodes the major type in the high 3 bits and uses the low 5 bits
/// plus optional following bytes for the argument:
///   0-23:    argument in the low 5 bits (1 byte total)
///   24:      1-byte argument follows
///   25:      2-byte argument follows
///   26:      4-byte argument follows
///   27:      8-byte argument follows
fn write_type_and_length(buf: &mut Vec<u8>, major: u8, val: u64) {
    let high = major << 5;
    match val {
        0..=23 => {
            buf.push(high | val as u8);
        }
        24..=0xff => {
            buf.push(high | 24);
            buf.push(val as u8);
        }
        0x100..=0xffff => {
            buf.push(high | 25);
            buf.extend_from_slice(&(val as u16).to_be_bytes());
        }
        0x10000..=0xffff_ffff => {
            buf.push(high | 26);
            buf.extend_from_slice(&(val as u32).to_be_bytes());
        }
        _ => {
            buf.push(high | 27);
            buf.extend_from_slice(&val.to_be_bytes());
        }
    }
}

/// Write a YAY integer as the smallest CBOR integer encoding.
///
/// CBOR has two integer major types:
///   - Major 0 (positive): encodes value n directly (represents n)
///   - Major 1 (negative): encodes value n (represents -1 - n)
///
/// The argument uses the smallest encoding that fits.
fn write_integer(buf: &mut Vec<u8>, n: &BigInt) -> Result<(), String> {
    if n.sign() == num_bigint::Sign::Minus {
        // Negative: CBOR major 1 encodes -1 - n, so the argument is |n| - 1
        let abs_minus_1 = (-n) - BigInt::from(1);
        if let Some(val) = abs_minus_1.to_u64() {
            write_type_and_length(buf, 1, val);
        } else {
            write_bignum(buf, 3, &abs_minus_1);
        }
    } else {
        if let Some(val) = n.to_u64() {
            write_type_and_length(buf, 0, val);
        } else {
            write_bignum(buf, 2, n);
        }
    }
    Ok(())
}

fn write_bignum(buf: &mut Vec<u8>, tag: u64, magnitude: &BigInt) {
    let (_, bytes) = magnitude.to_bytes_be();
    write_type_and_length(buf, 6, tag);
    write_type_and_length(buf, 2, bytes.len() as u64);
    buf.extend_from_slice(&bytes);
}

// ---------------------------------------------------------------------------
// Diagnostic Notation (CBOR -> human-readable text, RFC 8949 §8)
// ---------------------------------------------------------------------------

/// Render CBOR bytes as diagnostic notation (RFC 8949 §8).
///
/// This is a presentation format for reviewing CBOR data in a human-readable
/// form. It renders from the CBOR binary, not from YAY values, so it
/// faithfully represents the actual wire encoding.
pub fn diagnostic(input: &[u8]) -> Result<String, String> {
    let cbor_value = decode_raw(input)?;
    let mut out = String::new();
    diag_value(&mut out, &cbor_value, 0);
    out.push('\n');
    Ok(out)
}

fn diag_value(out: &mut String, val: &RawValue, indent: usize) {
    match val {
        RawValue::Undefined => out.push_str("undefined"),
        RawValue::Null => out.push_str("null"),
        RawValue::Bool(true) => out.push_str("true"),
        RawValue::Bool(false) => out.push_str("false"),
        RawValue::Integer(i) => write!(out, "{}", i).unwrap(),
        RawValue::Float(f) => {
            diag_float(out, *f);
        }
        RawValue::Text(s) => {
            diag_text(out, s);
        }
        RawValue::Bytes(b) => {
            out.push_str("h'");
            for byte in b {
                write!(out, "{:02x}", byte).unwrap();
            }
            out.push('\'');
        }
        RawValue::Array(arr) => {
            diag_array(out, arr, indent);
        }
        RawValue::Map(pairs) => {
            diag_map(out, pairs, indent);
        }
        RawValue::Tag(tag, inner) => {
            write!(out, "{}(", tag).unwrap();
            diag_value(out, inner, indent);
            out.push(')');
        }
    }
}

fn diag_float(out: &mut String, f: f64) {
    if f.is_nan() {
        out.push_str("NaN");
    } else if f.is_infinite() {
        if f.is_sign_positive() {
            out.push_str("Infinity");
        } else {
            out.push_str("-Infinity");
        }
    } else if f == 0.0 && f.is_sign_negative() {
        out.push_str("-0.0");
    } else if f.fract() == 0.0 && f.abs() < 1e18 {
        // Print as integer-like float with .0 suffix
        write!(out, "{:.1}", f).unwrap();
    } else {
        // Use full precision
        let s = format!("{}", f);
        out.push_str(&s);
        // Ensure there's a decimal point
        if !s.contains('.') && !s.contains('e') && !s.contains('E') {
            out.push_str(".0");
        }
    }
}

fn diag_text(out: &mut String, s: &str) {
    out.push('"');
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => {
                write!(out, "\\u{:04x}", c as u32).unwrap();
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

fn diag_array(out: &mut String, arr: &[RawValue], indent: usize) {
    if arr.is_empty() {
        out.push_str("[]");
        return;
    }
    // Use compact form for small arrays of simple values
    if arr.len() <= 5 && arr.iter().all(is_simple_value) {
        out.push('[');
        for (i, item) in arr.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            diag_value(out, item, indent);
        }
        out.push(']');
    } else {
        out.push_str("[\n");
        let child_indent = indent + 2;
        for (i, item) in arr.iter().enumerate() {
            for _ in 0..child_indent {
                out.push(' ');
            }
            diag_value(out, item, child_indent);
            if i < arr.len() - 1 {
                out.push(',');
            }
            out.push('\n');
        }
        for _ in 0..indent {
            out.push(' ');
        }
        out.push(']');
    }
}

fn diag_map(out: &mut String, pairs: &[(RawValue, RawValue)], indent: usize) {
    if pairs.is_empty() {
        out.push_str("{}");
        return;
    }
    out.push_str("{\n");
    let child_indent = indent + 2;
    for (i, (k, v)) in pairs.iter().enumerate() {
        for _ in 0..child_indent {
            out.push(' ');
        }
        diag_value(out, k, child_indent);
        out.push_str(": ");
        diag_value(out, v, child_indent);
        if i < pairs.len() - 1 {
            out.push(',');
        }
        out.push('\n');
    }
    for _ in 0..indent {
        out.push(' ');
    }
    out.push('}');
}

fn is_simple_value(val: &RawValue) -> bool {
    matches!(
        val,
        RawValue::Undefined
            | RawValue::Null
            | RawValue::Bool(_)
            | RawValue::Integer(_)
            | RawValue::Float(_)
            | RawValue::Text(_)
            | RawValue::Bytes(_)
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn undefined_is_distinct_from_null_in_any_position() {
        assert_eq!(decode(&[0xf7]).unwrap(), Value::Undefined);
        assert_eq!(
            decode(&[0x82, 0xf7, 0xf6]).unwrap(),
            Value::Array(vec![Value::Undefined, Value::Null])
        );
        assert_eq!(encode(&Value::Undefined).unwrap(), vec![0xf7]);
        assert_eq!(diagnostic(&[0xf7]).unwrap(), "undefined\n");
    }

    #[test]
    fn bignums_are_recursive_and_accept_leading_zero_bytes() {
        assert_eq!(
            decode(&[0x81, 0xc2, 0x42, 0x00, 0x01]).unwrap(),
            Value::Array(vec![Value::Integer(BigInt::from(1))])
        );
        assert_eq!(
            decode(&[0xa1, 0x61, b'n', 0xc3, 0x42, 0x00, 0x01]).unwrap(),
            Value::Object(HashMap::from([(
                "n".to_string(),
                Value::Integer(BigInt::from(-2)),
            )]))
        );
    }

    #[test]
    fn bignum_tags_require_bytes() {
        assert_eq!(
            decode(&[0xc2, 0x00]).unwrap_err(),
            "CBOR bignum tag 2 or 3 needs a byte string"
        );
        assert_eq!(
            decode(&[0xc3, 0x80]).unwrap_err(),
            "CBOR bignum tag 2 or 3 needs a byte string"
        );
    }
}