Skip to main content

webp/utils/
bit_reader_utils.rs

1// libwebp v1.6.0, src/utils/bit_reader_utils.c:
2//
3// Copyright 2010 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12// Boolean decoder non-inlined methods
13//
14// Author: Skal (pascal.massimino@gmail.com)
15
16// libwebp v1.6.0, src/utils/bit_reader_utils.h:
17//
18// Copyright 2010 Google Inc. All Rights Reserved.
19//
20// Use of this source code is governed by a BSD-style license
21// that can be found in the COPYING file in the root of the source
22// tree. An additional intellectual property rights grant can be found
23// in the file PATENTS. All contributing project authors may
24// be found in the AUTHORS file in the root of the source tree.
25// -----------------------------------------------------------------------------
26//
27// Boolean decoder
28//
29// Author: Skal (pascal.massimino@gmail.com)
30//         Vikas Arora (vikaas.arora@gmail.com)
31
32//! Translation of `src/utils/bit_reader_utils.c` and `src/utils/bit_reader_utils.h` from libwebp v1.6.0.
33//!
34//! Work package: WP2 (bit I/O).
35//!
36//! The readers hold no reference to their input (ADR 0003, as amended on
37//! 2026-11-06). `VP8BitReader` and `VP8LBitReader` store state and positions:
38//! every C pointer becomes a `usize` position into the input that the owner holds,
39//! and the owner passes that input to each function that reads it. A C `buf` that
40//! may be `NULL` becomes the flag `VP8BitReader::has_buf`.
41//!
42//! `VP8RemapBitReader` adds a signed offset to the three positions of a reader
43//! with an input, as C adds it to the pointers. The owner calls it when the same
44//! bytes have moved by that many indexes of its input.
45//!
46//! The bit-trace tool (`BITTRACE`) is off in the reference configuration, so the
47//! labels of the reader functions are removed, as the header's macros do.
48//!
49//! # Deviations from upstream
50//!
51//! Changes of representation that the ADRs allow, or behavior that the Rust
52//! side cannot reproduce exactly. Each records the reason.
53//!
54//! 1. **Public fields.** The fields of the four structs (`VP8BitReader`,
55//!    `VP8LBitReader`, `VP8BitWriter` and `VP8LBitWriter`) are `pub`, as the C
56//!    structs are public in their headers, so that the tests can read the
57//!    state. The C field `buf_end` is stored as `VP8BitReader::buf_end`,
58//!    because it no longer comes from a slice length; `VP8LBitReader::len` is
59//!    stored for the same reason.
60//! 2. **Remap by an index delta.** `VP8RemapBitReader` adds a signed offset to
61//!    the positions. The owner passes the index delta of its bytes, not the
62//!    pointer difference of two allocations, which C's caller computes. Both
63//!    sides of the remap test move the input inside one allocation, so that the
64//!    C pointer difference and the index delta are the same number. The test
65//!    does not move the input to a second allocation, because a pointer
66//!    difference between two allocations contains the distance of their bases,
67//!    which an index delta does not.
68//!
69//! # Excluded undefined behavior
70//!
71//! Inputs that are undefined behavior (or assertion failures) in C and are
72//! therefore excluded from the oracle comparison (PORTING rule 8). The
73//! asan-ubsan oracle found these, and the generators keep the tests away from
74//! them:
75//!
76//! 1. `VP8LBitReaderSetBuffer` with a length shorter than the reader's position
77//!    is a parameter error (the comment of the function says so), and
78//!    upstream's own debug assertion in `VP8LIsEndOfStream` fires there. The
79//!    Rust debug assertion mirrors it. The tests substitute `fill` for such a
80//!    call.
81//! 2. `VP8LDoFillBitWindow` requires `bit_pos >= VP8L_WBITS` (debug assertion).
82//!    The tests call it only there.
83//! 3. `VP8LReadBits` with a negative count indexes `kBitMask` out of range. The
84//!    Rust index panics in every profile, after the debug assertion; C reads
85//!    outside the table. No test issues it.
86//! 4. `VP8RemapBitReader` with a position that would become negative is outside
87//!    the contract of the owner (the pointer would leave its allocation). The
88//!    Rust version panics; no test issues it.
89//!
90//! # Checks not applicable
91//!
92//! These checks do not apply, or cannot be made, with the reason:
93//!
94//! 1. Layout of `repr(C)` mirrors. None of the four structs is exported by a
95//!    public header; the C declarations are internal to `bit_reader_utils.h`
96//!    and `bit_writer_utils.h`. ADR 0004 gives no ABI mirror to them.
97//! 2. The other `BITS` values of the header (8, 16, 32 and 48) are selected by
98//!    no target that upstream names, so they are not translated. `bit_t` and
99//!    `lbit_t` follow the two selected values.
100
101use crate::utils::bit_reader_inl_utils::{LBIT_BYTES, vp8_get_bit, vp8_load_new_bytes};
102use crate::utils::endian_inl_utils::h_to_le32;
103use crate::utils::utils::webp_mem_to_uint32;
104
105// upstream: src/utils/bit_reader_utils.h BITS
106/// Number of bits that the boolean decoder loads at once. Upstream chooses 56 on
107/// x86-64, `AArch64` and WebAssembly, and 24 on every other target; this constant
108/// makes the same choice for the Rust target architecture.
109pub const BITS: i32 = if cfg!(any(
110    target_arch = "x86_64",
111    target_arch = "aarch64",
112    target_arch = "wasm32",
113    target_arch = "wasm64"
114)) {
115    56
116} else {
117    24
118};
119
120// upstream: src/utils/bit_reader_utils.h bit_t
121/// Natural register type of the boolean decoder's `value`: 64 bits when
122/// `BITS > 24`, and 32 bits otherwise.
123#[cfg(any(
124    target_arch = "x86_64",
125    target_arch = "aarch64",
126    target_arch = "wasm32",
127    target_arch = "wasm64"
128))]
129#[expect(non_camel_case_types, reason = "C type name")]
130pub type bit_t = u64;
131
132// upstream: src/utils/bit_reader_utils.h bit_t
133/// Natural register type of the boolean decoder's `value`: 64 bits when
134/// `BITS > 24`, and 32 bits otherwise.
135#[cfg(not(any(
136    target_arch = "x86_64",
137    target_arch = "aarch64",
138    target_arch = "wasm32",
139    target_arch = "wasm64"
140)))]
141#[expect(non_camel_case_types, reason = "C type name")]
142pub type bit_t = u32;
143
144// upstream: src/utils/bit_reader_utils.h range_t
145/// Register for `range`, which holds eight significant bits.
146#[expect(non_camel_case_types, reason = "C type name")]
147pub type range_t = u32;
148
149// upstream: src/utils/bit_reader_utils.h VP8BitReader
150/// The boolean decoder: its value window, its range, and the positions of its
151/// input. It holds no reference to the input; see the module documentation.
152#[derive(Debug, Default)]
153pub struct VP8BitReader {
154    /// Current value; keeps `BITS + 8` bits.
155    pub value: bit_t,
156    /// Current range minus one, in `[127, 254]`.
157    pub range: range_t,
158    /// Number of valid bits left.
159    pub bits: i32,
160    /// Set once the reader has an input. This is the C test `buf != NULL`, which
161    /// only a reader that was set up passes.
162    pub has_buf: bool,
163    /// Index in the input of the next byte to be read (C `buf`).
164    pub buf: usize,
165    /// Index in the input where the input ends (C `buf_end`).
166    pub buf_end: usize,
167    /// Index in the input of the limit of the packed reads (C `buf_max`).
168    pub buf_max: usize,
169    /// Set when the input is exhausted.
170    pub eof: bool,
171}
172
173// upstream: src/utils/bit_reader_utils.c kVP8Log2Range
174/// `kVP8Log2Range[range]` is the number of renormalization shifts for `range`.
175pub const VP8_LOG2_RANGE: [u8; 128] = [
176    7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, //
177    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, //
178    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, //
179    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, //
180    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //
181    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //
182    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //
183    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //
184    0,
185];
186
187// upstream: src/utils/bit_reader_utils.c kVP8NewRange
188/// `kVP8NewRange[range]` is the renormalized range: `((range + 1) << shift) - 1`.
189pub const VP8_NEW_RANGE: [u8; 128] = [
190    127, 127, 191, 127, 159, 191, 223, 127, 143, 159, 175, 191, 207, 223, 239, 127, //
191    135, 143, 151, 159, 167, 175, 183, 191, 199, 207, 215, 223, 231, 239, 247, 127, //
192    131, 135, 139, 143, 147, 151, 155, 159, 163, 167, 171, 175, 179, 183, 187, 191, //
193    195, 199, 203, 207, 211, 215, 219, 223, 227, 231, 235, 239, 243, 247, 251, 127, //
194    129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, //
195    161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, //
196    193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, //
197    225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 127,
198];
199
200// upstream: src/utils/bit_reader_utils.c VP8BitReaderSetBuffer
201/// Gives the reader an input of `size` bytes, which the owner passes from now on,
202/// and rewinds the reader to the first byte. The value, the range and the
203/// end-of-input flag are not changed.
204pub fn vp8_bit_reader_set_buffer(br: &mut VP8BitReader, size: usize) {
205    br.has_buf = true;
206    br.buf = 0;
207    br.buf_end = size;
208    br.buf_max = if size >= LBIT_BYTES {
209        size + 1 - LBIT_BYTES
210    } else {
211        0
212    };
213}
214
215// upstream: src/utils/bit_reader_utils.c VP8InitBitReader
216/// Initializes the boolean decoder over `data`, which is the whole input of the
217/// reader, and loads its first bytes.
218pub fn vp8_init_bit_reader(br: &mut VP8BitReader, data: &[u8]) {
219    debug_assert!(data.len() < (1 << 31)); // limit ensured by format and upstream checks
220    br.range = 255 - 1;
221    br.value = 0;
222    br.bits = -8; // to load the very first 8bits
223    br.eof = false;
224    vp8_bit_reader_set_buffer(br, data.len());
225    vp8_load_new_bytes(br, data);
226}
227
228// upstream: src/utils/bit_reader_utils.c VP8RemapBitReader
229/// Adds `offset` to the positions of a reader that has an input, as C adds it to
230/// the pointers. The owner calls it when the same bytes have moved by `offset`
231/// indexes of its input. A reader without an input (C `buf == NULL`) is left as
232/// it is.
233///
234/// # Panics
235///
236/// Panics when a position would become negative, which means that `offset` does
237/// not describe a move of the input's bytes.
238pub fn vp8_remap_bit_reader(br: &mut VP8BitReader, offset: isize) {
239    if br.has_buf {
240        br.buf = br
241            .buf
242            .checked_add_signed(offset)
243            .expect("the remapped position stays in the input");
244        br.buf_end = br
245            .buf_end
246            .checked_add_signed(offset)
247            .expect("the remapped end stays in the input");
248        br.buf_max = br
249            .buf_max
250            .checked_add_signed(offset)
251            .expect("the remapped limit stays in the input");
252    }
253}
254
255// upstream: src/utils/bit_reader_utils.c VP8LoadFinalBytes
256/// Loads one byte at a time near the end of the input. Once the input is
257/// exhausted, the first call sets `eof` and shifts in zeros, and later calls
258/// only keep the state.
259pub fn vp8_load_final_bytes(br: &mut VP8BitReader, data: &[u8]) {
260    // Only read 8bits at a time
261    if br.buf < br.buf_end {
262        br.bits += 8;
263        br.value = bit_t::from(data[br.buf]) | (br.value << 8);
264        br.buf += 1;
265    } else if !br.eof {
266        br.value <<= 8;
267        br.bits += 8;
268        br.eof = true;
269    } else {
270        br.bits = 0; // This is to avoid undefined behaviour with shifts.
271    }
272}
273
274// upstream: src/utils/bit_reader_utils.c VP8GetValue
275/// Reads `num_bits` bits, most significant first, each with probability one
276/// half.
277#[expect(clippy::cast_sign_loss, reason = "each bit is 0 or 1")]
278pub fn vp8_get_value(br: &mut VP8BitReader, data: &[u8], num_bits: i32) -> u32 {
279    let mut v: u32 = 0;
280    let mut bits = num_bits;
281    while bits > 0 {
282        bits -= 1;
283        v |= (vp8_get_bit(br, data, 0x80) as u32) << bits;
284    }
285    v
286}
287
288// upstream: src/utils/bit_reader_utils.h VP8Get
289/// Reads one bit with probability one half. The header's macro of the same name
290/// expands to `VP8GetValue(br, 1)`.
291pub fn vp8_get(br: &mut VP8BitReader, data: &[u8]) -> u32 {
292    vp8_get_value(br, data, 1)
293}
294
295// upstream: src/utils/bit_reader_utils.c VP8GetSignedValue
296/// Reads `num_bits` bits, then a sign bit that negates the value when set.
297#[expect(clippy::cast_possible_wrap, reason = "C converts the uint32_t to int")]
298pub fn vp8_get_signed_value(br: &mut VP8BitReader, data: &[u8], num_bits: i32) -> i32 {
299    let value = vp8_get_value(br, data, num_bits) as i32;
300    if vp8_get(br, data) != 0 {
301        -value
302    } else {
303        value
304    }
305}
306
307// upstream: src/utils/bit_reader_utils.h VP8L_LBITS
308/// Number of bits prefetched by the lossless reader: the bit size of `vp8l_val_t`.
309pub const VP8L_LBITS: i32 = 64;
310
311// upstream: src/utils/bit_reader_utils.h VP8L_WBITS
312/// Minimum number of bits that `VP8LFillBitWindow` makes available.
313pub const VP8L_WBITS: i32 = 32;
314
315// upstream: src/utils/bit_reader_utils.h VP8L_MAX_NUM_BIT_READ
316/// Largest number of bits one `VP8LReadBits` call may read.
317pub const VP8L_MAX_NUM_BIT_READ: i32 = 24;
318
319// upstream: src/utils/bit_reader_utils.h vp8l_val_t
320/// The prefetched bits of the lossless reader: the right register is 64 bits.
321#[expect(non_camel_case_types, reason = "C type name")]
322pub type vp8l_val_t = u64;
323
324// upstream: src/utils/bit_reader_utils.c VP8L_LOG8_WBITS
325/// Number of bytes needed to store `VP8L_WBITS` bits.
326const VP8L_LOG8_WBITS: usize = 4;
327
328// upstream: src/utils/bit_reader_utils.c VP8L_USE_FAST_LOAD
329/// Whether `VP8LDoFillBitWindow` reads four bytes at once. Upstream defines the
330/// macro for ARM, `AArch64`, x86, x86-64 and WebAssembly.
331pub const VP8L_USE_FAST_LOAD: bool = cfg!(any(
332    target_arch = "arm",
333    target_arch = "aarch64",
334    target_arch = "x86",
335    target_arch = "x86_64",
336    target_arch = "wasm32",
337    target_arch = "wasm64",
338));
339
340// upstream: src/utils/bit_reader_utils.c kBitMask
341/// `kBitMask[n]` is the mask of the low `n` bits.
342const BIT_MASK: [u32; 25] = [
343    0,
344    0x0000_0001,
345    0x0000_0003,
346    0x0000_0007,
347    0x0000_000f,
348    0x0000_001f,
349    0x0000_003f,
350    0x0000_007f,
351    0x0000_00ff,
352    0x0000_01ff,
353    0x0000_03ff,
354    0x0000_07ff,
355    0x0000_0fff,
356    0x0000_1fff,
357    0x0000_3fff,
358    0x0000_7fff,
359    0x0000_ffff,
360    0x0001_ffff,
361    0x0003_ffff,
362    0x0007_ffff,
363    0x000f_ffff,
364    0x001f_ffff,
365    0x003f_ffff,
366    0x007f_ffff,
367    0x00ff_ffff,
368];
369
370// upstream: src/utils/bit_reader_utils.h VP8LBitReader
371/// The lossless bit reader: a window of prefetched bits and the positions of its
372/// input. It holds no reference to the input; see the module documentation.
373#[derive(Debug, Default)]
374pub struct VP8LBitReader {
375    /// Prefetched bits.
376    pub val: vp8l_val_t,
377    /// Length of the input (C `len`).
378    pub len: usize,
379    /// Byte position in the input of the next byte to be loaded.
380    pub pos: usize,
381    /// Current bit-reading position in `val`.
382    pub bit_pos: i32,
383    /// Set when a bit was read past the end of the input.
384    pub eos: bool,
385}
386
387// upstream: src/utils/bit_reader_utils.c VP8LInitBitReader
388/// Initializes the lossless reader over `data`, which is the whole input of the
389/// reader, and prefetches its first eight bytes.
390pub fn vp8l_init_bit_reader(br: &mut VP8LBitReader, data: &[u8]) {
391    debug_assert!(data.len() < 0xffff_fff8); // can't happen with a RIFF chunk.
392    let length = data.len().min(size_of::<vp8l_val_t>());
393    let mut value: vp8l_val_t = 0;
394    for (i, &byte) in data[..length].iter().enumerate() {
395        value |= vp8l_val_t::from(byte) << (8 * i);
396    }
397    br.len = data.len();
398    br.val = value;
399    br.pos = length;
400    br.bit_pos = 0;
401    br.eos = false;
402}
403
404// upstream: src/utils/bit_reader_utils.c VP8LBitReaderSetBuffer
405/// Sets a new input length, which the owner passes from now on. The position and
406/// the prefetched bits are kept, and the end-of-stream flag is recomputed, so a
407/// position past the new end sets `eos`.
408pub fn vp8l_bit_reader_set_buffer(br: &mut VP8LBitReader, len: usize) {
409    debug_assert!(len < 0xffff_fff8); // can't happen with a RIFF chunk.
410    br.len = len;
411    // 'pos' > 'len' should be considered a param error.
412    br.eos = (br.pos > br.len) || vp8l_is_end_of_stream(br);
413}
414
415// upstream: src/utils/bit_reader_utils.c VP8LSetEndOfStream
416/// Sets `eos` and clears the position, to avoid undefined shifts.
417fn vp8l_set_end_of_stream(br: &mut VP8LBitReader) {
418    br.eos = true;
419    br.bit_pos = 0; // To avoid undefined behaviour with shifts.
420}
421
422// upstream: src/utils/bit_reader_utils.c ShiftBytes
423/// Reloads up to `VP8L_LBITS` bits byte by byte, while the input lasts.
424fn shift_bytes(br: &mut VP8LBitReader, data: &[u8]) {
425    while br.bit_pos >= 8 && br.pos < br.len {
426        br.val >>= 8;
427        br.val |= vp8l_val_t::from(data[br.pos]) << (VP8L_LBITS - 8);
428        br.pos += 1;
429        br.bit_pos -= 8;
430    }
431    if vp8l_is_end_of_stream(br) {
432        vp8l_set_end_of_stream(br);
433    }
434}
435
436// upstream: src/utils/bit_reader_utils.c VP8LReadBits
437/// Reads `n_bits` bits. Reads with more than `VP8L_MAX_NUM_BIT_READ` bits, or
438/// after the end of the stream, return zero and set `eos`.
439///
440/// # Panics
441///
442/// Debug builds panic when `n_bits` is negative, which C leaves undefined.
443#[expect(
444    clippy::cast_sign_loss,
445    reason = "n_bits is checked not to be negative"
446)]
447pub fn vp8l_read_bits(br: &mut VP8LBitReader, data: &[u8], n_bits: i32) -> u32 {
448    debug_assert!(n_bits >= 0);
449    // Flag an error if end_of_stream or n_bits is more than allowed limit.
450    if !br.eos && n_bits <= VP8L_MAX_NUM_BIT_READ {
451        let val = vp8l_prefetch_bits(br) & BIT_MASK[n_bits as usize];
452        let new_bits = br.bit_pos + n_bits;
453        br.bit_pos = new_bits;
454        shift_bytes(br, data);
455        val
456    } else {
457        vp8l_set_end_of_stream(br);
458        0
459    }
460}
461
462// upstream: src/utils/bit_reader_utils.h VP8LPrefetchBits
463/// Returns the prefetched bits, so that they can be looked up.
464#[must_use]
465#[expect(clippy::cast_possible_truncation, reason = "C keeps the low 32 bits")]
466pub fn vp8l_prefetch_bits(br: &VP8LBitReader) -> u32 {
467    (br.val >> (br.bit_pos & (VP8L_LBITS - 1))) as u32
468}
469
470// upstream: src/utils/bit_reader_utils.h VP8LIsEndOfStream
471/// Reports whether a bit was read past the end of the input. Does not set `eos`.
472#[must_use]
473pub fn vp8l_is_end_of_stream(br: &VP8LBitReader) -> bool {
474    debug_assert!(br.pos <= br.len);
475    br.eos || ((br.pos == br.len) && (br.bit_pos > VP8L_LBITS))
476}
477
478// upstream: src/utils/bit_reader_utils.h VP8LSetBitPos
479/// Jumps to the bit position `val` of the prefetched bits. Does not set `eos`;
480/// use with care.
481pub fn vp8l_set_bit_pos(br: &mut VP8LBitReader, val: i32) {
482    br.bit_pos = val;
483}
484
485// upstream: src/utils/bit_reader_utils.c VP8LDoFillBitWindow
486/// Advances the input by four bytes to make room for the next 32 bits. With
487/// `VP8L_USE_FAST_LOAD` it reads four bytes at once while nine or more remain;
488/// otherwise, and near the end, it shifts in byte by byte.
489///
490/// # Panics
491///
492/// Debug builds panic when `bit_pos` is below `VP8L_WBITS`.
493pub fn vp8l_do_fill_bit_window(br: &mut VP8LBitReader, data: &[u8]) {
494    debug_assert!(br.bit_pos >= VP8L_WBITS);
495    if VP8L_USE_FAST_LOAD && br.pos + size_of::<vp8l_val_t>() < br.len {
496        br.val >>= VP8L_WBITS;
497        br.bit_pos -= VP8L_WBITS;
498        let word = h_to_le32(webp_mem_to_uint32(&data[br.pos..]));
499        br.val |= vp8l_val_t::from(word) << (VP8L_LBITS - VP8L_WBITS);
500        br.pos += VP8L_LOG8_WBITS;
501        return;
502    }
503    shift_bytes(br, data); // Slow path.
504}
505
506// upstream: src/utils/bit_reader_utils.h VP8LFillBitWindow
507/// Makes room for the next 32 bits when fewer than 32 bits are prefetched.
508pub fn vp8l_fill_bit_window(br: &mut VP8LBitReader, data: &[u8]) {
509    if br.bit_pos >= VP8L_WBITS {
510        vp8l_do_fill_bit_window(br, data);
511    }
512}