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
#![allow(dead_code)]

use super::super::alloc::{SliceWrapper, SliceWrapperMut};
use super::block_split::BlockSplit;
use super::command::Command;
use super::constants::{kSigned3BitContextLookup, kUTF8ContextLookup};
use super::vectorization::Mem256i;
use core::cmp::min;
static kBrotliMinWindowBits: i32 = 10i32;

static kBrotliMaxWindowBits: i32 = 24i32;

//#[derive(Clone)] clone is broken for arrays > 32
pub struct HistogramLiteral {
    pub data_: [u32; 256],
    pub total_count_: usize,
    pub bit_cost_: super::util::floatX,
}
impl Clone for HistogramLiteral {
    #[inline(always)]
    fn clone(&self) -> HistogramLiteral {
        HistogramLiteral {
            data_: self.data_,
            total_count_: self.total_count_,
            bit_cost_: self.bit_cost_,
        }
    }
}
impl Default for HistogramLiteral {
    #[inline(always)]
    fn default() -> HistogramLiteral {
        HistogramLiteral {
            data_: [0; 256],
            total_count_: 0,
            bit_cost_: 3.402e+38 as super::util::floatX,
        }
    }
}
//#[derive(Clone)] clone is broken for arrays > 32
pub struct HistogramCommand {
    pub data_: [u32; 704],
    pub total_count_: usize,
    pub bit_cost_: super::util::floatX,
}
impl Clone for HistogramCommand {
    #[inline(always)]
    fn clone(&self) -> HistogramCommand {
        HistogramCommand {
            data_: self.data_,
            total_count_: self.total_count_,
            bit_cost_: self.bit_cost_,
        }
    }
}
impl Default for HistogramCommand {
    #[inline(always)]
    fn default() -> HistogramCommand {
        HistogramCommand {
            data_: [0; 704],
            total_count_: 0,
            bit_cost_: 3.402e+38 as super::util::floatX,
        }
    }
}
//#[derive(Clone)] // #derive is broken for arrays > 32

#[cfg(not(feature = "disallow_large_window_size"))]
const BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS: usize = 544;
#[cfg(feature = "disallow_large_window_size")]
const BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS: usize = 520;

pub struct HistogramDistance {
    pub data_: [u32; BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS],
    pub total_count_: usize,
    pub bit_cost_: super::util::floatX,
}
impl Clone for HistogramDistance {
    fn clone(&self) -> HistogramDistance {
        HistogramDistance {
            data_: self.data_,
            total_count_: self.total_count_,
            bit_cost_: self.bit_cost_,
        }
    }
}
impl Default for HistogramDistance {
    fn default() -> HistogramDistance {
        HistogramDistance {
            data_: [0; BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS],
            total_count_: 0,
            bit_cost_: 3.402e+38 as super::util::floatX,
        }
    }
}

pub trait CostAccessors {
    type i32vec: Sized + SliceWrapper<Mem256i> + SliceWrapperMut<Mem256i>;
    fn make_nnz_storage() -> Self::i32vec;
    fn total_count(&self) -> usize;
    fn bit_cost(&self) -> super::util::floatX;
    fn set_bit_cost(&mut self, cost: super::util::floatX);
    fn set_total_count(&mut self, count: usize);
}
impl SliceWrapper<u32> for HistogramLiteral {
    #[inline(always)]
    fn slice(&self) -> &[u32] {
        &self.data_[..]
    }
}
impl SliceWrapperMut<u32> for HistogramLiteral {
    #[inline(always)]
    fn slice_mut(&mut self) -> &mut [u32] {
        &mut self.data_[..]
    }
}
pub struct Array264i([Mem256i; 33]);
impl SliceWrapperMut<Mem256i> for Array264i {
    #[inline(always)]
    fn slice_mut(&mut self) -> &mut [Mem256i] {
        &mut self.0[..]
    }
}

impl SliceWrapper<Mem256i> for Array264i {
    #[inline(always)]
    fn slice(&self) -> &[Mem256i] {
        &self.0[..]
    }
}
impl Default for Array264i {
    #[inline(always)]
    fn default() -> Array264i {
        Array264i([Mem256i::default(); 33])
    }
}
pub struct Array528i([Mem256i; 66]);
impl SliceWrapperMut<Mem256i> for Array528i {
    #[inline(always)]
    fn slice_mut(&mut self) -> &mut [Mem256i] {
        &mut self.0[..]
    }
}
impl SliceWrapper<Mem256i> for Array528i {
    #[inline(always)]
    fn slice(&self) -> &[Mem256i] {
        &self.0[..]
    }
}
impl Default for Array528i {
    #[inline(always)]
    fn default() -> Array528i {
        Array528i([Mem256i::default(); 66])
    }
}

pub struct Array712i([Mem256i; 89]);
impl SliceWrapperMut<Mem256i> for Array712i {
    #[inline(always)]
    fn slice_mut(&mut self) -> &mut [Mem256i] {
        &mut self.0[..]
    }
}
impl SliceWrapper<Mem256i> for Array712i {
    #[inline(always)]
    fn slice(&self) -> &[Mem256i] {
        &self.0[..]
    }
}
impl Default for Array712i {
    #[inline(always)]
    fn default() -> Array712i {
        Array712i([Mem256i::default(); 89])
    }
}

pub struct EmptyIVec {}

impl SliceWrapperMut<Mem256i> for EmptyIVec {
    #[inline(always)]
    fn slice_mut(&mut self) -> &mut [Mem256i] {
        &mut []
    }
}
impl SliceWrapper<Mem256i> for EmptyIVec {
    #[inline(always)]
    fn slice(&self) -> &[Mem256i] {
        &[]
    }
}

impl Default for EmptyIVec {
    #[inline(always)]
    fn default() -> EmptyIVec {
        EmptyIVec {}
    }
}

#[cfg(feature = "vector_scratch_space")]
pub type HistogramLiteralScratch = Array264i;

#[cfg(not(feature = "vector_scratch_space"))]
pub type HistogramLiteralScratch = EmptyIVec;

impl CostAccessors for HistogramLiteral {
    type i32vec = HistogramLiteralScratch;
    fn make_nnz_storage() -> Self::i32vec {
        HistogramLiteralScratch::default()
    }
    #[inline(always)]
    fn total_count(&self) -> usize {
        self.total_count_
    }
    #[inline(always)]
    fn bit_cost(&self) -> super::util::floatX {
        self.bit_cost_
    }
    #[inline(always)]
    fn set_bit_cost(&mut self, data: super::util::floatX) {
        self.bit_cost_ = data;
    }
    #[inline(always)]
    fn set_total_count(&mut self, data: usize) {
        self.total_count_ = data;
    }
}

impl SliceWrapper<u32> for HistogramCommand {
    #[inline(always)]
    fn slice(&self) -> &[u32] {
        &self.data_[..]
    }
}
impl SliceWrapperMut<u32> for HistogramCommand {
    #[inline(always)]
    fn slice_mut(&mut self) -> &mut [u32] {
        &mut self.data_[..]
    }
}

#[cfg(feature = "vector_scratch_space")]
pub type HistogramCommandScratch = Array712i;

#[cfg(not(feature = "vector_scratch_space"))]
pub type HistogramCommandScratch = EmptyIVec;

impl CostAccessors for HistogramCommand {
    type i32vec = HistogramCommandScratch;
    fn make_nnz_storage() -> Self::i32vec {
        HistogramCommandScratch::default()
    }
    #[inline(always)]
    fn total_count(&self) -> usize {
        self.total_count_
    }
    #[inline(always)]
    fn bit_cost(&self) -> super::util::floatX {
        self.bit_cost_
    }
    #[inline(always)]
    fn set_bit_cost(&mut self, data: super::util::floatX) {
        self.bit_cost_ = data;
    }
    #[inline(always)]
    fn set_total_count(&mut self, data: usize) {
        self.total_count_ = data;
    }
}

impl SliceWrapper<u32> for HistogramDistance {
    #[inline(always)]
    fn slice(&self) -> &[u32] {
        &self.data_[..]
    }
}
impl SliceWrapperMut<u32> for HistogramDistance {
    #[inline(always)]
    fn slice_mut(&mut self) -> &mut [u32] {
        &mut self.data_[..]
    }
}

#[cfg(feature = "vector_scratch_space")]
pub type HistogramDistanceScratch = Array528i;

#[cfg(not(feature = "vector_scratch_space"))]
pub type HistogramDistanceScratch = EmptyIVec;

impl CostAccessors for HistogramDistance {
    type i32vec = HistogramDistanceScratch;
    fn make_nnz_storage() -> Self::i32vec {
        HistogramDistanceScratch::default()
    }

