1 //! The CBOR subset that wire 2 uses.2 //!3 //! The encoder is canonical: definite lengths, shortest form, and map keys4 //! sorted by their encoded bytes. Two peers that encode the same value produce5 //! the same bytes. Goldens depend on that.6 //!7 //! The decoder accepts only definite lengths. An indefinite-length item is8 //! `Indefinite`. Tags are `Malformed`. Major type 7 with additional information9 //! 24 is `Malformed`. A length that is not in its shortest form is10 //! `NonCanonical`. A payload with bytes after the item is `Trailing`.11 //!12 //! The nesting limit exists because a decoder recurses. One level is one stack13 //! frame, and 64 levels keep the decoder well inside any thread stack. A frame14 //! of 16 MiB of nested arrays would otherwise exhaust it.15 16 use std::fmt;17 18 /// The deepest item that the decoder accepts.19 pub const MAX_DEPTH: usize = 64;20 21 /// One CBOR item.22 #[derive(Clone, PartialEq, Debug)]23 pub enum Value {24 /// Major type 0.25 Uint(u64),26 /// Major type 1. The value is negative and at least -2^63.27 Nint(i64),28 /// Major type 2.29 Bytes(Vec<u8>),30 /// Major type 3.31 Text(String),32 /// Major type 4.33 Array(Vec<Value>),34 /// Major type 5. Keys are unique.35 Map(Vec<(Value, Value)>),36 /// Major type 7, simple value 20 and 21.37 Bool(bool),38 /// Major type 7, simple value 22.39 Null,40 /// Major type 7, float. Half and single precision widen to f64.41 Float(f64),42 }43 44 impl Value {45 /// A map value. The encoder sorts the keys; this keeps them as given.46 pub fn map(entries: impl IntoIterator<Item = (Value, Value)>) -> Value {47 // `decode` returns the entries in wire order, which is the canonical48 // order, so a map built here sits in that order too or the two cannot49 // compare equal.50 let mut entries: Vec<(Value, Value)> = entries.into_iter().collect();51 sort_entries(&mut entries);52 Value::Map(entries)53 }54 55 /// The value at a text key, when this is a map.56 pub fn get(&self, key: &str) -> Option<&Value> {57 match self {58 Value::Map(entries) => entries59 .iter()60 .find(|(k, _)| matches!(k, Value::Text(s) if s == key))61 .map(|(_, v)| v),62 _ => None,63 }64 }65 66 /// The name of the item for an error message.67 pub fn kind(&self) -> &'static str {68 match self {69 Value::Uint(_) => "uint",70 Value::Nint(_) => "nint",71 Value::Bytes(_) => "bytes",72 Value::Text(_) => "text",73 Value::Array(_) => "array",74 Value::Map(_) => "map",75 Value::Bool(_) => "bool",76 Value::Null => "null",77 Value::Float(_) => "float",78 }79 }80 }81 82 /// A CBOR item that wire 2 does not allow.83 #[derive(Clone, PartialEq, Eq, Debug)]84 pub enum CborError {85 /// The payload ended in the middle of an item.86 Eof,87 /// A major type that this subset does not carry, or a reserved byte.88 Malformed(u8),89 /// An indefinite length. Wire 1 has none.90 Indefinite,91 /// Nesting deeper than [`MAX_DEPTH`].92 TooDeep,93 /// Bytes after the item.94 Trailing,95 /// A text string that is not UTF-8.96 Utf8,97 /// The same key twice in one map.98 Duplicate,99 /// A length that is not in its shortest form.100 NonCanonical,101 /// A value that does not fit the type it should have.102 Type {103 want: &'static str,104 got: &'static str,105 },106 }107 108 impl fmt::Display for CborError {109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {110 match self {111 CborError::Eof => write!(f, "the item ends before its data"),112 CborError::Malformed(b) => write!(f, "cbor byte {b:#04x} is not in the subset"),113 CborError::Indefinite => write!(f, "indefinite lengths are not allowed"),114 CborError::TooDeep => write!(f, "nesting is deeper than {MAX_DEPTH}"),115 CborError::Trailing => write!(f, "bytes follow the item"),116 CborError::Utf8 => write!(f, "a text string is not UTF-8"),117 CborError::Duplicate => write!(f, "the same key appears twice in one map"),118 CborError::NonCanonical => write!(f, "a length is not in its shortest form"),119 CborError::Type { want, got } => write!(f, "expected {want}, got {got}"),120 }121 }122 }123 124 impl std::error::Error for CborError {}125 126 /// The head byte plus the argument, in the shortest form that holds `arg`.127 fn write_head(out: &mut Vec<u8>, major: u8, arg: u64) {128 let mi = major << 5;129 if arg < 24 {130 out.push(mi | (arg as u8));131 } else if arg <= u64::from(u8::MAX) {132 out.push(mi | 24);133 out.push(arg as u8);134 } else if arg <= u64::from(u16::MAX) {135 out.push(mi | 25);136 out.extend_from_slice(&(arg as u16).to_be_bytes());137 } else if arg <= u64::from(u32::MAX) {138 out.push(mi | 26);139 out.extend_from_slice(&(arg as u32).to_be_bytes());140 } else {141 out.push(mi | 27);142 out.extend_from_slice(&arg.to_be_bytes());143 }144 }145 146 /// The canonical bytes of one item on its own, which is what a key sorts by.147 fn encoded(value: &Value) -> Vec<u8> {148 let mut out = Vec::new();149 encode(value, &mut out);150 out151 }152 153 /// Orders map entries by the bytes of their keys, never by the key values.154 fn sort_entries(entries: &mut [(Value, Value)]) {155 entries.sort_by_key(|(k, _)| encoded(k));156 }157 158 /// Appends the canonical encoding of `value` to `out`.159 pub fn encode(value: &Value, out: &mut Vec<u8>) {160 match value {161 Value::Uint(n) => write_head(out, 0, *n),162 // Major type 1 carries -1-arg, so the argument is !n.163 Value::Nint(n) => write_head(out, 1, !*n as u64),164 Value::Bytes(b) => {165 write_head(out, 2, b.len() as u64);166 out.extend_from_slice(b);167 }168 Value::Text(s) => {169 write_head(out, 3, s.len() as u64);170 out.extend_from_slice(s.as_bytes());171 }172 Value::Array(items) => {173 write_head(out, 4, items.len() as u64);174 for item in items {175 encode(item, out);176 }177 }178 Value::Map(entries) => {179 let mut entries = entries.clone();180 sort_entries(&mut entries);181 write_head(out, 5, entries.len() as u64);182 for (k, v) in &entries {183 encode(k, out);184 encode(v, out);185 }186 }187 Value::Bool(b) => out.push(if *b { 0xF5 } else { 0xF4 }),188 Value::Null => out.push(0xF6),189 Value::Float(x) => {190 out.push(0xFB);191 out.extend_from_slice(&x.to_bits().to_be_bytes());192 }193 }194 }195 196 /// Half precision widens to f64 without help from std.197 fn half_to_f64(bits: u16) -> f64 {198 let sign = if bits & 0x8000 == 0 { 1.0 } else { -1.0 };199 let exp = i32::from((bits >> 10) & 0x1F);200 let frac = u32::from(bits & 0x3FF);201 // Infinity and NaN.202 if exp == 0x1F {203 return sign * if frac == 0 { f64::INFINITY } else { f64::NAN };204 }205 // Zero and the subnormals, whose value is frac * 2^-24.206 if exp == 0 {207 return sign * f64::from(frac) * 2f64.powi(-24);208 }209 sign * f64::from(frac + 0x400) * 2f64.powi(exp - 25)210 }211 212 /// One item at a time, from a byte slice that is never copied.213 struct Reader<'a> {214 bytes: &'a [u8],215 at: usize,216 }217 218 impl<'a> Reader<'a> {219 /// The head byte. Additional information is read by `argument`.220 fn head(&mut self) -> Result<u8, CborError> {221 Ok(self.take(1)?[0])222 }223 224 /// The argument of `h`, in its shortest form, for major types 0..=5.225 fn argument(&mut self, h: u8) -> Result<u64, CborError> {226 let ai = h & 0x1F;227 let arg = match ai {228 0..=23 => u64::from(ai),229 24 => u64::from(self.take(1)?[0]),230 25 => {231 let b = self.take(2)?;232 u64::from(u16::from_be_bytes([b[0], b[1]]))233 }234 26 => {235 let b = self.take(4)?;236 u64::from(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))237 }238 27 => {239 let b = self.take(8)?;240 u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])241 }242 31 => return Err(CborError::Indefinite),243 _ => return Err(CborError::Malformed(h)),244 };245 let floor = match ai {246 24 => 24,247 25 => 256,248 26 => 65_536,249 27 => 4_294_967_296,250 _ => 0,251 };252 if arg < floor {253 return Err(CborError::NonCanonical);254 }255 Ok(arg)256 }257 258 /// Takes `n` bytes, or `Eof` when the payload ends first.259 fn take(&mut self, n: u64) -> Result<&'a [u8], CborError> {260 let n = usize::try_from(n).unwrap_or(usize::MAX);261 if n > self.bytes.len() - self.at {262 return Err(CborError::Eof);263 }264 let slice = &self.bytes[self.at..self.at + n];265 self.at += n;266 Ok(slice)267 }268 269 /// Decodes one item. `depth` is how many containers enclose it.270 fn item(&mut self, depth: usize) -> Result<Value, CborError> {271 let h = self.head()?;272 let major = h >> 5;273 match major {274 0 => Ok(Value::Uint(self.argument(h)?)),275 1 => {276 let arg = self.argument(h)?;277 i64::try_from(-1i128 - i128::from(arg))278 .map(Value::Nint)279 .map_err(|_| CborError::Malformed(h))280 }281 2 => {282 let arg = self.argument(h)?;283 Ok(Value::Bytes(self.take(arg)?.to_vec()))284 }285 3 => {286 let arg = self.argument(h)?;287 String::from_utf8(self.take(arg)?.to_vec())288 .map(Value::Text)289 .map_err(|_| CborError::Utf8)290 }291 4 => {292 let arg = self.argument(h)?;293 if depth + 1 > MAX_DEPTH {294 return Err(CborError::TooDeep);295 }296 let mut items = Vec::new();297 for _ in 0..arg {298 items.push(self.item(depth + 1)?);299 }300 Ok(Value::Array(items))301 }302 5 => {303 let arg = self.argument(h)?;304 if depth + 1 > MAX_DEPTH {305 return Err(CborError::TooDeep);306 }307 let mut entries: Vec<(Value, Value)> = Vec::new();308 // The bytes read so far are canonical, so the wire slice of a309 // key is a sound identity for the duplicate check.310 let mut keys: Vec<(usize, usize)> = Vec::new();311 for _ in 0..arg {312 let from = self.at;313 let key = self.item(depth + 1)?;314 let to = self.at;315 if keys316 .iter()317 .any(|&(a, b)| self.bytes[a..b] == self.bytes[from..to])318 {319 return Err(CborError::Duplicate);320 }321 keys.push((from, to));322 let value = self.item(depth + 1)?;323 entries.push((key, value));324 }325 Ok(Value::Map(entries))326 }327 // Tags. Wire 1 has none.328 6 => Err(CborError::Malformed(h)),329 7 => self.simple(h),330 _ => Err(CborError::Malformed(h)),331 }332 }333 334 /// Major type 7: the three simple values of wire 2 and the float widths.335 ///336 /// Additional information 24 names a simple value in the next byte, 23 is337 /// undefined, 28..=30 are reserved, and 31 is the break code. Wire 1338 /// carries none of them.339 fn simple(&mut self, h: u8) -> Result<Value, CborError> {340 match h & 0x1F {341 20 => Ok(Value::Bool(false)),342 21 => Ok(Value::Bool(true)),343 22 => Ok(Value::Null),344 25 => {345 let b = self.take(2)?;346 Ok(Value::Float(half_to_f64(u16::from_be_bytes([b[0], b[1]]))))347 }348 26 => {349 let b = self.take(4)?;350 Ok(Value::Float(f64::from(f32::from_bits(u32::from_be_bytes(351 [b[0], b[1], b[2], b[3]],352 )))))353 }354 27 => {355 let b = self.take(8)?;356 Ok(Value::Float(f64::from_bits(u64::from_be_bytes([357 b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],358 ]))))359 }360 _ => Err(CborError::Malformed(h)),361 }362 }363 }364 365 /// Decodes one item and requires that it is the whole input.366 pub fn decode(bytes: &[u8]) -> Result<Value, CborError> {367 let mut reader = Reader { bytes, at: 0 };368 let value = reader.item(0)?;369 if reader.at != reader.bytes.len() {370 return Err(CborError::Trailing);371 }372 Ok(value)373 }