1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/* Copyright 2010 Google Inc. All Rights Reserved.

   Distributed under MIT license.
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/

/* Entropy encoding (Huffman) utilities. */
#![allow(dead_code)]
use core::cmp::max;

#[derive(Clone, Copy, Default)]
pub struct HuffmanTree {
    pub total_count_: u32,
    pub index_left_: i16,
    pub index_right_or_value_: i16,
}

impl HuffmanTree {
    pub fn new(count: u32, left: i16, right: i16) -> Self {
        Self {
            total_count_: count,
            index_left_: left,
            index_right_or_value_: right,
        }
    }
}

pub fn BrotliSetDepth(p0: i32, pool: &mut [HuffmanTree], depth: &mut [u8], max_depth: i32) -> bool {
    let mut stack: [i32; 16] = [0; 16];
    let mut level: i32 = 0i32;
    let mut p: i32 = p0;
    stack[0] = -1i32;
    loop {
        if (pool[(p as usize)]).index_left_ as i32 >= 0i32 {
            level += 1;
            if level > max_depth {
                return false;
            }
            stack[level as usize] = (pool[(p as usize)]).index_right_or_value_ as i32;
            p = (pool[(p as usize)]).index_left_ as i32;
            {
                continue;
            }
        } else {
            let pp = pool[(p as usize)];
            depth[((pp).index_right_or_value_ as usize)] = level as u8;
        }
        while level >= 0i32 && (stack[level as usize] == -1i32) {
            level -= 1;
        }
        if level < 0i32 {
            return true;
        }
        p = stack[level as usize];
        stack[level as usize] = -1i32;
    }
}

pub trait HuffmanComparator {
    fn Cmp(&self, a: &HuffmanTree, b: &HuffmanTree) -> bool;
}
pub struct SortHuffmanTree {}
impl HuffmanComparator for SortHuffmanTree {
    fn Cmp(&self, v0: &HuffmanTree, v1: &HuffmanTree) -> bool {
        if v0.total_count_ != v1.total_count_ {
            v0.total_count_ < v1.total_count_
        } else {
            v0.index_right_or_value_ > v1.index_right_or_value_
        }
    }
}
pub fn SortHuffmanTreeItems<Comparator: HuffmanComparator>(
    items: &mut [HuffmanTree],
    n: usize,
    comparator: Comparator,
) {
    static gaps: [usize; 6] = [132, 57, 23, 10, 4, 1];
    if n < 13 {
        for i in 1..n {
            let mut tmp: HuffmanTree = items[i];
            let mut k: usize = i;
            let mut j: usize = i.wrapping_sub(1);
            while comparator.Cmp(&mut tmp, &mut items[j]) {
                items[k] = items[j];
                k = j;
                if {
                    let _old = j;
                    j = j.wrapping_sub(1);
                    _old
                } == 0
                {
                    break;
                }
            }
            items[k] = tmp;
        }
    } else {
        let mut g: i32 = if n < 57usize { 2i32 } else { 0i32 };
        while g < 6i32 {
            {
                let gap: usize = gaps[g as usize];
                for i in gap..n {
                    let mut j: usize = i;
                    let mut tmp: HuffmanTree = items[i];
                    while j >= gap && (comparator.Cmp(&mut tmp, &mut items[j.wrapping_sub(gap)])) {
                        {
                            items[j] = items[j.wrapping_sub(gap)];
                        }
                        j = j.wrapping_sub(gap);
                    }
                    items[j] = tmp;
                }
            }
            g += 1;
        }
    }
}

/* This function will create a Huffman tree.

The catch here is that the tree cannot be arbitrarily deep.
Brotli specifies a maximum depth of 15 bits for "code trees"
and 7 bits for "code length code trees."

count_limit is the value that is to be faked as the minimum value
and this minimum value is raised until the tree matches the
maximum length requirement.

This algorithm is not of excellent performance for very long data blocks,
especially when population counts are longer than 2**tree_limit, but
we are not planning to use this with extremely long blocks.

See https://en.wikipedia.org/wiki/Huffman_coding */
pub fn BrotliCreateHuffmanTree(
    data: &[u32],
    length: usize,
    tree_limit: i32,
    tree: &mut [HuffmanTree],
    depth: &mut [u8],
) {
    let sentinel = HuffmanTree::new(u32::MAX, -1, -1);
    let mut count_limit = 1u32;
    'break1: loop {
        {
            let mut n: usize = 0usize;
            let mut i: usize;
            let mut j: usize;
            let mut k: usize;
            i = length;
            while i != 0usize {
                i = i.wrapping_sub(1);
                if data[i] != 0 {
                    let count: u32 = max(data[i], count_limit);
                    tree[n] = HuffmanTree::new(count, -1, i as i16);
                    n = n.wrapping_add(1);
                }
            }
            if n == 1 {
                depth[((tree[0]).index_right_or_value_ as usize)] = 1u8;
                {
                    break 'break1;
                }
            }
            SortHuffmanTreeItems(tree, n, SortHuffmanTree {});
            tree[n] = sentinel;
            tree[n.wrapping_add(1)] = sentinel;
            i = 0usize;
            j = n.wrapping_add(1);
            k = n.wrapping_sub(1);
            while k != 0usize {
                {
                    let left: usize;
                    let right: usize;
                    if (tree[i]).total_count_ <= (tree[j]).total_count_ {
                        left = i;
                        i = i.wrapping_add(1);
                    } else {
                        left = j;
                        j = j.wrapping_add(1);
                    }
                    if (tree[i]).total_count_ <= (tree[j]).total_count_ {
                        right = i;
                        i = i.wrapping_add(1);
                    } else {
                        right = j;
                        j = j.wrapping_add(1);
                    }
                    {
                        let j_end: usize = (2usize).wrapping_mul(n).wrapping_sub(k);
                        (tree[j_end]).total_count_ = (tree[left])
                            .total_count_
                            .wrapping_add((tree[right]).total_count_);
                        (tree[j_end]).index_left_ = left as i16;
                        (tree[j_end]).index_right_or_value_ = right as i16;
                        tree[j_end.wrapping_add(1)] = sentinel;
                    }
                }
                k = k.wrapping_sub(1);
            }
            if BrotliSetDepth(
                (2usize).wrapping_mul(n).wrapping_sub(1) as i32,
                tree,
                depth,
                tree_limit,
            ) {
                break 'break1;
            }
        }
        count_limit = count_limit.wrapping_mul(2);
    }
}
pub fn BrotliOptimizeHuffmanCountsForRle(
    mut length: usize,
    counts: &mut [u32],
    good_for_rle: &mut [u8],
) {
    let mut nonzero_count: usize = 0usize;
    let mut stride: usize;
    let mut limit: usize;
    let mut sum: usize;
    let streak_limit: usize = 1240usize;
    for i in 0usize..length {
        if counts[i] != 0 {
            nonzero_count = nonzero_count.wrapping_add(1);
        }
    }
    if nonzero_count < 16usize {
        return;
    }
    while length != 0usize && (counts[length.wrapping_sub(1)] == 0u32) {
        length = length.wrapping_sub(1);
    }
    if length == 0usize {
        return;
    }
    {
        let mut nonzeros: usize = 0usize;
        let mut smallest_nonzero: u32 = (1i32 << 30) as u32;
        for i in 0usize..length {
            if counts[i] != 0u32 {
                nonzeros = nonzeros.wrapping_add(1);
                if smallest_nonzero > counts[i] {
                    smallest_nonzero = counts[i];
                }
            }
        }
        if nonzeros < 5usize {
            return;
        }
        if smallest_nonzero < 4u32 {
            let zeros: usize = length.wrapping_sub(nonzeros);
            if zeros < 6 {
                for i in 1..length.wrapping_sub(1) {
                    if counts[i - 1] != 0 && counts[i] == 0 && counts[i + 1] != 0 {
                        counts[i] = 1;
                    }
                }
            }
        }
        if nonzeros < 28usize {
            return;
        }
    }
    for rle_item in good_for_rle.iter_mut() {
        *rle_item = 0;
    }
    {
        let mut symbol: u32 = counts[0];
        let mut step: usize = 0usize;
        for i in 0..=length {
            if i == length || counts[i] != symbol {
                if symbol == 0u32 && (step >= 5usize) || symbol != 0u32 && (step >= 7usize) {
                    for k in 0usize..step {
                        good_for_rle[i.wrapping_sub(k).wrapping_sub(1)] = 1u8;
                    }
                }
                step = 1;
                if i != length {
                    symbol = counts[i];
                }
            } else {
                step = step.wrapping_add(1);
            }
        }
    }
    stride = 0usize;
    limit = (256u32)
        .wrapping_mul((counts[0]).wrapping_add(counts[1]).wrapping_add(counts[2]))
        .wrapping_div(3)
        .wrapping_add(420) as usize;
    sum = 0usize;
    for i in 0..=length {
        if i == length
            || good_for_rle[i] != 0
            || i != 0usize && (good_for_rle[i.wrapping_sub(1)] != 0)
            || ((256u32).wrapping_mul(counts[i]) as usize)
                .wrapping_sub(limit)
                .wrapping_add(streak_limit)
                >= (2usize).wrapping_mul(streak_limit)
        {
            if stride >= 4usize || stride >= 3usize && (sum == 0usize) {
                let mut count: usize = sum
                    .wrapping_add(stride.wrapping_div(2))
                    .wrapping_div(stride);
                if count == 0usize {
                    count = 1;
                }
                if sum == 0usize {
                    count = 0usize;
                }
                for k in 0usize..stride {
                    counts[i.wrapping_sub(k).wrapping_sub(1)] = count as u32;
                }
            }
            stride = 0usize;
            sum = 0usize;
            if i < length.wrapping_sub(2) {
                limit = (256u32)
                    .wrapping_mul(
                        (counts[i])
                            .wrapping_add(counts[i.wrapping_add(1)])
                            .wrapping_add(counts[i.wrapping_add(2)]),
                    )
                    .wrapping_div(3)
                    .wrapping_add(420) as usize;
            } else if i < length {
                limit = (256u32).wrapping_mul(counts[i]) as usize;
            } else {
                limit = 0usize;
            }
        }
        stride = stride.wrapping_add(1);
        if i != length {
            sum = sum.wrapping_add(counts[i] as usize);
            if stride >= 4usize {
                limit = (256usize)
                    .wrapping_mul(sum)
                    .wrapping_add(stride.wrapping_div(2))
                    .wrapping_div(stride);
            }
            if stride == 4usize {
                limit = limit.wrapping_add(120);
            }
        }
    }
}

