JFLib

game/src/net/bits.rs#

Source: lib/game/src/net/bits.rs

bits -- a bit stream for the netcode's messages: values of any width up to 32 bits, little-endian
bit order (the first bit written is bit 0 of byte 0), and two variable-length codes

  BitWriter   bits(value, n), bool, uvar (counts, gaps: 0 + 4 | 10 + 8 | 110 + 16 | 111 + 32 bits),
              svar (field deltas, zigzag: 0 + 6 | 10 + 10 | 110 + 16 | 111 + 32 bits), u8 / u16 / u32,
              bit_len, finish
  BitReader   the same reads; past the end or on a value out of range it returns 0 and sets a sticky
              error flag (ok() false): bytes from the network never panic, the caller checks once

The codes are sized for a game's snapshots: an id gap is mostly 0 (5 bits), a position delta of a
walking figure between two snapshots (a few hundred steps of 1/1024 m) takes 12 bits, an unchanged
field is not written at all (the field mask of the snapshot says which are).
  • struct BitWriter writes bits into bytes (see the module header)

impl BitWriter

  • fn new() -> BitWriter an empty stream

  • fn with_prefix(prefix: &[u8]) -> BitWriter an empty stream after prefix (whole bytes, such as a message type)

  • fn bits(&mut self, v: u32, n: u32) the low n bits of v (n at most 32)

  • fn bool(&mut self, b: bool) one bit

  • fn u8(&mut self, v: u8) 8 bits

  • fn u16(&mut self, v: u16) 16 bits

  • fn u32(&mut self, v: u32) 32 bits

  • fn uvar(&mut self, v: u32) an unsigned number in the code for counts and gaps: 0 + 4 bits, 10 + 8, 110 + 16, 111 + 32

  • fn svar(&mut self, d: i32) a signed difference in the code for field deltas (zigzag: 0, -1, 1, -2, ...): 0 + 6 bits (-32 ..= 31), 10 + 10 (-512 ..= 511), 110 + 16, 111 + 32

  • fn bit_len(&self) -> usize bits written so far (prefix included)

  • fn finish(mut self) -> Vec<u8> the bytes, the last one filled up with zero bits

  • fn uvar_bits(v: u32) -> usize the bits uvar takes for v

  • fn svar_bits(d: i32) -> usize the bits svar takes for d

  • fn zigzag(d: i32) -> u32 0, -1, 1, -2, 2 ... -> 0, 1, 2, 3, 4 ...

  • fn unzigzag(z: u32) -> i32 the inverse of zigzag

  • struct BitReader<'a> reads bits from bytes (see the module header)

impl<'a> BitReader<'a>

  • fn new(buf: &'a [u8]) -> BitReader<'a> a stream over buf
  • fn bits(&mut self, n: u32) -> u32 n bits (at most 32); 0 and the error flag past the end
  • fn bool(&mut self) -> bool one bit
  • fn u8(&mut self) -> u8 8 bits
  • fn u16(&mut self) -> u16 16 bits
  • fn u32(&mut self) -> u32 32 bits
  • fn uvar(&mut self) -> u32 BitWriter::uvar
  • fn svar(&mut self) -> i32 BitWriter::svar
  • fn fail(&mut self) mark the stream as bad (a value the caller found out of range)
  • fn ok(&self) -> bool no read went past the end and nothing was marked bad
  • fn bytes_left(&self) -> usize whole bytes not yet touched (the bits of a started byte do not count)

Source: docs/API.md in the JFLib repository.