A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
//! Writing bits the way JPEG XL wants them: least significant bit first.
#[derive(Default, Clone)]
pub struct BitWriter {
buf: Vec<u8>,
acc: u64,
nbits: u32,
}
impl BitWriter {
pub fn new() -> Self {
Self::default()
}
/// Puts the low `n` bits of `v` (n up to 32).
#[inline]
pub fn put(&mut self, v: u64, n: u32) {
debug_assert!(n <= 32 && (n == 0 || v >> n == 0), "value {v} does not fit {n} bits");
self.acc |= v << self.nbits;
self.nbits += n;
if self.nbits >= 32 {
self.buf.extend_from_slice(&(self.acc as u32).to_le_bytes());
self.acc >>= 32;
self.nbits -= 32;
}
}
/// Number of bits written so far.
pub fn bit_len(&self) -> usize {
self.buf.len() * 8 + self.nbits as usize
}
/// Pads with zero bits up to the next byte.
pub fn align(&mut self) {
let pad = (8 - self.nbits % 8) % 8;
self.put(0, pad);
}
/// The bytes written; the last byte is padded with zeros.
pub fn finish(mut self) -> Vec<u8> {
self.align();
while self.nbits > 0 {
self.buf.push(self.acc as u8);
self.acc >>= 8;
self.nbits = self.nbits.saturating_sub(8);
}
self.buf
}
/// Another writer's bits, appended bit by bit (neither needs to be aligned).
pub fn append(&mut self, other: &BitWriter) {
for &b in &other.buf {
self.put(b as u64, 8);
}
let mut acc = other.acc;
let mut n = other.nbits;
while n > 0 {
let k = n.min(16);
self.put(acc & ((1 << k) - 1), k);
acc >>= k;
n -= k;
}
}
}
/// One of the four forms of the headers' "u32" integers; 2 bits say which one is used.
pub enum U32Form {
Bits(u32),
BitsOffset(u32, u32),
}
/// Writes `v` with the first of the four forms that can hold it.
pub fn put_u32(bw: &mut BitWriter, v: u32, forms: [U32Form; 4]) {
for (sel, f) in forms.iter().enumerate() {
match *f {
U32Form::Bits(n) if n >= 32 || v >> n == 0 => {
bw.put(sel as u64, 2);
bw.put(v as u64, n);
return;
}
U32Form::BitsOffset(n, off) if v >= off && (n >= 32 || (v - off) >> n == 0) => {
bw.put(sel as u64, 2);
bw.put((v - off) as u64, n);
return;
}
_ => {}
}
}
panic!("u32 {v} fits none of the forms");
}
/// The 16-bit float (1 sign, 5 exponent, 10 mantissa bits) nearest to `v`; zero and the normal range only.
pub fn f16_bits(v: f32) -> u16 {
if v == 0.0 {
return 0;
}
let sign = if v < 0.0 { 0x8000u16 } else { 0 };
let b = v.abs().to_bits();
let exp = ((b >> 23) & 0xff) as i32 - 127 + 15;
debug_assert!((1..31).contains(&exp), "{v} is out of the 16-bit float's normal range");
let man = b & 0x7f_ffff;
// round the 23-bit mantissa to 10 bits; a carry moves into the exponent by itself
let rounded = ((exp as u32) << 10) + ((man + 0x1000) >> 13);
sign | rounded as u16
}
/// What a 16-bit float stands for (zero and the normal range).
pub fn f16_value(bits: u16) -> f32 {
let exp = ((bits >> 10) & 0x1f) as i32;
if exp == 0 {
return 0.0;
}
let man = (bits & 0x3ff) as f32;
let v = (1.0 + man / 1024.0) * 2f32.powi(exp - 15);
if bits & 0x8000 != 0 { -v } else { v }
}
pub fn ceil_log2(v: usize) -> u32 {
if v <= 1 { 0 } else { usize::BITS - (v - 1).leading_zeros() }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bits_come_out_least_significant_first() {
let mut w = BitWriter::new();
w.put(0b101, 3);
w.put(0xff, 8);
w.put(1, 1);
w.align();
assert_eq!(w.finish(), vec![0b1111_1101, 0b0000_1111]);
}
#[test]
fn appending_keeps_the_bits() {
let mut a = BitWriter::new();
a.put(0b11, 2);
let mut b = BitWriter::new();
for i in 0..70 {
b.put(i % 2, 1);
}
a.append(&b);
let mut direct = BitWriter::new();
direct.put(0b11, 2);
for i in 0..70 {
direct.put(i % 2, 1);
}
assert_eq!(a.finish(), direct.finish());
}
#[test]
fn sixteen_bit_floats_round_trip() {
for v in [0.0f32, 1.0, -1.0, 0.25, 3150.0 / 64.0, -0.4, 84.0, 0.0078125] {
let back = f16_value(f16_bits(v));
assert!((back - v).abs() <= v.abs() * 1e-3, "{v} came back as {back}");
}
}
#[test]
fn u32_forms_pick_the_first_that_fits() {
let mut w = BitWriter::new();
put_u32(&mut w, 5, [U32Form::Bits(2), U32Form::BitsOffset(4, 4), U32Form::Bits(8), U32Form::Bits(30)]);
// selector 1 (the first form is too small), then 5 - 4 in 4 bits
assert_eq!(w.finish(), vec![0b0000_0101]);
}
}