pub fn DecideOverRleUse(
    depth: &[u8],
    length: usize,
    use_rle_for_non_zero: &mut i32,
    use_rle_for_zero: &mut i32,
) {
    let mut total_reps_zero: usize = 0usize;
    let mut total_reps_non_zero: usize = 0usize;
    let mut count_reps_zero: usize = 1;
    let mut count_reps_non_zero: usize = 1;
    let mut i: usize;
    i = 0usize;
    while i < length {
        let value: u8 = depth[i];
        let mut reps: usize = 1;
        let mut k: usize;
        k = i.wrapping_add(1);
        while k < length && (depth[k] as i32 == value as i32) {
            {
                reps = reps.wrapping_add(1);
            }
            k = k.wrapping_add(1);
        }
        if reps >= 3usize && (value as i32 == 0i32) {
            total_reps_zero = total_reps_zero.wrapping_add(reps);
            count_reps_zero = count_reps_zero.wrapping_add(1);
        }
        if reps >= 4usize && (value as i32 != 0i32) {
            total_reps_non_zero = total_reps_non_zero.wrapping_add(reps);
            count_reps_non_zero = count_reps_non_zero.wrapping_add(1);
        }
        i = i.wrapping_add(reps);
    }
    *use_rle_for_non_zero = if total_reps_non_zero > count_reps_non_zero.wrapping_mul(2) {
        1i32
    } else {
        0i32
    };
    *use_rle_for_zero = if total_reps_zero > count_reps_zero.wrapping_mul(2) {
        1i32
    } else {
        0i32
    };
}

fn Reverse(v: &mut [u8], mut start: usize, mut end: usize) {
    end = end.wrapping_sub(1);
    while start < end {
        v.swap(start, end);
        start = start.wrapping_add(1);
        end = end.wrapping_sub(1);
    }
}

fn BrotliWriteHuffmanTreeRepetitions(
    previous_value: u8,
    value: u8,
    mut repetitions: usize,
    tree_size: &mut usize,
    tree: &mut [u8],
    extra_bits_data: &mut [u8],
) {
    if previous_value as i32 != value as i32 {
        tree[*tree_size] = value;
        extra_bits_data[*tree_size] = 0u8;
        *tree_size = tree_size.wrapping_add(1);
        repetitions = repetitions.wrapping_sub(1);
    }
    if repetitions == 7usize {
        tree[*tree_size] = value;
        extra_bits_data[*tree_size] = 0u8;
        *tree_size = tree_size.wrapping_add(1);
        repetitions = repetitions.wrapping_sub(1);
    }
    if repetitions < 3usize {
        for _i in 0usize..repetitions {
            tree[*tree_size] = value;
            extra_bits_data[*tree_size] = 0u8;
            *tree_size = tree_size.wrapping_add(1);
        }
    } else {
        let start: usize = *tree_size;
        repetitions = repetitions.wrapping_sub(3);
        loop {
            tree[*tree_size] = 16u8;
            extra_bits_data[*tree_size] = (repetitions & 0x03) as u8;
            *tree_size = tree_size.wrapping_add(1);
            repetitions >>= 2i32;
            if repetitions == 0usize {
                break;
            }
            repetitions = repetitions.wrapping_sub(1);
        }
        Reverse(tree, start, *tree_size);
        Reverse(extra_bits_data, start, *tree_size);
    }
}

