Skip to main content

unityrs_texture/decode/
length.rs

1//! Input lengths, format footprints and scratch charge estimates.
2
3use super::{Format, Library, astc, crunch};
4
5/// The length Pillow 9.5.0's `BCn` decoder sees for `len` bytes of data:
6/// `ImagingBcnDecode` passes its `Py_ssize_t` length to `decode_bcn`'s `int`
7/// parameter, a conversion GCC and Clang both make modulo 2^32, then as a
8/// signed value (C leaves an out-of-range conversion to the
9/// implementation), so the decode loop (`while (bytes >= SZ)`) runs on the
10/// length's low 32 bits, none when bit 31 is set. Below 2 GiB it is the
11/// length itself.
12#[must_use]
13pub fn bcn_length(len: usize) -> u64 {
14    let low = u64::try_from(len).unwrap_or(u64::MAX) & 0xFFFF_FFFF;
15    // As a signed 32-bit value: negative when bit 31 is set, and then the
16    // loop decodes no block.
17    if low >= 1 << 31 { 0 } else { low }
18}
19
20/// The temporary buffers and tables needed beside a decode's output.
21pub(super) fn scratch_charge(format: Format, unpacked_bytes: u64, width: u64) -> u64 {
22    if format.is_unity_crunched() {
23        crunch::unity::scratch(unpacked_bytes, width)
24    } else if format.is_crunched() {
25        crunch::scratch(unpacked_bytes)
26    } else {
27        astc_footprint(format).map_or(0, astc::Tables::charge)
28    }
29}
30
31/// Stored bytes per pixel for raw Pillow and closed-form formats.
32pub(super) fn raw_pixel_bytes(format: Format) -> u64 {
33    crate::tierb::layout(format).map_or_else(
34        || u64::from(format.raw_bits().unwrap_or(0) / 8),
35        crate::tierb::Layout::bytes,
36    )
37}
38
39/// An ASTC format's footprint.
40pub(super) fn astc_footprint(format: Format) -> Option<astc::Footprint> {
41    if format.library() != Library::Astcenc {
42        return None;
43    }
44    let (w, h) = format.block_size()?;
45    astc::Footprint::new(w, h)
46}