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;
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
)),
}
}
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 => {
buf.push(0xf6);
Ok(())
}
Value::Bool(b) => {
buf.push(if *b { 0xf5 } else { 0xf4 });
Ok(())
}
Value::Integer(n) => write_integer(buf, n),
Value::Float(f) => {
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); buf.extend_from_slice(bytes);
Ok(())
}
Value::Bytes(b) => {
write_type_and_length(buf, 2, b.len() as u64); buf.extend_from_slice(b);
Ok(())
}
Value::Array(arr) => {
write_type_and_length(buf, 4, arr.len() as u64); 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); for k in keys {
let key_bytes = k.as_bytes();
write_type_and_length(buf, 3, key_bytes.len() as u64);
buf.extend_from_slice(key_bytes);
write_value(buf, &obj[k])?;
}
Ok(())
}
}
}
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());
}
}
}
fn write_integer(buf: &mut Vec<u8>, n: &BigInt) -> Result<(), String> {
if n.sign() == num_bigint::Sign::Minus {
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);
}
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 {
write!(out, "{:.1}", f).unwrap();
} else {
let s = format!("{}", f);
out.push_str(&s);
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;
}
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"
);
}
}