fn BrotliWriteHuffmanTreeRepetitionsZeros(
    mut repetitions: usize,
    tree_size: &mut usize,
    tree: &mut [u8],
    extra_bits_data: &mut [u8],
) {
    if repetitions == 11 {
        tree[*tree_size] = 0u8;
        extra_bits_data[*tree_size] = 0u8;
        *tree_size = tree_size.wrapping_add(1);
        repetitions = repetitions.wrapping_sub(1);
    }
    if repetitions < 3usize {
        for _i in 0usize..repetitions {
            tree[*tree_size] = 0u8;
            extra_bits_data[*tree_size] = 0u8;
            *tree_size = tree_size.wrapping_add(1);
        }
    } else {
        let start: usize = *tree_size;
        repetitions = repetitions.wrapping_sub(3);
        loop {
            tree[*tree_size] = 17u8;
            extra_bits_data[*tree_size] = (repetitions & 0x7usize) as u8;
            *tree_size = tree_size.wrapping_add(1);
            repetitions >>= 3i32;
            if repetitions == 0usize {
                break;
            }
            repetitions = repetitions.wrapping_sub(1);
        }
        Reverse(tree, start, *tree_size);
        Reverse(extra_bits_data, start, *tree_size);
    }
}

pub fn BrotliWriteHuffmanTree(
    depth: &[u8],
    length: usize,
    tree_size: &mut usize,
    tree: &mut [u8],
    extra_bits_data: &mut [u8],
) {
    let mut previous_value: u8 = 8u8;
    let mut i: usize;
    let mut use_rle_for_non_zero: i32 = 0i32;
    let mut use_rle_for_zero: i32 = 0i32;
    let mut new_length: usize = length;
    i = 0usize;
    'break27: while i < length {
        {
            if depth[length.wrapping_sub(i).wrapping_sub(1)] as i32 == 0i32 {
                new_length = new_length.wrapping_sub(1);
            } else {
                break 'break27;
            }
        }
        i = i.wrapping_add(1);
    }
    if length > 50usize {
        DecideOverRleUse(
            depth,
            new_length,
            &mut use_rle_for_non_zero,
            &mut use_rle_for_zero,
        );
    }
    i = 0usize;
    while i < new_length {
        let value: u8 = depth[i];
        let mut reps: usize = 1;
        if value as i32 != 0i32 && (use_rle_for_non_zero != 0)
            || value as i32 == 0i32 && (use_rle_for_zero != 0)
        {
            let mut k: usize;
            k = i.wrapping_add(1);
            while k < new_length && (depth[k] as i32 == value as i32) {
                {
                    reps = reps.wrapping_add(1);
                }
                k = k.wrapping_add(1);
            }
        }
        if value as i32 == 0i32 {
            BrotliWriteHuffmanTreeRepetitionsZeros(reps, tree_size, tree, extra_bits_data);
        } else {
            BrotliWriteHuffmanTreeRepetitions(
                previous_value,
                value,
                reps,
                tree_size,
                tree,
                extra_bits_data,
            );
            previous_value = value;
        }
        i = i.wrapping_add(reps);
    }
}

fn BrotliReverseBits(num_bits: usize, mut bits: u16) -> u16 {
    static kLut: [usize; 16] = [
        0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf,
    ];
    let mut retval: usize = kLut[(bits as i32 & 0xfi32) as usize];
    let mut i: usize;
    i = 4usize;
    while i < num_bits {
        {
            retval <<= 4i32;
            bits = (bits as i32 >> 4) as u16;
            retval |= kLut[(bits as i32 & 0xfi32) as usize];
        }
        i = i.wrapping_add(4);
    }
    retval >>= (0usize.wrapping_sub(num_bits) & 0x3usize);
    retval as u16
}
const MAX_HUFFMAN_BITS: usize = 16;
pub fn BrotliConvertBitDepthsToSymbols(depth: &[u8], len: usize, bits: &mut [u16]) {
    /* In Brotli, all bit depths are [1..15]
    0 bit depth means that the symbol does not exist. */

    let mut bl_count: [u16; MAX_HUFFMAN_BITS] = [0; MAX_HUFFMAN_BITS];
    let mut next_code: [u16; MAX_HUFFMAN_BITS] = [0; MAX_HUFFMAN_BITS];
    let mut code: i32 = 0i32;
    for i in 0usize..len {
        let _rhs = 1;
        let _lhs = &mut bl_count[depth[i] as usize];
        *_lhs = (*_lhs as i32 + _rhs) as u16;
    }
    bl_count[0] = 0u16;
    next_code[0] = 0u16;
    for i in 1..MAX_HUFFMAN_BITS {
        code = (code + bl_count[i - 1] as i32) << 1;
        next_code[i] = code as u16;
    }
    for i in 0usize..len {
        if depth[i] != 0 {
            bits[i] = BrotliReverseBits(depth[i] as usize, {
                let _rhs = 1;
                let _lhs = &mut next_code[depth[i] as usize];
                let _old = *_lhs;
                *_lhs = (*_lhs as i32 + _rhs) as u16;
                _old
            });
        }
    }
}