| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::fmt::{self, Debug, Formatter, Write}; |
| 8 |
|
| 9 |
use crate::hex_with_len; |
| 10 |
|
| 11 |
pub const MAX_VARINT: u64 = (1 << 62) - 1; |
| 12 |
|
| 13 |
/// Decoder is a view into a byte array that has a read offset. Use it for parsing. |
| 14 |
pub struct Decoder<'a> { |
| 15 |
buf: &'a [u8], |
| 16 |
offset: usize, |
| 17 |
} |
| 18 |
|
| 19 |
impl<'a> Decoder<'a> { |
| 20 |
/// Make a new view of the provided slice. |
| 21 |
#[must_use] |
| 22 |
pub const fn new(buf: &[u8]) -> Decoder { |
| 23 |
Decoder { buf, offset: 0 } |
| 24 |
} |
| 25 |
|
| 26 |
/// Get the number of bytes remaining until the end. |
| 27 |
#[must_use] |
| 28 |
pub const fn remaining(&self) -> usize { |
| 29 |
self.buf.len() - self.offset |
| 30 |
} |
| 31 |
|
| 32 |
/// The number of bytes from the underlying slice that have been decoded. |
| 33 |
#[must_use] |
| 34 |
pub const fn offset(&self) -> usize { |
| 35 |
self.offset |
| 36 |
} |
| 37 |
|
| 38 |
/// Skip n bytes. |
| 39 |
/// |
| 40 |
/// # Panics |
| 41 |
/// |
| 42 |
/// If the remaining quantity is less than `n`. |
| 43 |
pub fn skip(&mut self, n: usize) { |
| 44 |
assert!(self.remaining() >= n, "insufficient data"); |
| 45 |
self.offset += n; |
| 46 |
} |
| 47 |
|
| 48 |
/// Skip helper that panics if `n` is `None` or not able to fit in `usize`. |
| 49 |
/// Only use this for tests because we panic rather than reporting a result. |
| 50 |
#[cfg(any(test, feature = "test-fixture"))] |
| 51 |
fn skip_inner(&mut self, n: Option<u64>) { |
| 52 |
#[expect(clippy::unwrap_used, reason = "Only used in tests.")] |
| 53 |
self.skip(usize::try_from(n.expect("invalid length")).unwrap()); |
| 54 |
} |
| 55 |
|
| 56 |
/// Skip a vector. Panics if there isn't enough space. |
| 57 |
/// Only use this for tests because we panic rather than reporting a result. |
| 58 |
#[cfg(any(test, feature = "test-fixture"))] |
| 59 |
pub fn skip_vec(&mut self, n: usize) { |
| 60 |
let len = self.decode_n(n); |
| 61 |
self.skip_inner(len); |
| 62 |
} |
| 63 |
|
| 64 |
/// Skip a variable length vector. Panics if there isn't enough space. |
| 65 |
/// Only use this for tests because we panic rather than reporting a result. |
| 66 |
#[cfg(any(test, feature = "test-fixture"))] |
| 67 |
pub fn skip_vvec(&mut self) { |
| 68 |
let len = self.decode_varint(); |
| 69 |
self.skip_inner(len); |
| 70 |
} |
| 71 |
|
| 72 |
/// Provides the next byte without moving the read position. |
| 73 |
#[must_use] |
| 74 |
pub const fn peek_byte(&self) -> Option<u8> { |
| 75 |
if self.remaining() < 1 { |
| 76 |
None |
| 77 |
} else { |
| 78 |
Some(self.buf[self.offset]) |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
/// Decodes arbitrary data. |
| 83 |
pub fn decode(&mut self, n: usize) -> Option<&'a [u8]> { |
| 84 |
if self.remaining() < n { |
| 85 |
return None; |
| 86 |
} |
| 87 |
let res = &self.buf[self.offset..self.offset + n]; |
| 88 |
self.offset += n; |
| 89 |
Some(res) |
| 90 |
} |
| 91 |
|
| 92 |
#[inline] |
| 93 |
pub(crate) fn decode_n(&mut self, n: usize) -> Option<u64> { |
| 94 |
debug_assert!(n > 0 && n <= 8); |
| 95 |
if self.remaining() < n { |
| 96 |
return None; |
| 97 |
} |
| 98 |
Some(if n == 1 { |
| 99 |
let v = u64::from(self.buf[self.offset]); |
| 100 |
self.offset += 1; |
| 101 |
v |
| 102 |
} else { |
| 103 |
let mut buf = [0; 8]; |
| 104 |
buf[8 - n..].copy_from_slice(&self.buf[self.offset..self.offset + n]); |
| 105 |
self.offset += n; |
| 106 |
u64::from_be_bytes(buf) |
| 107 |
}) |
| 108 |
} |
| 109 |
|
| 110 |
/// Decodes a big-endian, unsigned integer value into the target type. |
| 111 |
/// This returns `None` if there is not enough data remaining |
| 112 |
/// or if the conversion to the identified type fails. |
| 113 |
/// Conversion is via `u64`, so failures are impossible for |
| 114 |
/// unsigned integer types: `u8`, `u16`, `u32`, or `u64`. |
| 115 |
/// Signed types will fail if the high bit is set. |
| 116 |
pub fn decode_uint<T: TryFrom<u64>>(&mut self) -> Option<T> { |
| 117 |
let v = self.decode_n(size_of::<T>()); |
| 118 |
T::try_from(v?).ok() |
| 119 |
} |
| 120 |
|
| 121 |
/// Decodes a QUIC varint. |
| 122 |
pub fn decode_varint(&mut self) -> Option<u64> { |
| 123 |
let b1 = self.decode_n(1)?; |
| 124 |
match b1 >> 6 { |
| 125 |
0 => Some(b1), |
| 126 |
1 => Some(((b1 & 0x3f) << 8) | self.decode_n(1)?), |
| 127 |
2 => Some(((b1 & 0x3f) << 24) | self.decode_n(3)?), |
| 128 |
3 => Some(((b1 & 0x3f) << 56) | self.decode_n(7)?), |
| 129 |
_ => unreachable!(), |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
/// Decodes the rest of the buffer. Infallible. |
| 134 |
pub fn decode_remainder(&mut self) -> &'a [u8] { |
| 135 |
let res = &self.buf[self.offset..]; |
| 136 |
self.offset = self.buf.len(); |
| 137 |
res |
| 138 |
} |
| 139 |
|
| 140 |
fn decode_checked(&mut self, n: Option<u64>) -> Option<&'a [u8]> { |
| 141 |
if let Ok(l) = usize::try_from(n?) { |
| 142 |
self.decode(l) |
| 143 |
} else { |
| 144 |
// sizeof(usize) < sizeof(u64) and the value is greater than |
| 145 |
// usize can hold. Throw away the rest of the input. |
| 146 |
self.offset = self.buf.len(); |
| 147 |
None |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
/// Decodes a TLS-style length-prefixed buffer. |
| 152 |
pub fn decode_vec(&mut self, n: usize) -> Option<&'a [u8]> { |
| 153 |
let len = self.decode_n(n); |
| 154 |
self.decode_checked(len) |
| 155 |
} |
| 156 |
|
| 157 |
/// Decodes a QUIC varint-length-prefixed buffer. |
| 158 |
pub fn decode_vvec(&mut self) -> Option<&'a [u8]> { |
| 159 |
let len = self.decode_varint(); |
| 160 |
self.decode_checked(len) |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
// Implement `AsRef` for `Decoder` so that values can be examined without |
| 165 |
// moving the cursor. |
| 166 |
impl<'a> AsRef<[u8]> for Decoder<'a> { |
| 167 |
fn as_ref(&self) -> &'a [u8] { |
| 168 |
&self.buf[self.offset..] |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
impl Debug for Decoder<'_> { |
| 173 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 174 |
f.write_str(&hex_with_len(self.as_ref())) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
impl<'a> From<&'a [u8]> for Decoder<'a> { |
| 179 |
fn from(buf: &'a [u8]) -> Self { |
| 180 |
Decoder::new(buf) |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
impl<'a, T> From<&'a T> for Decoder<'a> |
| 185 |
where |
| 186 |
T: AsRef<[u8]>, |
| 187 |
{ |
| 188 |
fn from(buf: &'a T) -> Self { |
| 189 |
Decoder::new(buf.as_ref()) |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
impl<'b> PartialEq<Decoder<'b>> for Decoder<'_> { |
| 194 |
fn eq(&self, other: &Decoder<'b>) -> bool { |
| 195 |
self.buf == other.buf |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
/// Encoder is good for building data structures. |
| 200 |
#[derive(Clone, Default, PartialEq, Eq)] |
| 201 |
pub struct Encoder { |
| 202 |
buf: Vec<u8>, |
| 203 |
} |
| 204 |
|
| 205 |
impl Encoder { |
| 206 |
/// Static helper function for previewing the results of encoding without doing it. |
| 207 |
/// |
| 208 |
/// # Panics |
| 209 |
/// |
| 210 |
/// When `v` is too large. |
| 211 |
#[must_use] |
| 212 |
pub const fn varint_len(v: u64) -> usize { |
| 213 |
match () { |
| 214 |
() if v < (1 << 6) => 1, |
| 215 |
() if v < (1 << 14) => 2, |
| 216 |
() if v < (1 << 30) => 4, |
| 217 |
() if v < (1 << 62) => 8, |
| 218 |
() => panic!("Varint value too large"), |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
/// Static helper to determine how long a varint-prefixed array encodes to. |
| 223 |
/// |
| 224 |
/// # Panics |
| 225 |
/// |
| 226 |
/// When `len` doesn't fit in a `u64`. |
| 227 |
#[must_use] |
| 228 |
pub fn vvec_len(len: usize) -> usize { |
| 229 |
Self::varint_len(u64::try_from(len).expect("usize should fit into u64")) + len |
| 230 |
} |
| 231 |
|
| 232 |
/// Default construction of an empty buffer. |
| 233 |
#[must_use] |
| 234 |
pub fn new() -> Self { |
| 235 |
Self::default() |
| 236 |
} |
| 237 |
|
| 238 |
/// Construction of a buffer with a predetermined capacity. |
| 239 |
#[must_use] |
| 240 |
pub fn with_capacity(capacity: usize) -> Self { |
| 241 |
Self { |
| 242 |
buf: Vec::with_capacity(capacity), |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
/// Get the capacity of the underlying buffer: the number of bytes that can be |
| 247 |
/// written without causing an allocation to occur. |
| 248 |
#[must_use] |
| 249 |
pub fn capacity(&self) -> usize { |
| 250 |
self.buf.capacity() |
| 251 |
} |
| 252 |
|
| 253 |
/// Get the length of the underlying buffer: the number of bytes that have |
| 254 |
/// been written to the buffer. |
| 255 |
#[must_use] |
| 256 |
pub fn len(&self) -> usize { |
| 257 |
self.buf.len() |
| 258 |
} |
| 259 |
|
| 260 |
/// Returns true if the encoder buffer contains no elements. |
| 261 |
#[must_use] |
| 262 |
pub fn is_empty(&self) -> bool { |
| 263 |
self.buf.is_empty() |
| 264 |
} |
| 265 |
|
| 266 |
/// Create a view of the current contents of the buffer. |
| 267 |
/// Note: for a view of a slice, use `Decoder::new(&enc[s..e])` |
| 268 |
#[must_use] |
| 269 |
pub fn as_decoder(&self) -> Decoder { |
| 270 |
Decoder::new(self.as_ref()) |
| 271 |
} |
| 272 |
|
| 273 |
/// Don't use this except in testing. |
| 274 |
/// |
| 275 |
/// # Panics |
| 276 |
/// |
| 277 |
/// When `s` contains non-hex values or an odd number of values. |
| 278 |
#[cfg(any(test, feature = "test-fixture"))] |
| 279 |
#[must_use] |
| 280 |
pub fn from_hex(s: impl AsRef<str>) -> Self { |
| 281 |
let s = s.as_ref(); |
| 282 |
assert_eq!(s.len() % 2, 0, "Needs to be even length"); |
| 283 |
|
| 284 |
let cap = s.len() / 2; |
| 285 |
let mut enc = Self::with_capacity(cap); |
| 286 |
|
| 287 |
for i in 0..cap { |
| 288 |
#[expect(clippy::unwrap_used, reason = "Only used in tests.")] |
| 289 |
let v = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).unwrap(); |
| 290 |
enc.encode_byte(v); |
| 291 |
} |
| 292 |
enc |
| 293 |
} |
| 294 |
|
| 295 |
/// Generic encode routine for arbitrary data. |
| 296 |
pub fn encode(&mut self, data: &[u8]) -> &mut Self { |
| 297 |
self.buf.extend_from_slice(data.as_ref()); |
| 298 |
self |
| 299 |
} |
| 300 |
|
| 301 |
/// Encode a single byte. |
| 302 |
pub fn encode_byte(&mut self, data: u8) -> &mut Self { |
| 303 |
self.buf.push(data); |
| 304 |
self |
| 305 |
} |
| 306 |
|
| 307 |
/// Encode an integer of any size up to u64. |
| 308 |
/// |
| 309 |
/// # Panics |
| 310 |
/// |
| 311 |
/// When `n` is outside the range `1..=8`. |
| 312 |
pub fn encode_uint<T: Into<u64>>(&mut self, n: usize, v: T) -> &mut Self { |
| 313 |
let v = v.into(); |
| 314 |
assert!(n > 0 && n <= 8); |
| 315 |
for i in 0..n { |
| 316 |
self.encode_byte(((v >> (8 * (n - i - 1))) & 0xff) as u8); |
| 317 |
} |
| 318 |
self |
| 319 |
} |
| 320 |
|
| 321 |
/// Encode a QUIC varint. |
| 322 |
/// |
| 323 |
/// # Panics |
| 324 |
/// |
| 325 |
/// When `v >= 1<<62`. |
| 326 |
pub fn encode_varint<T: Into<u64>>(&mut self, v: T) -> &mut Self { |
| 327 |
let v = v.into(); |
| 328 |
match () { |
| 329 |
() if v < (1 << 6) => self.encode_uint(1, v), |
| 330 |
() if v < (1 << 14) => self.encode_uint(2, v | (1 << 14)), |
| 331 |
() if v < (1 << 30) => self.encode_uint(4, v | (2 << 30)), |
| 332 |
() if v < (1 << 62) => self.encode_uint(8, v | (3 << 62)), |
| 333 |
() => panic!("Varint value too large"), |
| 334 |
}; |
| 335 |
self |
| 336 |
} |
| 337 |
|
| 338 |
/// Encode a vector in TLS style. |
| 339 |
/// |
| 340 |
/// # Panics |
| 341 |
/// |
| 342 |
/// When `v` is longer than 2^64. |
| 343 |
pub fn encode_vec(&mut self, n: usize, v: &[u8]) -> &mut Self { |
| 344 |
self.encode_uint( |
| 345 |
n, |
| 346 |
u64::try_from(v.as_ref().len()).expect("v is longer than 2^64"), |
| 347 |
) |
| 348 |
.encode(v) |
| 349 |
} |
| 350 |
|
| 351 |
/// Encode a vector in TLS style using a closure for the contents. |
| 352 |
/// |
| 353 |
/// # Panics |
| 354 |
/// |
| 355 |
/// When `f()` returns a length larger than `2^8n`. |
| 356 |
#[expect( |
| 357 |
clippy::cast_possible_truncation, |
| 358 |
reason = "AND'ing with 0xff makes this OK." |
| 359 |
)] |
| 360 |
pub fn encode_vec_with<F: FnOnce(&mut Self)>(&mut self, n: usize, f: F) -> &mut Self { |
| 361 |
let start = self.buf.len(); |
| 362 |
self.buf.resize(self.buf.len() + n, 0); |
| 363 |
f(self); |
| 364 |
let len = self.buf.len() - start - n; |
| 365 |
assert!(len < (1 << (n * 8))); |
| 366 |
for i in 0..n { |
| 367 |
self.buf[start + i] = ((len >> (8 * (n - i - 1))) & 0xff) as u8; |
| 368 |
} |
| 369 |
self |
| 370 |
} |
| 371 |
|
| 372 |
/// Encode a vector with a varint length. |
| 373 |
/// |
| 374 |
/// # Panics |
| 375 |
/// |
| 376 |
/// When `v` is longer than 2^64. |
| 377 |
pub fn encode_vvec(&mut self, v: &[u8]) -> &mut Self { |
| 378 |
self.encode_varint(u64::try_from(v.as_ref().len()).expect("v is longer than 2^64")) |
| 379 |
.encode(v) |
| 380 |
} |
| 381 |
|
| 382 |
/// Encode a vector with a varint length using a closure. |
| 383 |
/// |
| 384 |
/// # Panics |
| 385 |
/// |
| 386 |
/// When `f()` writes more than 2^62 bytes. |
| 387 |
pub fn encode_vvec_with<F: FnOnce(&mut Self)>(&mut self, f: F) -> &mut Self { |
| 388 |
let start = self.buf.len(); |
| 389 |
// Optimize for short buffers, reserve a single byte for the length. |
| 390 |
self.buf.resize(self.buf.len() + 1, 0); |
| 391 |
f(self); |
| 392 |
let len = self.buf.len() - start - 1; |
| 393 |
|
| 394 |
// Now to insert a varint for `len` before the encoded block. |
| 395 |
// |
| 396 |
// We now have one zero byte at `start`, followed by `len` encoded bytes: |
| 397 |
// | 0 | ... encoded ... | |
| 398 |
// We are going to encode a varint by putting the low bytes in that spare byte. |
| 399 |
// Any additional bytes for the varint are put after the encoded blob: |
| 400 |
// | low | ... encoded ... | varint high | |
| 401 |
// Then we will rotate that entire piece right, by however many bytes we add: |
| 402 |
// | varint high | low | ... encoded ... | |
| 403 |
// As long as encoding more than 63 bytes is rare, this won't cost much relative |
| 404 |
// to the convenience of being able to use this function. |
| 405 |
|
| 406 |
let v = u64::try_from(len).expect("encoded value fits in a u64"); |
| 407 |
// The lower order byte fits before the inserted block of bytes. |
| 408 |
self.buf[start] = (v & 0xff) as u8; |
| 409 |
let (count, bits) = match () { |
| 410 |
// Great. The byte we have is enough. |
| 411 |
() if v < (1 << 6) => return self, |
| 412 |
() if v < (1 << 14) => (1, 1 << 6), |
| 413 |
() if v < (1 << 30) => (3, 2 << 22), |
| 414 |
() if v < (1 << 62) => (7, 3 << 54), |
| 415 |
() => panic!("Varint value too large"), |
| 416 |
}; |
| 417 |
// Now, we need to encode the high bits after the main block, ... |
| 418 |
self.encode_uint(count, (v >> 8) | bits); |
| 419 |
// ..., then rotate the entire thing right by the same amount. |
| 420 |
self.buf[start..].rotate_right(count); |
| 421 |
self |
| 422 |
} |
| 423 |
|
| 424 |
/// Truncate the encoder to the given size. |
| 425 |
pub fn truncate(&mut self, len: usize) { |
| 426 |
self.buf.truncate(len); |
| 427 |
} |
| 428 |
|
| 429 |
/// Pad the buffer to `len` with bytes set to `v`. |
| 430 |
pub fn pad_to(&mut self, len: usize, v: u8) { |
| 431 |
if len > self.buf.len() { |
| 432 |
self.buf.resize(len, v); |
| 433 |
} |
| 434 |
} |
| 435 |
} |
| 436 |
|
| 437 |
impl Debug for Encoder { |
| 438 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 439 |
f.write_str(&hex_with_len(self)) |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
impl AsRef<[u8]> for Encoder { |
| 444 |
fn as_ref(&self) -> &[u8] { |
| 445 |
self.buf.as_ref() |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
impl AsMut<[u8]> for Encoder { |
| 450 |
fn as_mut(&mut self) -> &mut [u8] { |
| 451 |
self.buf.as_mut() |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
impl<'a> From<Decoder<'a>> for Encoder { |
| 456 |
fn from(dec: Decoder<'a>) -> Self { |
| 457 |
Self::from(&dec.buf[dec.offset..]) |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
impl From<&[u8]> for Encoder { |
| 462 |
fn from(buf: &[u8]) -> Self { |
| 463 |
Self { |
| 464 |
buf: Vec::from(buf), |
| 465 |
} |
| 466 |
} |
| 467 |
} |
| 468 |
|
| 469 |
impl From<Encoder> for Vec<u8> { |
| 470 |
fn from(buf: Encoder) -> Self { |
| 471 |
buf.buf |
| 472 |
} |
| 473 |
} |
| 474 |
|
| 475 |
impl Write for Encoder { |
| 476 |
fn write_str(&mut self, s: &str) -> fmt::Result { |
| 477 |
self.buf.extend_from_slice(s.as_bytes()); |
| 478 |
Ok(()) |
| 479 |
} |
| 480 |
} |
| 481 |
|
| 482 |
#[cfg(test)] |
| 483 |
mod tests { |
| 484 |
use super::{Decoder, Encoder}; |
| 485 |
|
| 486 |
#[test] |
| 487 |
fn decode() { |
| 488 |
let enc = Encoder::from_hex("012345"); |
| 489 |
let mut dec = enc.as_decoder(); |
| 490 |
assert_eq!(dec.decode(2).unwrap(), &[0x01, 0x23]); |
| 491 |
assert!(dec.decode(2).is_none()); |
| 492 |
} |
| 493 |
|
| 494 |
#[test] |
| 495 |
fn decode_byte() { |
| 496 |
let enc = Encoder::from_hex("0123"); |
| 497 |
let mut dec = enc.as_decoder(); |
| 498 |
|
| 499 |
assert_eq!(dec.decode_uint::<u8>().unwrap(), 0x01); |
| 500 |
assert_eq!(dec.decode_uint::<u8>().unwrap(), 0x23); |
| 501 |
assert!(dec.decode_uint::<u8>().is_none()); |
| 502 |
} |
| 503 |
|
| 504 |
#[test] |
| 505 |
fn peek_byte() { |
| 506 |
let enc = Encoder::from_hex("01"); |
| 507 |
let mut dec = enc.as_decoder(); |
| 508 |
|
| 509 |
assert_eq!(dec.offset(), 0); |
| 510 |
assert_eq!(dec.peek_byte().unwrap(), 0x01); |
| 511 |
dec.skip(1); |
| 512 |
assert_eq!(dec.offset(), 1); |
| 513 |
assert!(dec.peek_byte().is_none()); |
| 514 |
} |
| 515 |
|
| 516 |
#[test] |
| 517 |
fn decode_byte_short() { |
| 518 |
let enc = Encoder::from_hex(""); |
| 519 |
let mut dec = enc.as_decoder(); |
| 520 |
assert!(dec.decode_uint::<u8>().is_none()); |
| 521 |
} |
| 522 |
|
| 523 |
#[test] |
| 524 |
fn decode_remainder() { |
| 525 |
let enc = Encoder::from_hex("012345"); |
| 526 |
let mut dec = enc.as_decoder(); |
| 527 |
assert_eq!(dec.decode_remainder(), &[0x01, 0x23, 0x45]); |
| 528 |
assert!(dec.decode(2).is_none()); |
| 529 |
|
| 530 |
let mut dec = Decoder::from(&[]); |
| 531 |
assert!(dec.decode_remainder().is_empty()); |
| 532 |
} |
| 533 |
|
| 534 |
#[test] |
| 535 |
fn decode_vec() { |
| 536 |
let enc = Encoder::from_hex("012345"); |
| 537 |
let mut dec = enc.as_decoder(); |
| 538 |
assert_eq!(dec.decode_vec(1).expect("read one octet length"), &[0x23]); |
| 539 |
assert_eq!(dec.remaining(), 1); |
| 540 |
|
| 541 |
let enc = Encoder::from_hex("00012345"); |
| 542 |
let mut dec = enc.as_decoder(); |
| 543 |
assert_eq!(dec.decode_vec(2).expect("read two octet length"), &[0x23]); |
| 544 |
assert_eq!(dec.remaining(), 1); |
| 545 |
} |
| 546 |
|
| 547 |
#[test] |
| 548 |
fn decode_vec_short() { |
| 549 |
// The length is too short. |
| 550 |
let enc = Encoder::from_hex("02"); |
| 551 |
let mut dec = enc.as_decoder(); |
| 552 |
assert!(dec.decode_vec(2).is_none()); |
| 553 |
|
| 554 |
// The body is too short. |
| 555 |
let enc = Encoder::from_hex("0200"); |
| 556 |
let mut dec = enc.as_decoder(); |
| 557 |
assert!(dec.decode_vec(1).is_none()); |
| 558 |
} |
| 559 |
|
| 560 |
#[test] |
| 561 |
fn decode_vvec() { |
| 562 |
let enc = Encoder::from_hex("012345"); |
| 563 |
let mut dec = enc.as_decoder(); |
| 564 |
assert_eq!(dec.decode_vvec().expect("read one octet length"), &[0x23]); |
| 565 |
assert_eq!(dec.remaining(), 1); |
| 566 |
|
| 567 |
let enc = Encoder::from_hex("40012345"); |
| 568 |
let mut dec = enc.as_decoder(); |
| 569 |
assert_eq!(dec.decode_vvec().expect("read two octet length"), &[0x23]); |
| 570 |
assert_eq!(dec.remaining(), 1); |
| 571 |
} |
| 572 |
|
| 573 |
#[test] |
| 574 |
fn decode_vvec_short() { |
| 575 |
// The length field is too short. |
| 576 |
let enc = Encoder::from_hex("ff"); |
| 577 |
let mut dec = enc.as_decoder(); |
| 578 |
assert!(dec.decode_vvec().is_none()); |
| 579 |
|
| 580 |
let enc = Encoder::from_hex("405500"); |
| 581 |
let mut dec = enc.as_decoder(); |
| 582 |
assert!(dec.decode_vvec().is_none()); |
| 583 |
} |
| 584 |
|
| 585 |
#[test] |
| 586 |
fn skip() { |
| 587 |
let enc = Encoder::from_hex("ffff"); |
| 588 |
let mut dec = enc.as_decoder(); |
| 589 |
dec.skip(1); |
| 590 |
assert_eq!(dec.remaining(), 1); |
| 591 |
} |
| 592 |
|
| 593 |
#[test] |
| 594 |
#[should_panic(expected = "insufficient data")] |
| 595 |
fn skip_too_much() { |
| 596 |
let enc = Encoder::from_hex("ff"); |
| 597 |
let mut dec = enc.as_decoder(); |
| 598 |
dec.skip(2); |
| 599 |
} |
| 600 |
|
| 601 |
#[test] |
| 602 |
fn skip_vec() { |
| 603 |
let enc = Encoder::from_hex("012345"); |
| 604 |
let mut dec = enc.as_decoder(); |
| 605 |
dec.skip_vec(1); |
| 606 |
assert_eq!(dec.remaining(), 1); |
| 607 |
} |
| 608 |
|
| 609 |
#[test] |
| 610 |
#[should_panic(expected = "insufficient data")] |
| 611 |
fn skip_vec_too_much() { |
| 612 |
let enc = Encoder::from_hex("ff1234"); |
| 613 |
let mut dec = enc.as_decoder(); |
| 614 |
dec.skip_vec(1); |
| 615 |
} |
| 616 |
|
| 617 |
#[test] |
| 618 |
#[should_panic(expected = "invalid length")] |
| 619 |
fn skip_vec_short_length() { |
| 620 |
let enc = Encoder::from_hex("ff"); |
| 621 |
let mut dec = enc.as_decoder(); |
| 622 |
dec.skip_vec(4); |
| 623 |
} |
| 624 |
#[test] |
| 625 |
fn skip_vvec() { |
| 626 |
let enc = Encoder::from_hex("012345"); |
| 627 |
let mut dec = enc.as_decoder(); |
| 628 |
dec.skip_vvec(); |
| 629 |
assert_eq!(dec.remaining(), 1); |
| 630 |
} |
| 631 |
|
| 632 |
#[test] |
| 633 |
#[should_panic(expected = "insufficient data")] |
| 634 |
fn skip_vvec_too_much() { |
| 635 |
let enc = Encoder::from_hex("0f1234"); |
| 636 |
let mut dec = enc.as_decoder(); |
| 637 |
dec.skip_vvec(); |
| 638 |
} |
| 639 |
|
| 640 |
#[test] |
| 641 |
#[should_panic(expected = "invalid length")] |
| 642 |
fn skip_vvec_short_length() { |
| 643 |
let enc = Encoder::from_hex("ff"); |
| 644 |
let mut dec = enc.as_decoder(); |
| 645 |
dec.skip_vvec(); |
| 646 |
} |
| 647 |
|
| 648 |
#[test] |
| 649 |
fn encoded_lengths() { |
| 650 |
assert_eq!(Encoder::varint_len(0), 1); |
| 651 |
assert_eq!(Encoder::varint_len(0x3f), 1); |
| 652 |
assert_eq!(Encoder::varint_len(0x40), 2); |
| 653 |
assert_eq!(Encoder::varint_len(0x3fff), 2); |
| 654 |
assert_eq!(Encoder::varint_len(0x4000), 4); |
| 655 |
assert_eq!(Encoder::varint_len(0x3fff_ffff), 4); |
| 656 |
assert_eq!(Encoder::varint_len(0x4000_0000), 8); |
| 657 |
} |
| 658 |
|
| 659 |
#[test] |
| 660 |
#[should_panic(expected = "Varint value too large")] |
| 661 |
const fn encoded_length_oob() { |
| 662 |
_ = Encoder::varint_len(1 << 62); |
| 663 |
} |
| 664 |
|
| 665 |
#[test] |
| 666 |
fn encoded_vvec_lengths() { |
| 667 |
assert_eq!(Encoder::vvec_len(0), 1); |
| 668 |
assert_eq!(Encoder::vvec_len(0x3f), 0x40); |
| 669 |
assert_eq!(Encoder::vvec_len(0x40), 0x42); |
| 670 |
assert_eq!(Encoder::vvec_len(0x3fff), 0x4001); |
| 671 |
assert_eq!(Encoder::vvec_len(0x4000), 0x4004); |
| 672 |
assert_eq!(Encoder::vvec_len(0x3fff_ffff), 0x4000_0003); |
| 673 |
assert_eq!(Encoder::vvec_len(0x4000_0000), 0x4000_0008); |
| 674 |
} |
| 675 |
|
| 676 |
#[test] |
| 677 |
#[cfg(target_pointer_width = "64")] // Test does not compile on 32-bit targets. |
| 678 |
#[should_panic(expected = "Varint value too large")] |
| 679 |
fn encoded_vvec_length_oob() { |
| 680 |
_ = Encoder::vvec_len(1 << 62); |
| 681 |
} |
| 682 |
|
| 683 |
#[test] |
| 684 |
fn encode_byte() { |
| 685 |
let mut enc = Encoder::default(); |
| 686 |
|
| 687 |
enc.encode_byte(1); |
| 688 |
assert_eq!(enc, Encoder::from_hex("01")); |
| 689 |
|
| 690 |
enc.encode_byte(0xfe); |
| 691 |
assert_eq!(enc, Encoder::from_hex("01fe")); |
| 692 |
} |
| 693 |
|
| 694 |
#[test] |
| 695 |
fn encode() { |
| 696 |
let mut enc = Encoder::default(); |
| 697 |
enc.encode(&[1, 2, 3]); |
| 698 |
assert_eq!(enc, Encoder::from_hex("010203")); |
| 699 |
} |
| 700 |
|
| 701 |
#[test] |
| 702 |
fn encode_uint() { |
| 703 |
let mut enc = Encoder::default(); |
| 704 |
enc.encode_uint(2, 10_u8); // 000a |
| 705 |
enc.encode_uint(1, 257_u16); // 01 |
| 706 |
enc.encode_uint(3, 0xff_ffff_u32); // ffffff |
| 707 |
enc.encode_uint(8, 0xfedc_ba98_7654_3210_u64); |
| 708 |
assert_eq!(enc, Encoder::from_hex("000a01fffffffedcba9876543210")); |
| 709 |
} |
| 710 |
|
| 711 |
#[test] |
| 712 |
fn builder_from_slice() { |
| 713 |
let slice = &[1, 2, 3]; |
| 714 |
let enc = Encoder::from(&slice[..]); |
| 715 |
assert_eq!(enc, Encoder::from_hex("010203")); |
| 716 |
} |
| 717 |
|
| 718 |
#[test] |
| 719 |
fn builder_inas_decoder() { |
| 720 |
let enc = Encoder::from_hex("010203"); |
| 721 |
let buf = &[1, 2, 3]; |
| 722 |
assert_eq!(enc.as_decoder(), Decoder::new(buf)); |
| 723 |
} |
| 724 |
|
| 725 |
struct UintTestCase { |
| 726 |
v: u64, |
| 727 |
b: String, |
| 728 |
} |
| 729 |
|
| 730 |
macro_rules! uint_tc { |
| 731 |
[$( $v:expr => $b:expr ),+ $(,)?] => { |
| 732 |
vec![ $( UintTestCase { v: $v, b: String::from($b) } ),+] |
| 733 |
}; |
| 734 |
} |
| 735 |
|
| 736 |
#[test] |
| 737 |
fn varint_encode_decode() { |
| 738 |
let cases = uint_tc![ |
| 739 |
0 => "00", |
| 740 |
1 => "01", |
| 741 |
63 => "3f", |
| 742 |
64 => "4040", |
| 743 |
16383 => "7fff", |
| 744 |
16384 => "80004000", |
| 745 |
(1 << 30) - 1 => "bfffffff", |
| 746 |
1 << 30 => "c000000040000000", |
| 747 |
(1 << 62) - 1 => "ffffffffffffffff", |
| 748 |
]; |
| 749 |
|
| 750 |
for c in cases { |
| 751 |
assert_eq!(Encoder::varint_len(c.v), c.b.len() / 2); |
| 752 |
|
| 753 |
let mut enc = Encoder::default(); |
| 754 |
enc.encode_varint(c.v); |
| 755 |
let encoded = Encoder::from_hex(&c.b); |
| 756 |
assert_eq!(enc, encoded); |
| 757 |
|
| 758 |
let mut dec = encoded.as_decoder(); |
| 759 |
let v = dec.decode_varint().expect("should decode"); |
| 760 |
assert_eq!(dec.remaining(), 0); |
| 761 |
assert_eq!(v, c.v); |
| 762 |
} |
| 763 |
} |
| 764 |
|
| 765 |
#[test] |
| 766 |
fn varint_decode_long_zero() { |
| 767 |
for c in &["4000", "80000000", "c000000000000000"] { |
| 768 |
let encoded = Encoder::from_hex(c); |
| 769 |
let mut dec = encoded.as_decoder(); |
| 770 |
let v = dec.decode_varint().expect("should decode"); |
| 771 |
assert_eq!(dec.remaining(), 0); |
| 772 |
assert_eq!(v, 0); |
| 773 |
} |
| 774 |
} |
| 775 |
|
| 776 |
#[test] |
| 777 |
fn varint_decode_short() { |
| 778 |
for c in &["40", "800000", "c0000000000000"] { |
| 779 |
let encoded = Encoder::from_hex(c); |
| 780 |
let mut dec = encoded.as_decoder(); |
| 781 |
assert!(dec.decode_varint().is_none()); |
| 782 |
} |
| 783 |
} |
| 784 |
|
| 785 |
#[test] |
| 786 |
fn encode_vec() { |
| 787 |
let mut enc = Encoder::default(); |
| 788 |
enc.encode_vec(2, &[1, 2, 0x34]); |
| 789 |
assert_eq!(enc, Encoder::from_hex("0003010234")); |
| 790 |
} |
| 791 |
|
| 792 |
#[test] |
| 793 |
fn encode_vec_with() { |
| 794 |
let mut enc = Encoder::default(); |
| 795 |
enc.encode_vec_with(2, |enc_inner| { |
| 796 |
enc_inner.encode(Encoder::from_hex("02").as_ref()); |
| 797 |
}); |
| 798 |
assert_eq!(enc, Encoder::from_hex("000102")); |
| 799 |
} |
| 800 |
|
| 801 |
#[test] |
| 802 |
#[should_panic(expected = "assertion failed")] |
| 803 |
fn encode_vec_with_overflow() { |
| 804 |
let mut enc = Encoder::default(); |
| 805 |
enc.encode_vec_with(1, |enc_inner| { |
| 806 |
enc_inner.encode(&[0xb0; 256]); |
| 807 |
}); |
| 808 |
} |
| 809 |
|
| 810 |
#[test] |
| 811 |
fn encode_vvec() { |
| 812 |
let mut enc = Encoder::default(); |
| 813 |
enc.encode_vvec(&[1, 2, 0x34]); |
| 814 |
assert_eq!(enc, Encoder::from_hex("03010234")); |
| 815 |
} |
| 816 |
|
| 817 |
#[test] |
| 818 |
fn encode_vvec_with() { |
| 819 |
let mut enc = Encoder::default(); |
| 820 |
enc.encode_vvec_with(|enc_inner| { |
| 821 |
enc_inner.encode(Encoder::from_hex("02").as_ref()); |
| 822 |
}); |
| 823 |
assert_eq!(enc, Encoder::from_hex("0102")); |
| 824 |
} |
| 825 |
|
| 826 |
#[test] |
| 827 |
fn encode_vvec_with_longer() { |
| 828 |
let mut enc = Encoder::default(); |
| 829 |
enc.encode_vvec_with(|enc_inner| { |
| 830 |
enc_inner.encode(&[0xa5; 65]); |
| 831 |
}); |
| 832 |
let v: Vec<u8> = enc.into(); |
| 833 |
assert_eq!(&v[..3], &[0x40, 0x41, 0xa5]); |
| 834 |
} |
| 835 |
|
| 836 |
// Test that Deref to &[u8] works for Encoder. |
| 837 |
#[test] |
| 838 |
fn encode_builder() { |
| 839 |
let mut enc = Encoder::from_hex("ff"); |
| 840 |
let enc2 = Encoder::from_hex("010234"); |
| 841 |
enc.encode(enc2.as_ref()); |
| 842 |
assert_eq!(enc, Encoder::from_hex("ff010234")); |
| 843 |
} |
| 844 |
|
| 845 |
// Test that Deref to &[u8] works for Decoder. |
| 846 |
#[test] |
| 847 |
fn encode_view() { |
| 848 |
let mut enc = Encoder::from_hex("ff"); |
| 849 |
let enc2 = Encoder::from_hex("010234"); |
| 850 |
let v = enc2.as_decoder(); |
| 851 |
enc.encode(v.as_ref()); |
| 852 |
assert_eq!(enc, Encoder::from_hex("ff010234")); |
| 853 |
} |
| 854 |
|
| 855 |
#[test] |
| 856 |
fn encode_mutate() { |
| 857 |
let mut enc = Encoder::from_hex("010234"); |
| 858 |
enc.as_mut()[0] = 0xff; |
| 859 |
assert_eq!(enc, Encoder::from_hex("ff0234")); |
| 860 |
} |
| 861 |
|
| 862 |
#[test] |
| 863 |
fn pad() { |
| 864 |
let mut enc = Encoder::from_hex("010234"); |
| 865 |
enc.pad_to(5, 0); |
| 866 |
assert_eq!(enc, Encoder::from_hex("0102340000")); |
| 867 |
enc.pad_to(4, 0); |
| 868 |
assert_eq!(enc, Encoder::from_hex("0102340000")); |
| 869 |
enc.pad_to(7, 0xc2); |
| 870 |
assert_eq!(enc, Encoder::from_hex("0102340000c2c2")); |
| 871 |
} |
| 872 |
} |