webp/utils/color_cache_utils.rs
1// libwebp v1.6.0, src/utils/color_cache_utils.c:
2//
3// Copyright 2012 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// Color Cache for WebP Lossless
13//
14// Author: Jyrki Alakuijala (jyrki@google.com)
15
16// libwebp v1.6.0, src/utils/color_cache_utils.h:
17//
18// Copyright 2012 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// Color Cache for WebP Lossless
28//
29// Authors: Jyrki Alakuijala (jyrki@google.com)
30// Urvang Joshi (urvang@google.com)
31
32//! Translation of `src/utils/color_cache_utils.c` and `src/utils/color_cache_utils.h` from libwebp v1.6.0.
33//!
34//! Work package: WP3 (lossless shared).
35//!
36//! # Deviations from upstream
37//!
38//! Changes of representation that the ADRs allow, or behavior that the Rust
39//! side cannot reproduce exactly. Each records the reason.
40//!
41//! 1. **`VP8LColorCache`.** `colors` is a `Vec<u32>`, empty where C has `NULL`.
42//! `Set` and `Insert` take `&mut`, because C writes through the cache's
43//! pointer from a `const` struct pointer. Keys index after a checked
44//! conversion.
45//!
46//! # Excluded undefined behavior
47//!
48//! Inputs that are undefined behavior (or assertion failures) in C and are
49//! therefore excluded from the oracle comparison (PORTING rule 8):
50//!
51//! 1. `VP8LHashPix` with a shift of 32 or more, `VP8LColorCacheInit` with hash
52//! bits outside 1 to 30, `VP8LSubSampleSize` with 31 or more sampling bits,
53//! `RightShiftRound` with a shift of 64 or more, `DivRound` by zero or with
54//! an overflowing quotient, and the prefix encodings for distances below 3:
55//! shifts out of range, a zero argument to `BitsLog2Floor` or signed
56//! overflow in C. (`VP8LSubSampleSize`, `RightShiftRound`, `DivRound` and
57//! the prefix encodings are in `src/dsp/lossless_common.rs`.)
58//!
59//! # Checks not applicable
60//!
61//! These checks do not apply, or cannot be made, with the reason:
62//!
63//! 1. **`VP8LColorCacheInit` failure.** The format allows 1 to 11 hash bits,
64//! which always pass the size test; the failure branch keeps C's partial
65//! state (see the documentation of `vp8l_color_cache_init`) but is not
66//! reached.
67
68use crate::utils::utils::webp_safe_calloc;
69
70// upstream: src/utils/color_cache_utils.h VP8LColorCache
71/// Main color cache struct.
72#[derive(Clone, Debug, Default, PartialEq, Eq)]
73pub struct VP8LColorCache {
74 /// Color entries; empty where C has `colors == NULL`.
75 pub colors: Vec<u32>,
76 /// Hash shift: 32 - `hash_bits`.
77 pub hash_shift: i32,
78 pub hash_bits: i32,
79}
80
81// upstream: src/utils/color_cache_utils.h kHashMul
82pub const HASH_MUL: u32 = 0x1e35_a7bd;
83
84// upstream: src/utils/color_cache_utils.h VP8LHashPix
85/// The hash of `argb`: the 32-bit product with [`HASH_MUL`], which wraps as
86/// in C, shifted right by `shift`.
87#[must_use]
88#[inline]
89pub fn vp8l_hash_pix(argb: u32, shift: i32) -> i32 {
90 (argb.wrapping_mul(HASH_MUL) >> shift).cast_signed()
91}
92
93/// Converts a cache key, which is never negative, to an index.
94#[inline]
95fn key_index(key: i32) -> usize {
96 usize::try_from(key).expect("a cache key is not negative")
97}
98
99// upstream: src/utils/color_cache_utils.h VP8LColorCacheLookup
100#[must_use]
101#[inline]
102pub fn vp8l_color_cache_lookup(cc: &VP8LColorCache, key: u32) -> u32 {
103 debug_assert_eq!(key >> cc.hash_bits, 0);
104 cc.colors[key as usize]
105}
106
107// upstream: src/utils/color_cache_utils.h VP8LColorCacheSet
108#[inline]
109pub fn vp8l_color_cache_set(cc: &mut VP8LColorCache, key: u32, argb: u32) {
110 debug_assert_eq!(key >> cc.hash_bits, 0);
111 cc.colors[key as usize] = argb;
112}
113
114// upstream: src/utils/color_cache_utils.h VP8LColorCacheInsert
115#[inline]
116pub fn vp8l_color_cache_insert(cc: &mut VP8LColorCache, argb: u32) {
117 let key = vp8l_hash_pix(argb, cc.hash_shift);
118 cc.colors[key_index(key)] = argb;
119}
120
121// upstream: src/utils/color_cache_utils.h VP8LColorCacheGetIndex
122#[must_use]
123#[inline]
124pub fn vp8l_color_cache_get_index(cc: &VP8LColorCache, argb: u32) -> i32 {
125 vp8l_hash_pix(argb, cc.hash_shift)
126}
127
128// upstream: src/utils/color_cache_utils.h VP8LColorCacheContains
129/// Return the key if cc contains argb, and -1 otherwise.
130#[must_use]
131#[inline]
132pub fn vp8l_color_cache_contains(cc: &VP8LColorCache, argb: u32) -> i32 {
133 let key = vp8l_hash_pix(argb, cc.hash_shift);
134 if cc.colors[key_index(key)] == argb {
135 key
136 } else {
137 -1
138 }
139}
140
141// upstream: src/utils/color_cache_utils.c VP8LColorCacheInit
142/// Initializes the color cache with `hash_bits` bits for the keys.
143/// Returns false in case of memory error; `colors` is then empty, and the
144/// other fields keep their values, as in C.
145#[must_use]
146pub fn vp8l_color_cache_init(color_cache: &mut VP8LColorCache, hash_bits: i32) -> bool {
147 let hash_size: i32 = 1 << hash_bits;
148 debug_assert!(hash_bits > 0);
149 let Some(colors) = webp_safe_calloc::<u32>(i64::from(hash_size).cast_unsigned(), 4) else {
150 color_cache.colors = Vec::new();
151 return false;
152 };
153 color_cache.colors = colors;
154 color_cache.hash_shift = 32 - hash_bits;
155 color_cache.hash_bits = hash_bits;
156 true
157}
158
159// upstream: src/utils/color_cache_utils.c VP8LColorCacheClear
160/// Delete the memory associated to color cache.
161pub fn vp8l_color_cache_clear(color_cache: &mut VP8LColorCache) {
162 color_cache.colors = Vec::new();
163}
164
165// upstream: src/utils/color_cache_utils.c VP8LColorCacheCopy
166/// Copies the `1 << dst.hash_bits` colors of `src` into `dst`.
167///
168/// # Panics
169///
170/// Panics when either cache holds fewer colors, where C copies outside them.
171pub fn vp8l_color_cache_copy(src: &VP8LColorCache, dst: &mut VP8LColorCache) {
172 debug_assert_eq!(src.hash_bits, dst.hash_bits);
173 let count = 1_usize << dst.hash_bits;
174 dst.colors[..count].copy_from_slice(&src.colors[..count]);
175}