    #[inline(always)]
    fn total_count(&self) -> usize {
        self.total_count_
    }
    #[inline(always)]
    fn bit_cost(&self) -> super::util::floatX {
        self.bit_cost_
    }
    #[inline(always)]
    fn set_bit_cost(&mut self, data: super::util::floatX) {
        self.bit_cost_ = data;
    }
    #[inline(always)]
    fn set_total_count(&mut self, data: usize) {
        self.total_count_ = data;
    }
}

#[derive(Copy, Clone)]
pub enum ContextType {
    CONTEXT_LSB6 = 0,
    CONTEXT_MSB6 = 1,
    CONTEXT_UTF8 = 2,
    CONTEXT_SIGNED = 3,
}

impl Default for ContextType {
    #[inline(always)]
    fn default() -> ContextType {
        ContextType::CONTEXT_LSB6
    }
}

pub struct BlockSplitIterator<'a, Alloc: alloc::Allocator<u8> + 'a + alloc::Allocator<u32> + 'a> {
    pub split_: &'a BlockSplit<Alloc>,
    pub idx_: usize,
    pub type_: usize,
    pub length_: usize,
}

impl<'a, Alloc: alloc::Allocator<u8> + alloc::Allocator<u32> + 'a> BlockSplitIterator<'a, Alloc> {
    fn new(split: &'a BlockSplit<Alloc>) -> Self {
        Self {
            split_: split,
            idx_: 0,
            type_: 0,
            length_: if !split.lengths.slice().is_empty() {
                split.lengths.slice()[0] as usize
            } else {
                0
            },
        }
    }

    fn next(&mut self) {
        if self.length_ == 0 {
            self.idx_ = self.idx_.wrapping_add(1);
            self.type_ = self.split_.types.slice()[self.idx_] as usize;
            self.length_ = self.split_.lengths.slice()[self.idx_] as usize;
        }
        self.length_ = self.length_.wrapping_sub(1);
    }
}

pub fn HistogramAddItem<HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors>(
    xself: &mut HistogramType,
    val: usize,
) {
    {
        let _rhs = 1;
        let _lhs = &mut xself.slice_mut()[val];
        let val = (*_lhs).wrapping_add(_rhs as u32);
        *_lhs = val;
    }
    let new_count = xself.total_count().wrapping_add(1);
    xself.set_total_count(new_count);
}
pub fn HistogramAddVector<
    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors,
    IntegerType: Sized + Clone,
>(
    xself: &mut HistogramType,
    p: &[IntegerType],
    n: usize,
) where
    u64: core::convert::From<IntegerType>,
{
    let new_tc = xself.total_count().wrapping_add(n);
    xself.set_total_count(new_tc);
    for p_item in p[..n].iter() {
        let _rhs = 1;
        let index: usize = u64::from(p_item.clone()) as usize;
        let _lhs = &mut xself.slice_mut()[index];
        *_lhs = (*_lhs).wrapping_add(_rhs as u32);
    }
}

#[inline(always)]
pub fn HistogramClear<HistogramType: SliceWrapperMut<u32> + CostAccessors>(
    xself: &mut HistogramType,
) {
    for data_elem in xself.slice_mut().iter_mut() {
        *data_elem = 0;
    }
    xself.set_total_count(0);
    xself.set_bit_cost(3.402e+38 as super::util::floatX);
}
pub fn ClearHistograms<HistogramType: SliceWrapperMut<u32> + CostAccessors>(
    array: &mut [HistogramType],
    length: usize,
) {
    for item in array[..length].iter_mut() {
        HistogramClear(item)
    }
}

#[inline(always)]
pub fn HistogramAddHistogram<
    HistogramType: SliceWrapperMut<u32> + SliceWrapper<u32> + CostAccessors,
>(
    xself: &mut HistogramType,
    v: &HistogramType,
) {
    let old_total_count = xself.total_count();
    xself.set_total_count(old_total_count + (*v).total_count());
    let h0 = xself.slice_mut();
    let h1 = v.slice();
    let n = min(h0.len(), h1.len());
    for i in 0..n {
        let h0val = &mut h0[i];
        let val = h0val.wrapping_add(h1[i]);
        *h0val = val;
    }
}
pub fn HistogramSelfAddHistogram<
    HistogramType: SliceWrapperMut<u32> + SliceWrapper<u32> + CostAccessors,
