| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The canonical binary codec shared by every hashed format. |
| 5 | //! |
| 6 | //! - `uv`: unsigned LEB128, at most 64 bits, always in its shortest form. |
| 7 | //! - `sv`: a signed integer, zigzag-mapped and then written as `uv`. |
| 8 | //! - `bytes`: a `uv` length followed by that many raw bytes. |
| 9 | //! |
| 10 | //! The decoder is strict: it rejects overlong integers, integers that do not |
| 11 | //! fit in 64 bits, lengths that run past the input, and trailing bytes. Every |
| 12 | //! value therefore has exactly one encoding, which is what lets an id stand for |
| 13 | //! the value. |
| 14 | |
| 15 | use core::fmt; |
| 16 | |
| 17 | use crate::id::ObjectId; |
| 18 | |
| 19 | /// Why some bytes are not a canonical encoding. |
| 20 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 21 | pub enum DecodeError { |
| 22 | /// The input ended in the middle of a field that starts at `at`. |
| 23 | UnexpectedEnd { at: usize }, |
| 24 | /// The integer at `at` uses more bytes than its shortest form. |
| 25 | NonMinimalInteger { at: usize }, |
| 26 | /// The integer at `at` does not fit in 64 bits. |
| 27 | IntegerOverflow { at: usize }, |
| 28 | /// The length or count at `at` is larger than the rest of the input. |
| 29 | LengthTooLarge { at: usize }, |
| 30 | /// Bytes were left after the last field, starting at `at`. |
| 31 | TrailingBytes { at: usize }, |
| 32 | /// The field at `at` holds a value the format does not allow. |
| 33 | Invalid { at: usize, what: &'static str }, |
| 34 | } |
| 35 | |
| 36 | impl fmt::Display for DecodeError { |
| 37 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 38 | match self { |
| 39 | DecodeError::UnexpectedEnd { at } => { |
| 40 | write!(f, "input ends inside the field at byte {at}") |
| 41 | } |
| 42 | DecodeError::NonMinimalInteger { at } => { |
| 43 | write!(f, "integer at byte {at} is not in its shortest form") |
| 44 | } |
| 45 | DecodeError::IntegerOverflow { at } => { |
| 46 | write!(f, "integer at byte {at} does not fit in 64 bits") |
| 47 | } |
| 48 | DecodeError::LengthTooLarge { at } => { |
| 49 | write!(f, "length at byte {at} runs past the end of the input") |
| 50 | } |
| 51 | DecodeError::TrailingBytes { at } => write!(f, "unexpected bytes from byte {at} on"), |
| 52 | DecodeError::Invalid { at, what } => write!(f, "invalid {what} at byte {at}"), |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | impl std::error::Error for DecodeError {} |
| 58 | |
| 59 | /// Reads canonical fields from a byte slice, front to back. |
| 60 | #[derive(Debug)] |
| 61 | pub struct Reader<'a> { |
| 62 | buf: &'a [u8], |
| 63 | pos: usize, |
| 64 | } |
| 65 | |
| 66 | impl<'a> Reader<'a> { |
| 67 | /// Starts reading at the beginning of `buf`. |
| 68 | pub fn new(buf: &'a [u8]) -> Self { |
| 69 | Self { buf, pos: 0 } |
| 70 | } |
| 71 | |
| 72 | /// Byte offset of the next field. |
| 73 | pub fn position(&self) -> usize { |
| 74 | self.pos |
| 75 | } |
| 76 | |
| 77 | /// Bytes not read yet. |
| 78 | pub fn remaining(&self) -> usize { |
| 79 | self.buf.len() - self.pos |
| 80 | } |
| 81 | |
| 82 | /// Reads exactly `n` bytes. |
| 83 | pub fn take(&mut self, n: usize) -> Result<&'a [u8], DecodeError> { |
| 84 | if n > self.remaining() { |
| 85 | return Err(DecodeError::UnexpectedEnd { at: self.pos }); |
| 86 | } |
| 87 | let out = &self.buf[self.pos..self.pos + n]; |
| 88 | self.pos += n; |
| 89 | Ok(out) |
| 90 | } |
| 91 | |
| 92 | /// Reads one byte. |
| 93 | pub fn u8(&mut self) -> Result<u8, DecodeError> { |
| 94 | Ok(self.take(1)?[0]) |
| 95 | } |
| 96 | |
| 97 | /// Reads a fixed-size array. |
| 98 | pub fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> { |
| 99 | let mut out = [0u8; N]; |
| 100 | out.copy_from_slice(self.take(N)?); |
| 101 | Ok(out) |
| 102 | } |
| 103 | |
| 104 | /// Reads a 32-byte object id. |
| 105 | pub fn id(&mut self) -> Result<ObjectId, DecodeError> { |
| 106 | Ok(ObjectId::from_bytes(self.array()?)) |
| 107 | } |
| 108 | |
| 109 | /// Reads an unsigned LEB128 integer in its shortest form. |
| 110 | pub fn uv(&mut self) -> Result<u64, DecodeError> { |
| 111 | let at = self.pos; |
| 112 | let mut value = 0u64; |
| 113 | let mut shift = 0u32; |
| 114 | loop { |
| 115 | let byte = self.u8().map_err(|_| DecodeError::UnexpectedEnd { at })?; |
| 116 | let low = u64::from(byte & 0x7f); |
| 117 | if shift == 63 && low > 1 { |
| 118 | return Err(DecodeError::IntegerOverflow { at }); |
| 119 | } |
| 120 | value |= low << shift; |
| 121 | if byte & 0x80 == 0 { |
| 122 | if byte == 0 && shift > 0 { |
| 123 | return Err(DecodeError::NonMinimalInteger { at }); |
| 124 | } |
| 125 | return Ok(value); |
| 126 | } |
| 127 | shift += 7; |
| 128 | if shift > 63 { |
| 129 | return Err(DecodeError::IntegerOverflow { at }); |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /// Reads a zigzag-mapped signed integer. |
| 135 | pub fn sv(&mut self) -> Result<i64, DecodeError> { |
| 136 | Ok(unzigzag(self.uv()?)) |
| 137 | } |
| 138 | |
| 139 | /// Reads a `uv` that must be a length or count, and checks that at least |
| 140 | /// `count × min_item_bytes` bytes remain, so that a forged count can never |
| 141 | /// make the decoder reserve more memory than the input could fill. |
| 142 | pub fn count(&mut self, min_item_bytes: usize) -> Result<usize, DecodeError> { |
| 143 | let at = self.pos; |
| 144 | let n = self.uv()?; |
| 145 | let n = usize::try_from(n).map_err(|_| DecodeError::LengthTooLarge { at })?; |
| 146 | if n.saturating_mul(min_item_bytes) > self.remaining() { |
| 147 | return Err(DecodeError::LengthTooLarge { at }); |
| 148 | } |
| 149 | Ok(n) |
| 150 | } |
| 151 | |
| 152 | /// Reads `bytes`: a length followed by that many bytes. |
| 153 | pub fn bytes(&mut self) -> Result<&'a [u8], DecodeError> { |
| 154 | let at = self.pos; |
| 155 | let n = self.uv()?; |
| 156 | let n = usize::try_from(n).map_err(|_| DecodeError::LengthTooLarge { at })?; |
| 157 | if n > self.remaining() { |
| 158 | return Err(DecodeError::LengthTooLarge { at }); |
| 159 | } |
| 160 | self.take(n) |
| 161 | } |
| 162 | |
| 163 | /// Succeeds only if every byte was read. |
| 164 | pub fn finish(self) -> Result<(), DecodeError> { |
| 165 | if self.pos == self.buf.len() { |
| 166 | Ok(()) |
| 167 | } else { |
| 168 | Err(DecodeError::TrailingBytes { at: self.pos }) |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// Appends an unsigned LEB128 integer in its shortest form. |
| 174 | pub fn put_uv(out: &mut Vec<u8>, mut value: u64) { |
| 175 | loop { |
| 176 | let low = (value & 0x7f) as u8; |
| 177 | value >>= 7; |
| 178 | if value == 0 { |
| 179 | out.push(low); |
| 180 | return; |
| 181 | } |
| 182 | out.push(low | 0x80); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /// Appends a zigzag-mapped signed integer. |
| 187 | pub fn put_sv(out: &mut Vec<u8>, value: i64) { |
| 188 | put_uv(out, zigzag(value)); |
| 189 | } |
| 190 | |
| 191 | /// Appends `bytes`: the length, then the bytes. |
| 192 | pub fn put_bytes(out: &mut Vec<u8>, bytes: &[u8]) { |
| 193 | put_uv(out, bytes.len() as u64); |
| 194 | out.extend_from_slice(bytes); |
| 195 | } |
| 196 | |
| 197 | /// Appends a 32-byte object id. |
| 198 | pub fn put_id(out: &mut Vec<u8>, id: &ObjectId) { |
| 199 | out.extend_from_slice(id.as_bytes()); |
| 200 | } |
| 201 | |
| 202 | /// Number of bytes `put_uv` writes for `value`. |
| 203 | pub fn uv_len(value: u64) -> usize { |
| 204 | let bits = 64 - value.leading_zeros() as usize; |
| 205 | bits.div_ceil(7).max(1) |
| 206 | } |
| 207 | |
| 208 | /// Maps signed to unsigned so that small magnitudes stay small: 0, -1, 1, -2, … |
| 209 | /// become 0, 1, 2, 3, … |
| 210 | pub const fn zigzag(value: i64) -> u64 { |
| 211 | ((value << 1) ^ (value >> 63)) as u64 |
| 212 | } |
| 213 | |
| 214 | /// The inverse of [`zigzag`]. |
| 215 | pub const fn unzigzag(value: u64) -> i64 { |
| 216 | ((value >> 1) as i64) ^ -((value & 1) as i64) |
| 217 | } |
| 218 | |
| 219 | #[cfg(test)] |
| 220 | mod tests { |
| 221 | use super::*; |
| 222 | |
| 223 | fn uv_bytes(value: u64) -> Vec<u8> { |
| 224 | let mut out = Vec::new(); |
| 225 | put_uv(&mut out, value); |
| 226 | out |
| 227 | } |
| 228 | |
| 229 | fn read_uv(bytes: &[u8]) -> Result<u64, DecodeError> { |
| 230 | let mut reader = Reader::new(bytes); |
| 231 | let value = reader.uv()?; |
| 232 | reader.finish()?; |
| 233 | Ok(value) |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn uv_vectors() { |
| 238 | let cases: &[(u64, &[u8])] = &[ |
| 239 | (0, &[0x00]), |
| 240 | (1, &[0x01]), |
| 241 | (127, &[0x7f]), |
| 242 | (128, &[0x80, 0x01]), |
| 243 | (300, &[0xac, 0x02]), |
| 244 | (16_383, &[0xff, 0x7f]), |
| 245 | (16_384, &[0x80, 0x80, 0x01]), |
| 246 | ( |
| 247 | u64::MAX, |
| 248 | &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01], |
| 249 | ), |
| 250 | ]; |
| 251 | for (value, bytes) in cases { |
| 252 | assert_eq!(uv_bytes(*value), *bytes, "{value}"); |
| 253 | assert_eq!(read_uv(bytes), Ok(*value), "{value}"); |
| 254 | assert_eq!(uv_len(*value), bytes.len(), "{value}"); |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | #[test] |
| 259 | fn uv_rejects_non_canonical() { |
| 260 | assert_eq!( |
| 261 | read_uv(&[0x80, 0x00]), |
| 262 | Err(DecodeError::NonMinimalInteger { at: 0 }) |
| 263 | ); |
| 264 | assert_eq!( |
| 265 | read_uv(&[0xff, 0x80, 0x00]), |
| 266 | Err(DecodeError::NonMinimalInteger { at: 0 }) |
| 267 | ); |
| 268 | // Eleven bytes, or a tenth byte above 1, cannot fit in 64 bits. |
| 269 | assert_eq!( |
| 270 | read_uv(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02]), |
| 271 | Err(DecodeError::IntegerOverflow { at: 0 }) |
| 272 | ); |
| 273 | assert_eq!( |
| 274 | read_uv(&[ |
| 275 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0x00 |
| 276 | ]), |
| 277 | Err(DecodeError::IntegerOverflow { at: 0 }) |
| 278 | ); |
| 279 | assert_eq!(read_uv(&[0x80]), Err(DecodeError::UnexpectedEnd { at: 0 })); |
| 280 | assert_eq!(read_uv(&[]), Err(DecodeError::UnexpectedEnd { at: 0 })); |
| 281 | assert_eq!( |
| 282 | read_uv(&[0x01, 0x02]), |
| 283 | Err(DecodeError::TrailingBytes { at: 1 }) |
| 284 | ); |
| 285 | } |
| 286 | |
| 287 | #[test] |
| 288 | fn zigzag_vectors() { |
| 289 | let cases: &[(i64, u64)] = &[ |
| 290 | (0, 0), |
| 291 | (-1, 1), |
| 292 | (1, 2), |
| 293 | (-2, 3), |
| 294 | (i64::MAX, u64::MAX - 1), |
| 295 | (i64::MIN, u64::MAX), |
| 296 | ]; |
| 297 | for (signed, unsigned) in cases { |
| 298 | assert_eq!(zigzag(*signed), *unsigned); |
| 299 | assert_eq!(unzigzag(*unsigned), *signed); |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | #[test] |
| 304 | fn bytes_and_count_guard_lengths() { |
| 305 | let mut out = Vec::new(); |
| 306 | put_bytes(&mut out, b"abc"); |
| 307 | let mut reader = Reader::new(&out); |
| 308 | assert_eq!(reader.bytes(), Ok(&b"abc"[..])); |
| 309 | reader.finish().unwrap(); |
| 310 | |
| 311 | // A length past the end of the input. |
| 312 | let mut reader = Reader::new(&[0x05, b'a']); |
| 313 | assert_eq!(reader.bytes(), Err(DecodeError::LengthTooLarge { at: 0 })); |
| 314 | |
| 315 | // A count that would need more bytes than remain. |
| 316 | let mut forged = Vec::new(); |
| 317 | put_uv(&mut forged, u64::MAX); |
| 318 | let mut reader = Reader::new(&forged); |
| 319 | assert_eq!(reader.count(1), Err(DecodeError::LengthTooLarge { at: 0 })); |
| 320 | } |
| 321 | |
| 322 | #[test] |
| 323 | fn uv_round_trips_at_every_boundary() { |
| 324 | for shift in 0..64 { |
| 325 | for value in [(1u64 << shift) - 1, 1u64 << shift, (1u64 << shift) + 1] { |
| 326 | assert_eq!(read_uv(&uv_bytes(value)), Ok(value)); |
| 327 | assert_eq!(uv_bytes(value).len(), uv_len(value)); |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | } |