Debian Codegraph @

debian/rust-vendor/zopfli/src/katajainen.rs

raw
1 use alloc::vec::Vec;
2 use core::{
3 cell::Cell,
4 cmp::{self, Ordering},
5 };
6
7 use bumpalo::Bump;
8
9 // Bounded package merge algorithm, based on the paper
10 // "A Fast and Space-Economical Algorithm for Length-Limited Coding
11 // Jyrki Katajainen, Alistair Moffat, Andrew Turpin".
12
13 struct Thing<'a> {
14 node_arena: &'a Bump,
15 leaves: Vec<Leaf>,
16 lists: [List<'a>; 15],
17 }
18
19 struct Node<'a> {
20 weight: usize,
21 count: usize,
22 tail: Cell<Option<&'a Node<'a>>>,
23 }
24
25 struct Leaf {
26 weight: usize,
27 count: usize,
28 }
29 impl PartialEq for Leaf {
30 fn eq(&self, other: &Self) -> bool {
31 self.weight == other.weight
32 }
33 }
34 impl Eq for Leaf {}
35 impl Ord for Leaf {
36 fn cmp(&self, other: &Self) -> Ordering {
37 self.weight.cmp(&other.weight)
38 }
39 }
40 impl PartialOrd for Leaf {
41 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
42 Some(self.cmp(other))
43 }
44 }
45
46 #[derive(Clone, Copy)]
47 struct List<'arena> {
48 lookahead0: &'arena Node<'arena>,
49 lookahead1: &'arena Node<'arena>,
50 }
51
52 /// Calculates the bitlengths for the Huffman tree, based on the counts of each
53 /// symbol.
54 pub fn length_limited_code_lengths(frequencies: &[usize], max_bits: usize) -> Vec<u32> {
55 let num_freqs = frequencies.len();
56 assert!(num_freqs <= 288);
57
58 // Count used symbols and place them in the leaves.
59 let mut leaves = frequencies
60 .iter()
61 .enumerate()
62 .filter_map(|(i, &freq)| {
63 (freq != 0).then_some(Leaf {
64 weight: freq,
65 count: i,
66 })
67 })
68 .collect::<Vec<_>>();
69
70 let num_symbols = leaves.len();
71
72 // Short circuit some special cases
73
74 // TODO:
75 // if ((1 << maxbits) < numsymbols) {
76 // free(leaves);
77 // return 1; /* Error, too few maxbits to represent symbols. */
78 // }
79
80 if num_symbols <= 2 {
81 // The symbols for the non-zero frequencies can be represented
82 // with zero or one bits.
83 let mut bit_lengths = vec![0; num_freqs];
84 for i in 0..num_symbols {
85 bit_lengths[leaves[i].count] = 1;
86 }
87 return bit_lengths;
88 }
89
90 // Sort the leaves from least frequent to most frequent.
91 leaves.sort();
92
93 let max_bits = cmp::min(num_symbols - 1, max_bits);
94 assert!(max_bits <= 15);
95
96 let arena_capacity = max_bits * 2 * num_symbols;
97 let node_arena = Bump::with_capacity(arena_capacity);
98
99 let node0 = node_arena.alloc(Node {
100 weight: leaves[0].weight,
101 count: 1,
102 tail: Cell::new(None),
103 });
104
105 let node1 = node_arena.alloc(Node {
106 weight: leaves[1].weight,
107 count: 2,
108 tail: Cell::new(None),
109 });
110
111 let lists = [List {
112 lookahead0: node0,
113 lookahead1: node1,
114 }; 15];
115
116 let mut thing = Thing {
117 node_arena: &node_arena,
118 leaves,
119 lists,
120 };
121
122 // In the last list, 2 * num_symbols - 2 active chains need to be created. Two
123 // are already created in the initialization. Each boundary_pm run creates one.
124 let num_boundary_pm_runs = 2 * num_symbols - 4;
125 for _ in 0..num_boundary_pm_runs - 1 {
126 thing.boundary_pm(max_bits - 1);
127 }
128
129 thing.boundary_pm_final(max_bits - 1);
130
131 thing.extract_bit_lengths(max_bits, num_freqs)
132 }
133
134 impl Thing<'_> {
135 fn boundary_pm(&mut self, index: usize) {
136 let num_symbols = self.leaves.len();
137
138 let last_count = self.lists[index].lookahead1.count; // Count of last chain of list.
139
140 if index == 0 && last_count >= num_symbols {
141 return;
142 }
143
144 self.lists[index].lookahead0 = self.lists[index].lookahead1;
145
146 if index == 0 {
147 // New leaf node in list 0.
148 let new_chain = self.node_arena.alloc(Node {
149 weight: self.leaves[last_count].weight,
150 count: last_count + 1,
151 tail: self.lists[index].lookahead0.tail.clone(),
152 });
153 self.lists[index].lookahead1 = new_chain;
154 } else {
155 let weight_sum = {
156 let previous_list = &self.lists[index - 1];
157 previous_list.lookahead0.weight + previous_list.lookahead1.weight
158 };
159
160 if last_count < num_symbols && weight_sum > self.leaves[last_count].weight {
161 // New leaf inserted in list, so count is incremented.
162 let new_chain = self.node_arena.alloc(Node {
163 weight: self.leaves[last_count].weight,
164 count: last_count + 1,
165 tail: self.lists[index].lookahead0.tail.clone(),
166 });
167 self.lists[index].lookahead1 = new_chain;
168 } else {
169 let new_chain = self.node_arena.alloc(Node {
170 weight: weight_sum,
171 count: last_count,
172 tail: Cell::new(Some(self.lists[index - 1].lookahead1)),
173 });
174 self.lists[index].lookahead1 = new_chain;
175
176 // Two lookahead chains of previous list used up, create new ones.
177 self.boundary_pm(index - 1);
178 self.boundary_pm(index - 1);
179 }
180 }
181 }
182
183 fn boundary_pm_final(&mut self, index: usize) {
184 let num_symbols = self.leaves.len();
185
186 // Count of last chain of list.
187 let last_count = self.lists[index].lookahead1.count;
188
189 let weight_sum = {
190 let previous_list = &self.lists[index - 1];
191 previous_list.lookahead0.weight + previous_list.lookahead1.weight
192 };
193
194 if last_count < num_symbols && weight_sum > self.leaves[last_count].weight {
195 let new_chain = self.node_arena.alloc(Node {
196 weight: 0,
197 count: last_count + 1,
198 tail: self.lists[index].lookahead1.tail.clone(),
199 });
200 self.lists[index].lookahead1 = new_chain;
201 } else {
202 self.lists[index]
203 .lookahead1
204 .tail
205 .set(Some(self.lists[index - 1].lookahead1));
206 }
207 }
208
209 fn extract_bit_lengths(&self, max_bits: usize, num_freqs: usize) -> Vec<u32> {
210 let mut counts = [0; 16];
211 let mut end = 16;
212 let mut ptr = 15;
213 let mut value = 1;
214
215 let mut node = self.lists[max_bits - 1].lookahead1;
216
217 end -= 1;
218 counts[end] = node.count;
219
220 while let Some(tail) = node.tail.get() {
221 end -= 1;
222 counts[end] = tail.count;
223 node = tail;
224 }
225
226 let mut val = counts[15];
227
228 let mut bit_lengths = vec![0; num_freqs];
229
230 while ptr >= end {
231 while val > counts[ptr - 1] {
232 bit_lengths[self.leaves[val - 1].count] = value;
233 val -= 1;
234 }
235 ptr -= 1;
236 value += 1;
237 }
238
239 bit_lengths
240 }
241 }
242
243 // fn next_leaf(lists: &mut [List], leaves: &[Leaf], current_list_index: usize) {
244 // let mut current_list = &mut lists[current_list_index];
245 //
246 // // The next leaf goes next; counting itself makes the leaf_count increase by one.
247 // current_list.lookahead1.weight = leaves[current_list.next_leaf_index].weight;
248 // current_list.lookahead1.leaf_counts.clear();
249 // current_list.lookahead1.leaf_counts.extend_from_slice(&current_list.lookahead0.leaf_counts);
250 // let last_index = current_list.lookahead1.leaf_counts.len() - 1;
251 // current_list.lookahead1.leaf_counts[last_index] += 1;
252 // current_list.next_leaf_index += 1;
253 // }
254
255 // fn next_tree(weight_sum: usize, lists: &mut [List], leaves: &[Leaf], current_list_index: usize) {
256 // {
257 // let (head, tail) = lists.split_at_mut(current_list_index);
258 // let prev_list = head.last_mut().unwrap();
259 // let current_list = tail.first_mut().unwrap();
260 //
261 // let previous_list_leaf_counts = &prev_list.lookahead1.leaf_counts;
262 //
263 // // Make a tree from the lookaheads from the previous list; that goes next.
264 // // This is not a leaf node, so the leaf count stays the same.
265 // current_list.lookahead1.weight = weight_sum;
266 // current_list.lookahead1.leaf_counts.clear();
267 //
268 // current_list.lookahead1.leaf_counts.extend_from_slice(previous_list_leaf_counts);
269 // current_list.lookahead1.leaf_counts.push(*current_list.lookahead0.leaf_counts.last().unwrap());
270 // }
271 //
272 // // The previous list needs two new lookahead nodes.
273 // boundary_pm(lists, leaves, current_list_index - 1);
274 // boundary_pm(lists, leaves, current_list_index - 1);
275 // }
276
277 // fn boundary_pm_toplevel(lists: &mut [List], leaves: &[Leaf]) {
278 // let last_index = lists.len() - 1;
279 // boundary_pm(lists, leaves, last_index);
280 // }
281
282 // fn boundary_pm(lists: &mut [List], leaves: &[Leaf], current_list_index: usize) {
283 // let next_leaf_index = lists[current_list_index].next_leaf_index;
284 // let num_symbols = leaves.len();
285 //
286 // if current_list_index == 0 && next_leaf_index == num_symbols {
287 // // We've added all the leaves to the lowest list, so we're done here
288 // return;
289 // }
290 //
291 // mem::swap(&mut lists[current_list_index].lookahead0, &mut lists[current_list_index].lookahead1);
292 //
293 // if current_list_index == 0 {
294 // lowest_list(lists, leaves);
295 // } else {
296 // // We're at a list other than the lowest list.
297 // let weight_sum = {
298 // let previous_list = &lists[current_list_index - 1];
299 // previous_list.lookahead0.weight + previous_list.lookahead1.weight
300 // };
301 //
302 // if next_leaf_index < num_symbols && weight_sum > leaves[next_leaf_index].weight {
303 // next_leaf(lists, leaves, current_list_index);
304 // } else {
305 // next_tree(weight_sum, lists, leaves, current_list_index);
306 // }
307 // }
308 // }
309
310 #[cfg(test)]
311 mod test {
312 use super::*;
313
314 #[test]
315 fn test_from_paper_3() {
316 let input = [1, 1, 5, 7, 10, 14];
317 let output = length_limited_code_lengths(&input, 3);
318 let answer = vec![3, 3, 3, 3, 2, 2];
319 assert_eq!(output, answer);
320 }
321
322 #[test]
323 fn test_from_paper_4() {
324 let input = [1, 1, 5, 7, 10, 14];
325 let output = length_limited_code_lengths(&input, 4);
326 let answer = vec![4, 4, 3, 2, 2, 2];
327 assert_eq!(output, answer);
328 }
329
330 #[test]
331 fn max_bits_7() {
332 let input = [252, 0, 1, 6, 9, 10, 6, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
333 let output = length_limited_code_lengths(&input, 7);
334 let answer = vec![1, 0, 6, 4, 3, 3, 3, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
335 assert_eq!(output, answer);
336 }
337
338 #[test]
339 fn max_bits_15() {
340 let input = [
341 0, 0, 0, 0, 0, 0, 18, 0, 6, 0, 12, 2, 14, 9, 27, 15, 23, 15, 17, 8, 1, 0, 0, 0, 0, 0,
342 0, 0, 0, 0, 0, 0,
343 ];
344 let output = length_limited_code_lengths(&input, 15);
345 let answer = vec![
346 0, 0, 0, 0, 0, 0, 3, 0, 5, 0, 4, 6, 4, 4, 3, 4, 3, 3, 3, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0,
347 0, 0, 0,
348 ];
349 assert_eq!(output, answer);
350 }
351
352 #[test]
353 fn no_frequencies() {
354 let input = [0, 0, 0, 0, 0];
355 let output = length_limited_code_lengths(&input, 7);
356 let answer = vec![0, 0, 0, 0, 0];
357 assert_eq!(output, answer);
358 }
359
360 #[test]
361 fn only_one_frequency() {
362 let input = [0, 10, 0];
363 let output = length_limited_code_lengths(&input, 7);
364 let answer = vec![0, 1, 0];
365 assert_eq!(output, answer);
366 }
367
368 #[test]
369 fn only_two_frequencies() {
370 let input = [0, 0, 0, 0, 252, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
371 let output = length_limited_code_lengths(&input, 7);
372 let answer = [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
373 assert_eq!(output, answer);
374 }
375 }