>(
    xself: &mut [HistogramType],
    i0: usize,
    i1: usize,
) {
    let tc_new = xself[i1].total_count();
    let tc_old = xself[i0].total_count();
    xself[i0].set_total_count(tc_old.wrapping_add(tc_new));
    let h0 = xself[i0].slice().len();
    let h0a = xself[i0].slice().len();
    let h1 = xself[i1].slice().len();
    let n = min(h0, min(h0a, h1));
    for h_index in 0..n {
        let val = xself[i0].slice()[h_index].wrapping_add(xself[i1].slice()[h_index]);
        xself[i0].slice_mut()[h_index] = val;
    }
}

#[inline(always)]
pub fn Context(p1: u8, p2: u8, mode: ContextType) -> u8 {
    match mode {
        ContextType::CONTEXT_SIGNED => {
            (((kSigned3BitContextLookup[p1 as usize] as i32) << 3)
                + kSigned3BitContextLookup[p2 as usize] as i32) as u8
        }
        ContextType::CONTEXT_UTF8 => {
            (kUTF8ContextLookup[p1 as usize] as i32
                | kUTF8ContextLookup[(p2 as i32 + 256i32) as usize] as i32) as u8
        }
        ContextType::CONTEXT_MSB6 => (p1 as i32 >> 2) as u8,
        ContextType::CONTEXT_LSB6 => (p1 as i32 & 0x3fi32) as u8, /* else {
                                                                  0u8
                                                                  }*/
    }
}

pub fn BrotliBuildHistogramsWithContext<'a, Alloc: alloc::Allocator<u8> + alloc::Allocator<u32>>(
    cmds: &[Command],
    num_commands: usize,
    literal_split: &BlockSplit<Alloc>,
    insert_and_copy_split: &BlockSplit<Alloc>,
    dist_split: &BlockSplit<Alloc>,
    ringbuffer: &[u8],
    start_pos: usize,
    mask: usize,
    mut prev_byte: u8,
    mut prev_byte2: u8,
    context_modes: &[ContextType],
    literal_histograms: &mut [HistogramLiteral],
    insert_and_copy_histograms: &mut [HistogramCommand],
    copy_dist_histograms: &mut [HistogramDistance],
) {
    let mut pos: usize = start_pos;
    let mut literal_it: BlockSplitIterator<Alloc>;
    let mut insert_and_copy_it: BlockSplitIterator<Alloc>;
    let mut dist_it: BlockSplitIterator<Alloc>;
    literal_it = BlockSplitIterator::new(literal_split);
    insert_and_copy_it = BlockSplitIterator::new(insert_and_copy_split);
    dist_it = BlockSplitIterator::new(dist_split);
    for i in 0usize..num_commands {
        let cmd = &cmds[i];
        let mut j: usize;
        insert_and_copy_it.next();
        HistogramAddItem(
            &mut insert_and_copy_histograms[insert_and_copy_it.type_],
            cmd.cmd_prefix_ as usize,
        );
        j = cmd.insert_len_ as usize;
        while j != 0usize {
            {
                literal_it.next();
                let context: usize = if !context_modes.is_empty() {
                    (literal_it.type_ << 6).wrapping_add(Context(
                        prev_byte,
                        prev_byte2,
                        context_modes[literal_it.type_],
                    ) as usize)
                } else {
                    literal_it.type_
                };
                HistogramAddItem(
                    &mut literal_histograms[(context as usize)],
                    ringbuffer[(pos & mask)] as usize,
                );
                prev_byte2 = prev_byte;
                prev_byte = ringbuffer[(pos & mask)];
                pos = pos.wrapping_add(1);
            }
            j = j.wrapping_sub(1);
        }
        pos = pos.wrapping_add(cmd.copy_len() as usize);
        if cmd.copy_len() != 0 {
            prev_byte2 = ringbuffer[(pos.wrapping_sub(2) & mask)];
            prev_byte = ringbuffer[(pos.wrapping_sub(1) & mask)];
            if cmd.cmd_prefix_ as i32 >= 128i32 {
                dist_it.next();
                let context: usize =
                    (dist_it.type_ << 2).wrapping_add(cmd.distance_context() as usize);
                HistogramAddItem(
                    &mut copy_dist_histograms[(context as usize)],
                    cmd.dist_prefix_ as usize & 0x3ff,
                );
            }
        }
    }
}