webp/utils/bit_writer_utils.rs
1// libwebp v1.6.0, src/utils/bit_writer_utils.c:
2//
3// Copyright 2011 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// Bit writing and boolean coder
13//
14// Author: Skal (pascal.massimino@gmail.com)
15// Vikas Arora (vikaas.arora@gmail.com)
16
17// libwebp v1.6.0, src/utils/bit_writer_utils.h:
18//
19// Copyright 2011 Google Inc. All Rights Reserved.
20//
21// Use of this source code is governed by a BSD-style license
22// that can be found in the COPYING file in the root of the source
23// tree. An additional intellectual property rights grant can be found
24// in the file PATENTS. All contributing project authors may
25// be found in the AUTHORS file in the root of the source tree.
26// -----------------------------------------------------------------------------
27//
28// Bit writing and boolean coder
29//
30// Author: Skal (pascal.massimino@gmail.com)
31
32//! Translation of `src/utils/bit_writer_utils.c` and `src/utils/bit_writer_utils.h` from libwebp v1.6.0.
33//!
34//! Work package: WP2 (bit I/O).
35//!
36//! `VP8BitWriter` and `VP8LBitWriter` own their byte buffers. The buffer is a
37//! `Vec<u8>` whose length is the allocated size (C `max_pos`, or `end - buf`), and
38//! `cur` is an offset into it (ADR 0003). `Finish` returns the buffer as a borrow,
39//! and `WipeOut` drops it.
40//!
41//! The `VP8LBitWriter` accumulator and write word depend on the target: upstream
42//! uses 64-bit and 32-bit types on x86-64, and 32-bit and 16-bit types elsewhere.
43//! The constants below make the same choice, so that the internal state matches
44//! the oracle built for the same host. The output bytes are the same for both
45//! choices.
46//!
47//! # Deviations from upstream
48//!
49//! Changes of representation that the ADRs allow, or behavior that the Rust
50//! side cannot reproduce exactly. Each records the reason.
51//!
52//! 1. **Writer buffers.** `VP8BitWriter::buf` and `VP8LBitWriter::buf` are
53//! `Vec<u8>`. The length of the vector is the allocated size (`max_pos`, or
54//! `end - buf`), and `cur` is an offset. Allocations use
55//! `webp_safe_calloc::<u8>(n, 1)`, which applies the size test of
56//! `WebPSafeMalloc(1, n)` with the same decision (`n` and `1` in place of
57//! `1` and `n`), and it zero-fills the buffer, as ADR 0003 requires. C's
58//! `malloc` does not zero-fill.
59//! 2. **Bit values.** `VP8PutBit` and `VP8PutBitUniform` take and return a
60//! `bool`, because the C `int` is used only as a predicate. `VP8GetBit`,
61//! `VP8GetSigned` and `VP8GetBitAlt` (`src/utils/bit_reader_inl_utils.rs`)
62//! return an `i32`, because the decoder uses the bit as a value.
63//! 3. **Errors.** The writers keep `error` as a `bool`. A refused allocation
64//! sets it, and it stays set until `Init` or `WipeOut` clears it, as in C.
65//!
66//! The fields of the writers are `pub` for the reason given in item 1 of
67//! `# Deviations from upstream` in `src/utils/bit_reader_utils.rs`.
68//! `VP8PutSignedBits` takes the magnitude with `unsigned_abs`, which defines
69//! the case of `INT_MIN`; see item 1 of `# Deviations from upstream` in
70//! `src/utils/bit_reader_inl_utils.rs`.
71//!
72//! # Excluded undefined behavior
73//!
74//! Inputs that are undefined behavior (or assertion failures) in C and are
75//! therefore excluded from the oracle comparison (PORTING rule 8). The
76//! asan-ubsan oracle found these, and the generators keep the tests away from
77//! them:
78//!
79//! 1. `VP8LPutBitsInternal` with 32 bits at `used == 0` on the 16-bit path
80//! shifts a `uint32_t` by 32. The Rust `>>=` panics in dev and `checked`
81//! builds. The generator narrows such a call to 31 bits.
82//! 2. Writes after `VP8LBitWriterFinish`, whose cursor may be odd, store a
83//! 16-bit or 32-bit word at an odd address (`*(vp8l_wtype_t*)bw->cur`). The
84//! sequences finish and wipe a writer only at their end.
85//! 3. A write into a writer without a buffer (after a refused `Init`) adds the
86//! cursor offset to a null pointer. The Rust version resizes the empty
87//! vector and writes. The refused-allocation test issues only writes that do
88//! not flush, then a finish.
89//! 4. `VP8LBitWriterReset` to a cursor whose bytes the destination does not
90//! hold: a resize copies only the bytes before the cursor, and C then reads
91//! memory that it never wrote. The tests reset only after a clone of the
92//! same source.
93//! 5. `VP8LBitWriterClone` from a writer without a buffer passes a null pointer
94//! to `memcpy`. No sequence wipes a writer before a clone.
95//!
96//! # Checks not applicable
97//!
98//! These checks do not apply, or cannot be made, with the reason:
99//!
100//! 1. The C assertion `sizeof(vp8l_wtype_t) == 2` of `VP8LPutBitsInternal`
101//! holds on every path that calls the function, the 16-bit accumulator path,
102//! so it is not checked at run time.
103//! 2. The failure branch of `VP8LPutBitsFlushBits` (the cursor returns to the
104//! start, and the error flag is set) is reached only when the growth would
105//! exceed `WEBP_MAX_ALLOCABLE_MEMORY`, which the tests cannot reach without
106//! reserving 16 GiB. The arithmetic is the same as the refused `Init`, which
107//! is tested.
108//! 3. The host-specific writer state. On macOS ARM64 (not x86-64) the lossless
109//! writer uses the 32-bit accumulator and 16-bit write words; x86-64 uses 64
110//! and 32 bits. The tests compare the internal state, so they check the path
111//! of the host they run on. `VP8LPutBitsInternal` is reached only by the
112//! 16-bit words, so the x86-64 CI host exercises the 32-bit path alone, and
113//! the macOS ARM64 host the 16-bit path.
114
115use crate::utils::utils::{check_size_overflow, webp_safe_calloc};
116
117// upstream: src/utils/bit_writer_utils.c MIN_EXTRA_SIZE
118/// The smallest growth step of the `VP8LBitWriter` buffer, in bytes.
119const MIN_EXTRA_SIZE: u64 = 32768;
120
121// upstream: src/utils/bit_writer_utils.h vp8l_atype_t
122/// Bit accumulator of `VP8LBitWriter`: 64 bits on x86-64, 32 bits elsewhere.
123#[cfg(target_arch = "x86_64")]
124#[expect(non_camel_case_types, reason = "C type name")]
125pub type vp8l_atype_t = u64;
126
127// upstream: src/utils/bit_writer_utils.h vp8l_atype_t
128/// Bit accumulator of `VP8LBitWriter`: 64 bits on x86-64, 32 bits elsewhere.
129#[cfg(not(target_arch = "x86_64"))]
130#[expect(non_camel_case_types, reason = "C type name")]
131pub type vp8l_atype_t = u32;
132
133// upstream: src/utils/bit_writer_utils.h vp8l_wtype_t
134/// Write word of `VP8LBitWriter`: 32 bits on x86-64, 16 bits elsewhere.
135#[cfg(target_arch = "x86_64")]
136#[expect(non_camel_case_types, reason = "C type name")]
137pub type vp8l_wtype_t = u32;
138
139// upstream: src/utils/bit_writer_utils.h vp8l_wtype_t
140/// Write word of `VP8LBitWriter`: 32 bits on x86-64, 16 bits elsewhere.
141#[cfg(not(target_arch = "x86_64"))]
142#[expect(non_camel_case_types, reason = "C type name")]
143pub type vp8l_wtype_t = u16;
144
145// upstream: src/utils/bit_writer_utils.h VP8L_WRITER_BYTES
146/// `sizeof(vp8l_wtype_t)`.
147#[cfg(target_arch = "x86_64")]
148pub const VP8L_WRITER_BYTES: usize = 4;
149// upstream: src/utils/bit_writer_utils.h VP8L_WRITER_BYTES
150/// `sizeof(vp8l_wtype_t)`.
151#[cfg(not(target_arch = "x86_64"))]
152pub const VP8L_WRITER_BYTES: usize = 2;
153
154// upstream: src/utils/bit_writer_utils.h VP8L_WRITER_BITS
155/// `8 * sizeof(vp8l_wtype_t)`.
156#[cfg(target_arch = "x86_64")]
157pub const VP8L_WRITER_BITS: i32 = 32;
158// upstream: src/utils/bit_writer_utils.h VP8L_WRITER_BITS
159/// `8 * sizeof(vp8l_wtype_t)`.
160#[cfg(not(target_arch = "x86_64"))]
161pub const VP8L_WRITER_BITS: i32 = 16;
162
163// upstream: src/utils/bit_writer_utils.h VP8L_WRITER_MAX_BITS
164/// `8 * sizeof(vp8l_atype_t)`.
165#[cfg(target_arch = "x86_64")]
166pub const VP8L_WRITER_MAX_BITS: i32 = 64;
167// upstream: src/utils/bit_writer_utils.h VP8L_WRITER_MAX_BITS
168/// `8 * sizeof(vp8l_atype_t)`.
169#[cfg(not(target_arch = "x86_64"))]
170pub const VP8L_WRITER_MAX_BITS: i32 = 32;
171
172const _: () = assert!(size_of::<vp8l_wtype_t>() == VP8L_WRITER_BYTES);
173const _: () = assert!(VP8L_WRITER_MAX_BITS == 2 * VP8L_WRITER_BITS);
174
175// upstream: src/utils/bit_writer_utils.c kNorm
176/// Renormalization shifts: `renorm_sizes[i] = 8 - log2(i)`.
177const NORM: [u8; 128] = [
178 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, //
179 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, //
180 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, //
181 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, //
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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //
185 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, //
186 0,
187];
188
189// upstream: src/utils/bit_writer_utils.c kNewRange
190/// `range = ((range + 1) << kNorm[range]) - 1`.
191const NEW_RANGE: [u8; 128] = [
192 127, 127, 191, 127, 159, 191, 223, 127, 143, 159, 175, 191, 207, 223, 239, 127, //
193 135, 143, 151, 159, 167, 175, 183, 191, 199, 207, 215, 223, 231, 239, 247, 127, //
194 131, 135, 139, 143, 147, 151, 155, 159, 163, 167, 171, 175, 179, 183, 187, 191, //
195 195, 199, 203, 207, 211, 215, 219, 223, 227, 231, 235, 239, 243, 247, 251, 127, //
196 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, //
197 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, //
198 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, //
199 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 127,
200];
201
202// upstream: src/utils/bit_writer_utils.h VP8BitWriter
203/// The boolean encoder of one partition, with the bytes it has written.
204#[derive(Debug, Default)]
205pub struct VP8BitWriter {
206 /// Range minus one.
207 pub range: i32,
208 pub value: i32,
209 /// Number of outstanding `0xff` bytes that wait for a possible carry.
210 pub run: i32,
211 /// Number of pending bits.
212 pub nb_bits: i32,
213 /// The byte buffer. Its length is the allocated size (C `max_pos`).
214 pub buf: Vec<u8>,
215 /// Number of bytes written into `buf`.
216 pub pos: usize,
217 /// Set after a failed memory allocation.
218 pub error: bool,
219}
220
221// upstream: src/utils/bit_writer_utils.c BitWriterResize
222/// Makes room for `extra_size` more bytes, growing the buffer as C does: at
223/// least twice the old size, at least the needed size, and at least 1024 bytes.
224/// The reservation uses the size test of `WebPSafeMalloc(1, new_size)`, which
225/// `webp_safe_calloc::<u8>(new_size, 1)` applies with the same decision.
226fn bit_writer_resize(bw: &mut VP8BitWriter, extra_size: usize) -> bool {
227 let needed_size_64b = bw.pos as u64 + extra_size as u64;
228 let Ok(needed_size) = usize::try_from(needed_size_64b) else {
229 bw.error = true;
230 return false;
231 };
232 if needed_size <= bw.buf.len() {
233 return true;
234 }
235 let mut new_size = bw.buf.len().wrapping_mul(2);
236 if new_size < needed_size {
237 new_size = needed_size;
238 }
239 if new_size < 1024 {
240 new_size = 1024;
241 }
242 let Some(mut new_buf) = webp_safe_calloc::<u8>(new_size as u64, 1) else {
243 bw.error = true;
244 return false;
245 };
246 new_buf[..bw.pos].copy_from_slice(&bw.buf[..bw.pos]);
247 bw.buf = new_buf;
248 true
249}
250
251// upstream: src/utils/bit_writer_utils.c Flush
252/// Moves the top bits of `value` into the buffer, delaying `0xff` bytes until a
253/// possible carry is known.
254#[expect(
255 clippy::if_not_else,
256 clippy::cast_sign_loss,
257 reason = "keeps the branch order of C; the run and the byte are non-negative"
258)]
259fn flush(bw: &mut VP8BitWriter) {
260 let s = 8 + bw.nb_bits;
261 let bits = bw.value >> s;
262 debug_assert!(bw.nb_bits >= 0);
263 bw.value -= bits << s;
264 bw.nb_bits -= 8;
265 if (bits & 0xff) != 0xff {
266 let mut pos = bw.pos;
267 if !bit_writer_resize(bw, bw.run as usize + 1) {
268 return;
269 }
270 if (bits & 0x100) != 0 && pos > 0 {
271 // overflow: propagate the carry over the pending 0xff bytes
272 bw.buf[pos - 1] = bw.buf[pos - 1].wrapping_add(1);
273 }
274 if bw.run > 0 {
275 let value: u8 = if (bits & 0x100) != 0 { 0x00 } else { 0xff };
276 while bw.run > 0 {
277 bw.buf[pos] = value;
278 pos += 1;
279 bw.run -= 1;
280 }
281 }
282 bw.buf[pos] = (bits & 0xff) as u8;
283 pos += 1;
284 bw.pos = pos;
285 } else {
286 bw.run += 1;
287 }
288}
289
290// upstream: src/utils/bit_writer_utils.c VP8PutBit
291/// Writes `bit` with the probability `prob` of a zero, and returns `bit`.
292#[expect(
293 clippy::cast_sign_loss,
294 reason = "the renormalized range is in 0..128, a table index"
295)]
296pub fn vp8_put_bit(bw: &mut VP8BitWriter, bit: bool, prob: i32) -> bool {
297 let split = (bw.range * prob) >> 8;
298 if bit {
299 bw.value += split + 1;
300 bw.range -= split + 1;
301 } else {
302 bw.range = split;
303 }
304 if bw.range < 127 {
305 // emit 'shift' bits out and renormalize
306 let shift = i32::from(NORM[bw.range as usize]);
307 bw.range = i32::from(NEW_RANGE[bw.range as usize]);
308 bw.value <<= shift;
309 bw.nb_bits += shift;
310 if bw.nb_bits > 0 {
311 flush(bw);
312 }
313 }
314 bit
315}
316
317// upstream: src/utils/bit_writer_utils.c VP8PutBitUniform
318/// Writes `bit` with probability one half, and returns `bit`.
319#[expect(
320 clippy::cast_sign_loss,
321 reason = "the renormalized range is in 0..128, a table index"
322)]
323pub fn vp8_put_bit_uniform(bw: &mut VP8BitWriter, bit: bool) -> bool {
324 let split = bw.range >> 1;
325 if bit {
326 bw.value += split + 1;
327 bw.range -= split + 1;
328 } else {
329 bw.range = split;
330 }
331 if bw.range < 127 {
332 bw.range = i32::from(NEW_RANGE[bw.range as usize]);
333 bw.value <<= 1;
334 bw.nb_bits += 1;
335 if bw.nb_bits > 0 {
336 flush(bw);
337 }
338 }
339 bit
340}
341
342// upstream: src/utils/bit_writer_utils.c VP8PutBits
343/// Writes the `nb_bits` low bits of `value`, most significant first, uniformly.
344pub fn vp8_put_bits(bw: &mut VP8BitWriter, value: u32, nb_bits: i32) {
345 debug_assert!(nb_bits > 0 && nb_bits < 32);
346 let mut mask: u32 = 1u32 << (nb_bits - 1);
347 while mask != 0 {
348 vp8_put_bit_uniform(bw, value & mask != 0);
349 mask >>= 1;
350 }
351}
352
353// upstream: src/utils/bit_writer_utils.c VP8PutSignedBits
354/// Writes a flag for a nonzero `value`, then its magnitude and sign.
355///
356/// # Panics
357///
358/// Debug builds panic when `nb_bits` is outside `0..31`, as `VP8PutBits` does.
359#[expect(clippy::cast_sign_loss, reason = "the branch takes value >= 0")]
360pub fn vp8_put_signed_bits(bw: &mut VP8BitWriter, value: i32, nb_bits: i32) {
361 if !vp8_put_bit_uniform(bw, value != 0) {
362 return;
363 }
364 if value < 0 {
365 // C computes `(-value) << 1 | 1` as an int; the magnitude is the same
366 // for every value that does not overflow.
367 vp8_put_bits(bw, (value.unsigned_abs() << 1) | 1, nb_bits + 1);
368 } else {
369 vp8_put_bits(bw, (value as u32) << 1, nb_bits + 1);
370 }
371}
372
373// upstream: src/utils/bit_writer_utils.c VP8BitWriterInit
374/// Initializes the encoder and reserves `expected_size` bytes when it is
375/// positive. Returns `false` after a failed allocation, with `error` set.
376pub fn vp8_bit_writer_init(bw: &mut VP8BitWriter, expected_size: usize) -> bool {
377 *bw = VP8BitWriter {
378 range: 255 - 1,
379 value: 0,
380 run: 0,
381 nb_bits: -8,
382 buf: Vec::new(),
383 pos: 0,
384 error: false,
385 };
386 if expected_size > 0 {
387 bit_writer_resize(bw, expected_size)
388 } else {
389 true
390 }
391}
392
393// upstream: src/utils/bit_writer_utils.c VP8BitWriterFinish
394/// Pads the stream with zero bits, flushes it, and returns the buffer. The
395/// first `vp8_bit_writer_size` bytes of the returned slice are the stream.
396pub fn vp8_bit_writer_finish(bw: &mut VP8BitWriter) -> &[u8] {
397 vp8_put_bits(bw, 0, 9 - bw.nb_bits);
398 bw.nb_bits = 0;
399 flush(bw);
400 &bw.buf
401}
402
403// upstream: src/utils/bit_writer_utils.c VP8BitWriterAppend
404/// Appends `data` to the buffer. Refused, and returns `false`, unless the
405/// encoder is byte aligned (`nb_bits == -8`), as C requires.
406pub fn vp8_bit_writer_append(bw: &mut VP8BitWriter, data: &[u8]) -> bool {
407 if bw.nb_bits != -8 {
408 return false; // Flush() must have been called
409 }
410 if !bit_writer_resize(bw, data.len()) {
411 return false;
412 }
413 bw.buf[bw.pos..bw.pos + data.len()].copy_from_slice(data);
414 bw.pos += data.len();
415 true
416}
417
418// upstream: src/utils/bit_writer_utils.c VP8BitWriterWipeOut
419/// Releases the buffer and zeroes the encoder. Only useful after an error, when
420/// the buffer has not been taken.
421pub fn vp8_bit_writer_wipe_out(bw: &mut VP8BitWriter) {
422 *bw = VP8BitWriter::default();
423}
424
425// upstream: src/utils/bit_writer_utils.h VP8BitWriterPos
426/// The approximate write position, in bits.
427#[must_use]
428#[expect(
429 clippy::cast_sign_loss,
430 reason = "nb_bits is at least -8 and run is not negative"
431)]
432pub fn vp8_bit_writer_pos(bw: &VP8BitWriter) -> u64 {
433 let nb_bits = (8 + bw.nb_bits) as u64; // bw.nb_bits is <= 0, note
434 ((bw.pos as u64) + (bw.run as u64)) * 8 + nb_bits
435}
436
437// upstream: src/utils/bit_writer_utils.h VP8BitWriterBuf
438/// The internal buffer, including the bytes past `vp8_bit_writer_size`.
439#[must_use]
440pub fn vp8_bit_writer_buf(bw: &VP8BitWriter) -> &[u8] {
441 &bw.buf
442}
443
444// upstream: src/utils/bit_writer_utils.h VP8BitWriterSize
445/// The number of bytes written.
446#[must_use]
447pub fn vp8_bit_writer_size(bw: &VP8BitWriter) -> usize {
448 bw.pos
449}
450
451// upstream: src/utils/bit_writer_utils.c VP8LBitWriterResize
452/// Makes room for `extra_size` more bytes of the `VP8LBitWriter` buffer. The new
453/// size is one and a half times the old, at least the needed size, rounded up to
454/// a multiple of 1024 bytes, and it always adds at least one such step.
455fn vp8l_bit_writer_resize(bw: &mut VP8LBitWriter, extra_size: usize) -> bool {
456 let max_bytes = bw.buf.len();
457 let current_size = bw.cur;
458 let size_required_64b = current_size as u64 + extra_size as u64;
459 let Ok(size_required) = usize::try_from(size_required_64b) else {
460 bw.error = true;
461 return false;
462 };
463 if max_bytes > 0 && size_required <= max_bytes {
464 return true;
465 }
466 let mut allocated_size = (3 * max_bytes) >> 1;
467 if allocated_size < size_required {
468 allocated_size = size_required;
469 }
470 // make allocated size multiple of 1k
471 allocated_size = ((allocated_size >> 10) + 1) << 10;
472 let Some(mut allocated_buf) = webp_safe_calloc::<u8>(allocated_size as u64, 1) else {
473 bw.error = true;
474 return false;
475 };
476 allocated_buf[..current_size].copy_from_slice(&bw.buf[..current_size]);
477 bw.buf = allocated_buf;
478 bw.cur = current_size;
479 true
480}
481
482// upstream: src/utils/bit_writer_utils.h VP8LBitWriter
483/// The lossless bit writer: an accumulator of `used` pending bits and a buffer
484/// that the complete words are written into.
485#[derive(Debug, Default)]
486pub struct VP8LBitWriter {
487 /// Pending bits, least significant first.
488 pub bits: vp8l_atype_t,
489 /// Number of bits used in `bits`.
490 pub used: i32,
491 /// The byte buffer. Its length is the allocated size (C `end - buf`).
492 pub buf: Vec<u8>,
493 /// Offset in `buf` of the current write position (C `cur`).
494 pub cur: usize,
495 /// Set after a failed memory allocation.
496 pub error: bool,
497}
498
499// upstream: src/utils/bit_writer_utils.h VP8LBitWriterNumBytes
500/// The number of bytes that the stream occupies if it is finished now.
501#[must_use]
502#[expect(clippy::cast_sign_loss, reason = "used is not negative")]
503pub fn vp8l_bit_writer_num_bytes(bw: &VP8LBitWriter) -> usize {
504 bw.cur + ((bw.used + 7) >> 3) as usize
505}
506
507// upstream: src/utils/bit_writer_utils.c VP8LBitWriterInit
508/// Zeroes the writer and reserves `expected_size` bytes. Returns `false` after a
509/// failed allocation, with `error` set.
510pub fn vp8l_bit_writer_init(bw: &mut VP8LBitWriter, expected_size: usize) -> bool {
511 *bw = VP8LBitWriter::default();
512 vp8l_bit_writer_resize(bw, expected_size)
513}
514
515// upstream: src/utils/bit_writer_utils.c VP8LBitWriterClone
516/// Copies the written bytes and the pending bits of `src` into `dst`. Returns
517/// `false` when `dst` cannot grow.
518pub fn vp8l_bit_writer_clone(src: &VP8LBitWriter, dst: &mut VP8LBitWriter) -> bool {
519 let current_size = src.cur;
520 debug_assert!(src.cur <= src.buf.len());
521 if !vp8l_bit_writer_resize(dst, current_size) {
522 return false;
523 }
524 dst.buf[..current_size].copy_from_slice(&src.buf[..current_size]);
525 dst.bits = src.bits;
526 dst.used = src.used;
527 dst.error = src.error;
528 dst.cur = current_size;
529 true
530}
531
532// upstream: src/utils/bit_writer_utils.c VP8LBitWriterWipeOut
533/// Releases the buffer and zeroes the writer.
534pub fn vp8l_bit_writer_wipe_out(bw: &mut VP8LBitWriter) {
535 *bw = VP8LBitWriter::default();
536}
537
538// upstream: src/utils/bit_writer_utils.c VP8LBitWriterReset
539/// Returns the cursor of `bw` to the position that `bw_init` had when it was
540/// initialized, with the same pending bits and error state. The bytes are not
541/// copied, so `bw` must hold the bytes that `bw_init` had written.
542pub fn vp8l_bit_writer_reset(bw_init: &VP8LBitWriter, bw: &mut VP8LBitWriter) {
543 bw.bits = bw_init.bits;
544 bw.used = bw_init.used;
545 bw.cur = bw_init.cur;
546 debug_assert!(bw.cur <= bw.buf.len());
547 bw.error = bw_init.error;
548}
549
550// upstream: src/utils/bit_writer_utils.c VP8LBitWriterSwap
551/// Swaps the memory and the state of two writers.
552pub fn vp8l_bit_writer_swap(src: &mut VP8LBitWriter, dst: &mut VP8LBitWriter) {
553 std::mem::swap(src, dst);
554}
555
556// upstream: src/utils/bit_writer_utils.c VP8LBitWriterFinish
557/// Writes the pending bits as whole bytes and returns the buffer. The first
558/// `vp8l_bit_writer_num_bytes` bytes of the returned slice are the stream.
559#[expect(
560 clippy::cast_sign_loss,
561 clippy::cast_possible_truncation,
562 reason = "used is not negative; C stores the low byte"
563)]
564pub fn vp8l_bit_writer_finish(bw: &mut VP8LBitWriter) -> &[u8] {
565 // flush leftover bits
566 if vp8l_bit_writer_resize(bw, ((bw.used + 7) >> 3) as usize) {
567 while bw.used > 0 {
568 bw.buf[bw.cur] = bw.bits as u8;
569 bw.cur += 1;
570 bw.bits >>= 8;
571 bw.used -= 8;
572 }
573 bw.used = 0;
574 }
575 &bw.buf
576}
577
578// upstream: src/utils/bit_writer_utils.c VP8LPutBitsFlushBits
579/// Writes one write word of the accumulator and makes room for it first, by
580/// growing the buffer. After a failed growth the cursor returns to the start of
581/// the buffer and `error` is set, as C does.
582#[expect(
583 clippy::cast_possible_truncation,
584 reason = "the size is checked by check_size_overflow first"
585)]
586pub fn vp8l_put_bits_flush_bits(bw: &mut VP8LBitWriter) {
587 // If needed, make some room by flushing some bits out.
588 if bw.cur + VP8L_WRITER_BYTES > bw.buf.len() {
589 let extra_size = bw.buf.len() as u64 + MIN_EXTRA_SIZE;
590 if !check_size_overflow(extra_size) || !vp8l_bit_writer_resize(bw, extra_size as usize) {
591 bw.cur = 0;
592 bw.error = true;
593 return;
594 }
595 }
596 let word = bw.bits as vp8l_wtype_t;
597 bw.buf[bw.cur..bw.cur + VP8L_WRITER_BYTES].copy_from_slice(&word.to_le_bytes());
598 bw.cur += VP8L_WRITER_BYTES;
599 bw.bits >>= VP8L_WRITER_BITS;
600 bw.used -= VP8L_WRITER_BITS;
601}
602
603// upstream: src/utils/bit_writer_utils.c VP8LPutBitsInternal
604/// Writes up to 32 bits into the accumulator in the write-word size of 16 bits,
605/// which is the path of every target except x86-64. Its state after the call
606/// matches C for every input except `n_bits == 32` at `used == 0`: C shifts
607/// `uint32_t` by 32 there, which is undefined behavior, so that input is excluded
608/// from the differential tests.
609#[expect(
610 clippy::cast_possible_truncation,
611 reason = "the size is checked by check_size_overflow first"
612)]
613pub fn vp8l_put_bits_internal(bw: &mut VP8LBitWriter, mut bits: u32, mut n_bits: i32) {
614 debug_assert!(n_bits <= 32);
615 if n_bits > 0 {
616 let mut lbits = bw.bits;
617 let mut used = bw.used;
618 // Special case of overflow handling for 32bit accumulator (2-steps flush).
619 if VP8L_WRITER_BITS == 16 && used + n_bits >= VP8L_WRITER_MAX_BITS {
620 // Fill up all the VP8L_WRITER_MAX_BITS so it can be flushed out below.
621 let shift = VP8L_WRITER_MAX_BITS - used;
622 lbits |= vp8l_atype_t::from(bits) << used;
623 used = VP8L_WRITER_MAX_BITS;
624 n_bits -= shift;
625 bits >>= shift;
626 debug_assert!(n_bits <= VP8L_WRITER_MAX_BITS);
627 }
628 // If needed, make some room by flushing some bits out.
629 while used >= VP8L_WRITER_BITS {
630 if bw.cur + VP8L_WRITER_BYTES > bw.buf.len() {
631 let extra_size = bw.buf.len() as u64 + MIN_EXTRA_SIZE;
632 if !check_size_overflow(extra_size)
633 || !vp8l_bit_writer_resize(bw, extra_size as usize)
634 {
635 bw.cur = 0;
636 bw.error = true;
637 return;
638 }
639 }
640 let word = lbits as vp8l_wtype_t;
641 bw.buf[bw.cur..bw.cur + VP8L_WRITER_BYTES].copy_from_slice(&word.to_le_bytes());
642 bw.cur += VP8L_WRITER_BYTES;
643 lbits >>= VP8L_WRITER_BITS;
644 used -= VP8L_WRITER_BITS;
645 }
646 bw.bits = lbits | (vp8l_atype_t::from(bits) << used);
647 bw.used = used + n_bits;
648 }
649}
650
651// upstream: src/utils/bit_writer_utils.h VP8LPutBits
652/// Writes the `n_bits` low bits of `bits`, least significant first. Sets `error`
653/// on a failed memory allocation. The 32-bit write word writes the accumulator
654/// directly; the 16-bit word delegates to `vp8l_put_bits_internal`.
655pub fn vp8l_put_bits(bw: &mut VP8LBitWriter, bits: u32, n_bits: i32) {
656 if VP8L_WRITER_BYTES == 4 {
657 if n_bits > 0 {
658 if bw.used >= 32 {
659 vp8l_put_bits_flush_bits(bw);
660 }
661 bw.bits |= vp8l_atype_t::from(bits) << bw.used;
662 bw.used += n_bits;
663 }
664 } else {
665 vp8l_put_bits_internal(bw, bits, n_bits);
666 }
667}