Skip to main content

moq_net/coding/
varint.rs

1//! Variable-length integers: QUIC's two-bit length tag, and moq-transport's leading ones.
2//!
3//! A varint is a wire encoding of a plain `u64`, not a type. The codec works on the two
4//! `u32` halves so it never needs 64-bit bitwise math, which a JavaScript `number`
5//! cannot do.
6
7use thiserror::Error;
8
9use super::{DecodeError, EncodeError};
10use crate::{Draft, Version, ietf, lite};
11
12/// The number does not fit the target: a varint wire form or a narrower integer.
13#[derive(Debug, Copy, Clone, Eq, PartialEq, Error)]
14#[error("value out of range")]
15pub struct BoundsExceeded;
16
17/// The largest value the QUIC form can carry: `2^62 - 1`.
18pub(crate) const MAX_QUIC: u64 = (1 << 62) - 1;
19
20/// The longest varint either form decodes, minimal or not: the leading-ones form's 9 bytes,
21/// past QUIC's 8.
22pub(crate) const MAX_LEN: usize = 9;
23
24/// How a protocol version lays out a varint on the wire.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub(crate) enum Form {
27	/// QUIC's two-bit length tag, up to [`MAX_QUIC`].
28	Quic,
29	/// Leading one bits count the length, up to `u64::MAX`.
30	LeadingOnes,
31}
32
33impl From<lite::Version> for Form {
34	fn from(version: lite::Version) -> Self {
35		match version {
36			lite::Version::Lite01
37			| lite::Version::Lite02
38			| lite::Version::Lite03
39			| lite::Version::Lite04
40			| lite::Version::Lite05
41			| lite::Version::Lite06 => Self::Quic,
42			// Lite-07 is reached through its ALPN or a SETUP hand-off, so the form is known
43			// before the first byte of any lite-07 stream.
44			_ => Self::LeadingOnes,
45		}
46	}
47}
48
49impl From<ietf::Version> for Form {
50	fn from(_: ietf::Version) -> Self {
51		Self::LeadingOnes
52	}
53}
54
55impl From<Version> for Form {
56	fn from(version: Version) -> Self {
57		match version {
58			Version(Draft::Lite(v)) => v.into(),
59			Version(Draft::Ietf(v)) => v.into(),
60		}
61	}
62}
63
64/// The high and low 32 bits: the only place the codec splits a `u64`.
65const fn to_halves(value: u64) -> (u32, u32) {
66	((value >> 32) as u32, value as u32)
67}
68
69/// The inverse of [`to_halves`].
70const fn from_halves(hi: u32, lo: u32) -> u64 {
71	((hi as u64) << 32) | lo as u64
72}
73
74/// The bytes `value` takes on the wire in `form`, or [`BoundsExceeded`] if it does not fit.
75pub(crate) fn size(value: u64, form: Form) -> Result<usize, BoundsExceeded> {
76	let (hi, lo) = to_halves(value);
77	Ok(match form {
78		Form::Quic if hi == 0 && lo < 1 << 6 => 1,
79		Form::Quic if hi == 0 && lo < 1 << 14 => 2,
80		Form::Quic if hi == 0 && lo < 1 << 30 => 4,
81		Form::Quic if hi < 1 << 30 => 8,
82		Form::Quic => return Err(BoundsExceeded),
83		Form::LeadingOnes if hi == 0 && lo < 1 << 7 => 1,
84		Form::LeadingOnes if hi == 0 && lo < 1 << 14 => 2,
85		Form::LeadingOnes if hi == 0 && lo < 1 << 21 => 3,
86		Form::LeadingOnes if hi == 0 && lo < 1 << 28 => 4,
87		Form::LeadingOnes if hi < 1 << 3 => 5,
88		Form::LeadingOnes if hi < 1 << 10 => 6,
89		// The 7-byte form is skipped: one byte longer, but legal on every draft.
90		Form::LeadingOnes if hi < 1 << 24 => 8,
91		Form::LeadingOnes => 9,
92	})
93}
94
95/// Append the minimal encoding of `value` in `form`.
96///
97/// Fails past [`MAX_QUIC`] in the QUIC form, writing nothing.
98#[inline(always)]
99pub(super) fn write(value: u64, form: Form, out: &mut Vec<u8>) -> Result<(), BoundsExceeded> {
100	match form {
101		Form::Quic => write_quic(value, out),
102		Form::LeadingOnes => {
103			write_leading_ones(value, out);
104			Ok(())
105		}
106	}
107}
108
109// Each arm below is a fixed-size write or read, which is what keeps the codec as fast as
110// a hand-rolled `put_u16`/`get_u32`. The varint path is `inline(always)` from
111// `Encoder::varint`/`Decoder::varint` down: left to LLVM's heuristics it stays a call
112// whose `Result<u64, DecodeError>` goes through memory, which doubles the cost of a varint
113// in a tight loop. The QUIC read is an if-chain rather than a `match` on the tag: the jump
114// table measured ~35% slower on a mixed-length stream.
115
116#[inline(always)]
117fn write_quic(value: u64, out: &mut Vec<u8>) -> Result<(), BoundsExceeded> {
118	let (hi, lo) = to_halves(value);
119	if hi == 0 && lo < 1 << 6 {
120		out.push(lo as u8);
121	} else if hi == 0 && lo < 1 << 14 {
122		out.extend_from_slice(&(0x4000 | lo as u16).to_be_bytes());
123	} else if hi == 0 && lo < 1 << 30 {
124		out.extend_from_slice(&(0x8000_0000 | lo).to_be_bytes());
125	} else if hi < 1 << 30 {
126		let [a, b, c, d] = (0xc000_0000 | hi).to_be_bytes();
127		let [e, f, g, h] = lo.to_be_bytes();
128		out.extend_from_slice(&[a, b, c, d, e, f, g, h]);
129	} else {
130		return Err(BoundsExceeded);
131	}
132	Ok(())
133}
134
135#[inline(always)]
136fn write_leading_ones(value: u64, out: &mut Vec<u8>) {
137	let (hi, lo) = to_halves(value);
138	let [a, b, c, d] = lo.to_be_bytes();
139	if hi == 0 && lo < 1 << 7 {
140		out.push(d);
141	} else if hi == 0 && lo < 1 << 14 {
142		out.extend_from_slice(&[0x80 | c, d]);
143	} else if hi == 0 && lo < 1 << 21 {
144		out.extend_from_slice(&[0xc0 | b, c, d]);
145	} else if hi == 0 && lo < 1 << 28 {
146		out.extend_from_slice(&[0xe0 | a, b, c, d]);
147	} else if hi < 1 << 3 {
148		out.extend_from_slice(&[0xf0 | hi as u8, a, b, c, d]);
149	} else if hi < 1 << 10 {
150		out.extend_from_slice(&[0xf8 | (hi >> 8) as u8, hi as u8, a, b, c, d]);
151	} else if hi < 1 << 24 {
152		// The 7-byte form is skipped: one byte longer, but legal on every draft.
153		let [_, f, g, h] = hi.to_be_bytes();
154		out.extend_from_slice(&[0xfe, f, g, h, a, b, c, d]);
155	} else {
156		let [e, f, g, h] = hi.to_be_bytes();
157		out.extend_from_slice(&[0xff, e, f, g, h, a, b, c, d]);
158	}
159}
160
161/// Decode a varint in `form` from the front of `buf`, returning it and the rest of `buf`.
162#[inline(always)]
163#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
164pub(super) fn read(buf: &[u8], form: Form) -> Result<(u64, &[u8]), DecodeError> {
165	match form {
166		Form::Quic => read_quic(buf),
167		Form::LeadingOnes => read_leading_ones(buf),
168	}
169}
170
171#[inline(always)]
172fn read_quic(buf: &[u8]) -> Result<(u64, &[u8]), DecodeError> {
173	let Some((&first, rest)) = buf.split_first() else {
174		return Err(DecodeError::Short);
175	};
176
177	let be = u32::from_be_bytes;
178	if first < 0x40 {
179		Ok((first as u64, rest))
180	} else if first < 0x80 {
181		let ([a, b], rest) = buf.split_first_chunk().ok_or(DecodeError::Short)?;
182		Ok((be([0, 0, a & 0x3f, *b]) as u64, rest))
183	} else if first < 0xc0 {
184		let ([a, b, c, d], rest) = buf.split_first_chunk().ok_or(DecodeError::Short)?;
185		Ok((be([a & 0x3f, *b, *c, *d]) as u64, rest))
186	} else {
187		let ([a, b, c, d, lo @ ..], rest) = buf.split_first_chunk::<8>().ok_or(DecodeError::Short)?;
188		Ok((from_halves(be([a & 0x3f, *b, *c, *d]), be(*lo)), rest))
189	}
190}
191
192#[inline(always)]
193#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
194fn read_leading_ones(buf: &[u8]) -> Result<(u64, &[u8]), DecodeError> {
195	let Some((&first, rest)) = buf.split_first() else {
196		return Err(DecodeError::Short);
197	};
198
199	let be = u32::from_be_bytes;
200	Ok(match first.leading_ones() {
201		0 => (first as u64, rest),
202		1 => {
203			let ([a, b], rest) = buf.split_first_chunk().ok_or(DecodeError::Short)?;
204			(be([0, 0, a & 0x3f, *b]) as u64, rest)
205		}
206		2 => {
207			let ([a, b, c], rest) = buf.split_first_chunk().ok_or(DecodeError::Short)?;
208			(be([0, a & 0x1f, *b, *c]) as u64, rest)
209		}
210		3 => {
211			let ([a, b, c, d], rest) = buf.split_first_chunk().ok_or(DecodeError::Short)?;
212			(be([a & 0x0f, *b, *c, *d]) as u64, rest)
213		}
214		4 => {
215			let ([a, lo @ ..], rest) = buf.split_first_chunk::<5>().ok_or(DecodeError::Short)?;
216			(from_halves((a & 0x07) as u32, be(*lo)), rest)
217		}
218		5 => {
219			let ([a, b, lo @ ..], rest) = buf.split_first_chunk::<6>().ok_or(DecodeError::Short)?;
220			(from_halves(be([0, 0, a & 0x03, *b]), be(*lo)), rest)
221		}
222		6 => {
223			let ([a, b, c, lo @ ..], rest) = buf.split_first_chunk::<7>().ok_or(DecodeError::Short)?;
224			(from_halves(be([0, a & 0x01, *b, *c]), be(*lo)), rest)
225		}
226		7 => {
227			let ([_, b, c, d, lo @ ..], rest) = buf.split_first_chunk::<8>().ok_or(DecodeError::Short)?;
228			(from_halves(be([0, *b, *c, *d]), be(*lo)), rest)
229		}
230		_ => {
231			let ([_, hi @ .., e, f, g, h], rest) = buf.split_first_chunk::<9>().ok_or(DecodeError::Short)?;
232			(from_halves(be(*hi), be([*e, *f, *g, *h])), rest)
233		}
234	})
235}
236
237/// Decode a QUIC varint (two-bit length tag) from the front of `r`.
238pub fn decode_quic<R: bytes::Buf>(r: &mut R) -> Result<u64, DecodeError> {
239	let Some(&first) = r.chunk().first() else {
240		return Err(DecodeError::Short);
241	};
242
243	// Copy out so a varint split across chunks still decodes.
244	let len = 1usize << (first >> 6);
245	if r.remaining() < len {
246		return Err(DecodeError::Short);
247	}
248	let mut buf = [0u8; 8];
249	r.copy_to_slice(&mut buf[..len]);
250
251	Ok(read_quic(&buf[..len])?.0)
252}
253
254/// Encode `value` as a QUIC varint (two-bit length tag).
255///
256/// Fails with [`EncodeError::BoundsExceeded`] past `2^62 - 1`, writing nothing.
257pub fn encode_quic<W: bytes::BufMut>(value: u64, w: &mut W) -> Result<(), EncodeError> {
258	let len = size(value, Form::Quic)?;
259	if w.remaining_mut() < len {
260		return Err(EncodeError::Short);
261	}
262
263	let (hi, lo) = to_halves(value);
264	match len {
265		1 => w.put_u8(lo as u8),
266		2 => w.put_u16(0x4000 | lo as u16),
267		4 => w.put_u32(0x8000_0000 | lo),
268		_ => {
269			w.put_u32(0xc000_0000 | hi);
270			w.put_u32(lo);
271		}
272	}
273	Ok(())
274}
275
276/// Map a signed value onto the unsigned range: `(n << 1) ^ (n >> 63)`.
277///
278/// Small magnitudes stay small (-1 -> 1, 1 -> 2, -2 -> 3, ...), and all of `i64` fits.
279#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
280pub(crate) const fn zigzag(signed: i64) -> u64 {
281	((signed << 1) ^ (signed >> 63)) as u64
282}
283
284/// The inverse of [`zigzag`].
285#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
286pub(crate) const fn unzigzag(value: u64) -> i64 {
287	((value >> 1) as i64) ^ -((value & 1) as i64)
288}
289
290#[cfg(test)]
291mod tests {
292	use super::*;
293
294	const LEADING_ONES: Form = Form::LeadingOnes;
295
296	fn encode(value: u64, form: Form) -> Result<Vec<u8>, BoundsExceeded> {
297		let mut buf = Vec::new();
298		write(value, form, &mut buf)?;
299		assert_eq!(buf.len(), size(value, form)?, "size disagrees with the encoding");
300		Ok(buf)
301	}
302
303	/// Test vectors from the spec (Table 2: Example Integer Encodings),
304	/// excluding the known-buggy example 4 (0xdd7f3e7d).
305	#[test]
306	fn leading_ones_spec_examples() {
307		let cases: &[(&[u8], u64)] = &[
308			(&[0x25], 37),
309			(&[0x80, 0x25], 37),
310			(&[0xbb, 0xbd], 15_293),
311			// Example 4 (0xdd7f3e7d = 494,878,333) is omitted. The spec has a bug.
312			// See https://github.com/moq-wg/moq-transport/pull/1521
313			(&[0xfa, 0xa1, 0xa0, 0xe4, 0x03, 0xd8], 2_893_212_287_960),
314			(
315				&[0xfe, 0xfa, 0x31, 0x8f, 0xa8, 0xe3, 0xca, 0x11],
316				70_423_237_261_249_041,
317			),
318			(
319				&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
320				18_446_744_073_709_551_615,
321			),
322		];
323
324		for (bytes, expected) in cases {
325			let (decoded, rest) = read(bytes, LEADING_ONES).expect("decode should succeed");
326			assert_eq!(decoded, *expected, "decode mismatch for bytes {bytes:02x?}");
327			assert!(rest.is_empty(), "all bytes should be consumed for {bytes:02x?}");
328
329			// Skip the non-minimal encoding (0x8025 for 37); we only emit the minimal one.
330			if bytes.len() == 1 || *expected != 37 {
331				let encoded = encode(*expected, LEADING_ONES).unwrap();
332				assert_eq!(&encoded, bytes, "encode mismatch for value {expected}");
333			}
334		}
335	}
336
337	#[test]
338	fn leading_ones_boundaries_round_trip() {
339		let cases = [
340			((1u64 << 7) - 1, 1usize),
341			(1u64 << 7, 2usize),
342			((1u64 << 14) - 1, 2usize),
343			(1u64 << 14, 3usize),
344			((1u64 << 56) - 1, 8usize),
345			(1u64 << 56, 9usize),
346		];
347
348		for (value, expected_len) in cases {
349			let encoded = encode(value, LEADING_ONES).unwrap();
350			assert_eq!(
351				encoded.len(),
352				expected_len,
353				"unexpected encoded length for value {value}"
354			);
355
356			let (decoded, _) = read(&encoded, LEADING_ONES).expect("leading-ones decode should succeed");
357			assert_eq!(decoded, value, "round-trip mismatch for value {value}");
358		}
359	}
360
361	/// Every length class of both forms survives a round trip, including the boundaries
362	/// of each class.
363	#[test]
364	fn every_length_round_trips() {
365		for bits in 0..64 {
366			for value in [1u64 << bits, (1u64 << bits) - 1, (1u64 << bits) + 1] {
367				for form in [Form::Quic, LEADING_ONES] {
368					let Ok(encoded) = encode(value, form) else {
369						assert_eq!(form, Form::Quic);
370						assert!(value > MAX_QUIC);
371						continue;
372					};
373					let (decoded, rest) = read(&encoded, form).unwrap();
374					assert_eq!((decoded, rest), (value, &[][..]), "{form:?} {value}");
375				}
376			}
377		}
378	}
379
380	/// The QUIC form stops at 2^62 - 1 and refuses anything past it rather than
381	/// truncating, while the leading-ones form carries the whole u64.
382	#[test]
383	fn quic_refuses_past_62_bits() {
384		assert_eq!(encode(MAX_QUIC, Form::Quic).unwrap(), [0xff; 8]);
385
386		for value in [1u64 << 62, u64::MAX] {
387			assert_eq!(encode(value, Form::Quic), Err(BoundsExceeded));
388			assert!(matches!(
389				encode_quic(value, &mut Vec::new()),
390				Err(EncodeError::BoundsExceeded)
391			));
392		}
393
394		for value in [MAX_QUIC, 1u64 << 62, u64::MAX] {
395			let encoded = encode(value, LEADING_ONES).unwrap();
396			assert_eq!(encoded.len(), 9);
397			assert_eq!(read(&encoded, LEADING_ONES).unwrap().0, value);
398		}
399	}
400
401	#[test]
402	fn zigzag_roundtrip_small() {
403		for n in [-3i64, -2, -1, 0, 1, 2, 3, 100, -100] {
404			assert_eq!(unzigzag(zigzag(n)), n, "roundtrip failed for {}", n);
405		}
406	}
407
408	#[test]
409	fn zigzag_small_values_compact() {
410		// First few values should fit in 1 byte (varint range 0..=63 = top-2-bits tag 00).
411		assert_eq!([0, -1, 1, -2, 2].map(zigzag), [0, 1, 2, 3, 4]);
412	}
413
414	/// Zigzag covers the whole i64 range; only the QUIC form bounds what goes on the wire.
415	#[test]
416	fn zigzag_roundtrip_boundary() {
417		let mid = (1i64 << 30) + 17;
418
419		for n in [i64::MAX, i64::MIN, (1i64 << 61) - 1, -(1i64 << 61), mid, -mid] {
420			assert_eq!(unzigzag(zigzag(n)), n);
421		}
422
423		assert_eq!(zigzag(i64::MIN), u64::MAX);
424		assert!(zigzag(1i64 << 61) > MAX_QUIC);
425		assert_eq!(zigzag(-(1i64 << 61)), MAX_QUIC);
426	}
427
428	#[test]
429	fn zigzag_quic_varint_roundtrip() {
430		// Encode a zigzag value through the QUIC varint wire format.
431		for n in [-5000i64, 0, 100, -1, 1_000_000, -1_000_000] {
432			let bytes = encode(zigzag(n), Form::Quic).unwrap();
433			let (decoded, _) = read(&bytes, Form::Quic).unwrap();
434			assert_eq!(unzigzag(decoded), n);
435		}
436	}
437
438	#[test]
439	fn accepts_7_byte_varint() {
440		// Value 0x1234_5678_9ABC encoded as 7-byte leading-ones (1111110x | hi, +6 bytes).
441		let value: u64 = 0x1234_5678_9ABC;
442		let mut bytes = Vec::new();
443		// Prefix byte: 1111110_0 + (value >> 48) bit. Top 1 bit of 49 = bit 48.
444		// value fits in 49 bits, so the 0x01 LSB of prefix encodes bit 48 of value.
445		let hi_bit = ((value >> 48) & 0x01) as u8;
446		bytes.push(0xFC | hi_bit);
447		for shift in (0..48).step_by(8).rev() {
448			bytes.push(((value >> shift) & 0xFF) as u8);
449		}
450		let (decoded, _) = read(&bytes, LEADING_ONES).unwrap();
451		assert_eq!(decoded, value);
452	}
453
454	fn lite(value: u64, version: lite::Version) -> Vec<u8> {
455		encode(value, version.into()).unwrap()
456	}
457
458	/// Lite-01 through lite-06 keep the QUIC form byte for byte.
459	#[test]
460	fn lite06_keeps_quic_varints() {
461		for version in [lite::Version::Lite01, lite::Version::Lite05, lite::Version::Lite06] {
462			assert_eq!(lite(63, version), [0x3F]);
463			assert_eq!(lite(64, version), [0x40, 0x40]);
464			assert_eq!(lite(16_384, version), [0x80, 0x00, 0x40, 0x00]);
465		}
466	}
467
468	/// Lite-07 switches to leading-ones, including at every length boundary and past 62 bits.
469	#[test]
470	fn lite07_uses_leading_ones() {
471		let version = lite::Version::Lite07;
472		let cases: &[(u64, &[u8])] = &[
473			(0, &[0x00]),
474			(127, &[0x7F]),
475			(128, &[0x80, 0x80]),
476			((1 << 14) - 1, &[0xBF, 0xFF]),
477			(1 << 14, &[0xC0, 0x40, 0x00]),
478			((1 << 21) - 1, &[0xDF, 0xFF, 0xFF]),
479			(1 << 21, &[0xE0, 0x20, 0x00, 0x00]),
480			((1 << 56) - 1, &[0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]),
481			(1 << 56, &[0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
482			(MAX_QUIC, &[0xFF, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]),
483			(u64::MAX, &[0xFF; 9]),
484		];
485		for (value, wire) in cases {
486			assert_eq!(lite(*value, version), *wire, "encode {value}");
487			assert_eq!(read(wire, version.into()).unwrap(), (*value, &[][..]));
488		}
489	}
490
491	/// The 7-byte `1111110x` form is valid on lite-07, as on draft-18+.
492	#[test]
493	fn lite07_accepts_7_byte_varint() {
494		let wire = [0xFD, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD];
495		assert_eq!(read(&wire, lite::Version::Lite07.into()).unwrap().0, 0x1_2345_6789_ABCD);
496	}
497
498	/// The Buf-based helpers other crates use read and write the same bytes, even when
499	/// the varint straddles two chunks.
500	#[test]
501	fn quic_helpers_match_the_codec() {
502		use bytes::Buf;
503
504		let value = 0x1234_5678u64;
505		let mut out = Vec::new();
506		encode_quic(value, &mut out).unwrap();
507		assert_eq!(out, encode(value, Form::Quic).unwrap());
508
509		let mut split = (&out[..2]).chain(&out[2..]);
510		assert_eq!(decode_quic(&mut split).unwrap(), value);
511		assert!(!split.has_remaining());
512	}
513}