Skip to main content

brotli/enc/
block_splitter.rs

1use core;
2use core::cmp::{max, min};
3#[cfg(feature = "simd")]
4use core::simd::prelude::{SimdFloat, SimdPartialOrd};
5
6use super::super::alloc::{Allocator, SliceWrapper, SliceWrapperMut};
7use super::backward_references::BrotliEncoderParams;
8use super::bit_cost::BrotliPopulationCost;
9use super::block_split::BlockSplit;
10use super::cluster::{BrotliHistogramBitCostDistance, BrotliHistogramCombine, HistogramPair};
11use super::command::Command;
12use super::histogram::{
13    ClearHistograms, CostAccessors, HistogramAddHistogram, HistogramAddItem, HistogramAddVector,
14    HistogramClear, HistogramCommand, HistogramDistance, HistogramLiteral,
15};
16use super::util::FastLog2;
17use super::vectorization::{sum8i, v256, v256i, Mem256f};
18use crate::enc::combined_alloc::allocate;
19use crate::enc::floatX;
20
21static kMaxLiteralHistograms: usize = 100usize;
22
23static kMaxCommandHistograms: usize = 50usize;
24
25static kLiteralBlockSwitchCost: floatX = 28.1;
26
27static kCommandBlockSwitchCost: floatX = 13.5;
28
29static kDistanceBlockSwitchCost: floatX = 14.6;
30
31static kLiteralStrideLength: usize = 70usize;
32
33static kCommandStrideLength: usize = 40usize;
34
35static kSymbolsPerLiteralHistogram: usize = 544usize;
36
37static kSymbolsPerCommandHistogram: usize = 530usize;
38
39static kSymbolsPerDistanceHistogram: usize = 544usize;
40
41static kMinLengthForBlockSplitting: usize = 128usize;
42
43static kIterMulForRefining: usize = 2usize;
44
45static kMinItersForRefining: usize = 100usize;
46
47#[inline(always)]
48fn update_cost_and_signal(
49    num_histograms32: u32,
50    ix: usize,
51    min_cost: floatX,
52    block_switch_cost: floatX,
53    cost: &mut [Mem256f],
54    switch_signal: &mut [u8],
55) {
56    let ymm_min_cost = v256::splat(min_cost);
57    let ymm_block_switch_cost = v256::splat(block_switch_cost);
58    let ymm_and_mask = v256i::from([
59        1 << 0,
60        1 << 1,
61        1 << 2,
62        1 << 3,
63        1 << 4,
64        1 << 5,
65        1 << 6,
66        1 << 7,
67    ]);
68
69    for (index, cost_it) in cost[..((num_histograms32 as usize + 7) >> 3)]
70        .iter_mut()
71        .enumerate()
72    {
73        let mut ymm_cost = *cost_it;
74        let costk_minus_min_cost = ymm_cost - ymm_min_cost;
75        let ymm_cmpge: v256i = costk_minus_min_cost
76            .simd_ge(ymm_block_switch_cost)
77            .to_simd();
78        let ymm_bits = ymm_cmpge & ymm_and_mask;
79        let result = sum8i(ymm_bits);
80        //super::vectorization::sum8(ymm_bits) as u8;
81        switch_signal[ix + index] |= result as u8;
82        ymm_cost = costk_minus_min_cost.simd_min(ymm_block_switch_cost);
83        *cost_it = Mem256f::from(ymm_cost);
84        //println_stderr!("{:} ss {:} c {:?}", (index << 3) + 7, switch_signal[ix + index],*cost_it);
85    }
86}
87fn CountLiterals(cmds: &[Command], num_commands: usize) -> usize {
88    let mut total_length: usize = 0usize;
89    for i in 0usize..num_commands {
90        total_length = total_length.wrapping_add((cmds[i]).insert_len_ as usize);
91    }
92    total_length
93}
94
95fn CopyLiteralsToByteArray(
96    cmds: &[Command],
97    num_commands: usize,
98    data: &[u8],
99    offset: usize,
100    mask: usize,
101    literals: &mut [u8],
102) {
103    let mut pos: usize = 0usize;
104    let mut from_pos: usize = offset & mask;
105    for i in 0usize..num_commands {
106        let mut insert_len: usize = (cmds[i]).insert_len_ as usize;
107        if from_pos.wrapping_add(insert_len) > mask {
108            let head_size: usize = mask.wrapping_add(1).wrapping_sub(from_pos);
109            literals[pos..(pos + head_size)]
110                .clone_from_slice(&data[from_pos..(from_pos + head_size)]);
111            from_pos = 0usize;
112            pos = pos.wrapping_add(head_size);
113            insert_len = insert_len.wrapping_sub(head_size);
114        }
115        if insert_len > 0usize {
116            literals[pos..(pos + insert_len)]
117                .clone_from_slice(&data[from_pos..(from_pos + insert_len)]);
118            pos = pos.wrapping_add(insert_len);
119        }
120        from_pos = from_pos
121            .wrapping_add(insert_len)
122            .wrapping_add(cmds[i].copy_len() as usize)
123            & mask;
124    }
125}
126
127fn MyRand(seed: &mut u32) -> u32 {
128    *seed = seed.wrapping_mul(16807);
129    if *seed == 0u32 {
130        *seed = 1u32;
131    }
132    *seed
133}
134
135fn InitialEntropyCodes<
136    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors,
137    IntegerType: Sized + Clone,
138>(
139    data: &[IntegerType],
140    length: usize,
141    stride: usize,
142    num_histograms: usize,
143    histograms: &mut [HistogramType],
144) where
145    u64: core::convert::From<IntegerType>,
146{
147    let mut seed: u32 = 7u32;
148    let block_length: usize = length.wrapping_div(num_histograms);
149    ClearHistograms(histograms, num_histograms);
150    for i in 0usize..num_histograms {
151        let mut pos: usize = length.wrapping_mul(i).wrapping_div(num_histograms);
152        if i != 0usize {
153            pos = pos.wrapping_add((MyRand(&mut seed) as usize).wrapping_rem(block_length));
154        }
155        if pos.wrapping_add(stride) >= length {
156            pos = length.wrapping_sub(stride).wrapping_sub(1);
157        }
158        HistogramAddVector(&mut histograms[i], &data[pos..], stride);
159    }
160}
161
162fn RandomSample<
163    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors,
164    IntegerType: Sized + Clone,
165>(
166    seed: &mut u32,
167    data: &[IntegerType],
168    length: usize,
169    mut stride: usize,
170    sample: &mut HistogramType,
171) where
172    u64: core::convert::From<IntegerType>,
173{
174    let pos: usize;
175    if stride >= length {
176        pos = 0usize;
177        stride = length;
178    } else {
179        pos = (MyRand(seed) as usize).wrapping_rem(length.wrapping_sub(stride).wrapping_add(1));
180    }
181    HistogramAddVector(sample, &data[pos..], stride);
182}
183
184fn RefineEntropyCodes<
185    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors + core::default::Default,
186    IntegerType: Sized + Clone,
187>(
188    data: &[IntegerType],
189    length: usize,
190    stride: usize,
191    num_histograms: usize,
192    histograms: &mut [HistogramType],
193) where
194    u64: core::convert::From<IntegerType>,
195{
196    let mut iters: usize = kIterMulForRefining
197        .wrapping_mul(length)
198        .wrapping_div(stride)
199        .wrapping_add(kMinItersForRefining);
200    let mut seed: u32 = 7u32;
201    iters = iters
202        .wrapping_add(num_histograms)
203        .wrapping_sub(1)
204        .wrapping_div(num_histograms)
205        .wrapping_mul(num_histograms);
206    for iter in 0usize..iters {
207        let mut sample = HistogramType::default();
208        HistogramClear(&mut sample);
209        RandomSample(&mut seed, data, length, stride, &mut sample);
210        HistogramAddHistogram(
211            &mut histograms[iter.wrapping_rem(num_histograms)],
212            &mut sample,
213        );
214    }
215}
216
217fn BitCost(count: usize) -> floatX {
218    if count == 0usize {
219        -2.0
220    } else {
221        FastLog2(count as u64)
222    }
223}
224
225fn FindBlocks<
226    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors,
227    IntegerType: Sized + Clone,
228>(
229    data: &[IntegerType],
230    length: usize,
231    block_switch_bitcost: floatX,
232    num_histograms: usize,
233    histograms: &[HistogramType],
234    insert_cost: &mut [floatX],
235    cost: &mut [Mem256f],
236    switch_signal: &mut [u8],
237    block_id: &mut [u8],
238) -> usize
239where
240    u64: core::convert::From<IntegerType>,
241{
242    if num_histograms == 0 {
243        return 0;
244    }
245    let data_size: usize = histograms[0].slice().len();
246    let bitmaplen: usize = num_histograms.wrapping_add(7) >> 3;
247    let mut num_blocks: usize = 1;
248    let mut i: usize;
249    if num_histograms <= 1 {
250        for i in 0usize..length {
251            block_id[i] = 0u8;
252        }
253        return 1;
254    }
255    for item in insert_cost[..(data_size * num_histograms)].iter_mut() {
256        *item = 0.0;
257    }
258    for i in 0usize..num_histograms {
259        insert_cost[i] = FastLog2((histograms[i]).total_count() as u32 as (u64));
260    }
261    i = data_size;
262    while i != 0usize {
263        i = i.wrapping_sub(1);
264        for j in 0usize..num_histograms {
265            insert_cost[i.wrapping_mul(num_histograms).wrapping_add(j)] =
266                insert_cost[j] - BitCost((histograms[j]).slice()[i] as usize);
267        }
268    }
269    for item in cost.iter_mut() {
270        *item = Mem256f::default();
271    }
272    for item in switch_signal[..(length * bitmaplen)].iter_mut() {
273        *item = 0;
274    }
275    for (byte_ix, data_byte_ix) in data[..length].iter().enumerate() {
276        let block_id_ptr = &mut block_id[byte_ix];
277        let ix: usize = byte_ix.wrapping_mul(bitmaplen);
278        let insert_cost_ix: usize =
279            u64::from(data_byte_ix.clone()).wrapping_mul(num_histograms as u64) as usize;
280        let mut min_cost: floatX = 1e38;
281        let mut block_switch_cost: floatX = block_switch_bitcost;
282        // main (vectorized) loop
283        let insert_cost_slice = insert_cost.split_at(insert_cost_ix).1;
284        for (v_index, cost_iter) in cost
285            .split_at_mut(num_histograms >> 3)
286            .0
287            .iter_mut()
288            .enumerate()
289        {
290            let base_index = v_index << 3;
291            let mut local_insert_cost = [0.0; 8];
292            local_insert_cost
293                .clone_from_slice(insert_cost_slice.split_at(base_index).1.split_at(8).0);
294            for sub_index in 0usize..8usize {
295                cost_iter[sub_index] += local_insert_cost[sub_index];
296                let final_cost = cost_iter[sub_index];
297                if final_cost < min_cost {
298                    min_cost = final_cost;
299                    *block_id_ptr = (base_index + sub_index) as u8;
300                }
301            }
302        }
303        let vectorized_offset = ((num_histograms >> 3) << 3);
304        let mut k = vectorized_offset;
305        //remainder loop for
306        for insert_cost_iter in insert_cost
307            .split_at(insert_cost_ix + vectorized_offset)
308            .1
309            .split_at(num_histograms & 7)
310            .0
311            .iter()
312        {
313            let cost_iter = &mut cost[(k >> 3)];
314            cost_iter[k & 7] += *insert_cost_iter;
315            if cost_iter[k & 7] < min_cost {
316                min_cost = cost_iter[k & 7];
317                *block_id_ptr = k as u8;
318            }
319            k += 1;
320        }
321        if byte_ix < 2000usize {
322            block_switch_cost *= (0.77 + 0.07 * (byte_ix as floatX) / 2000.0);
323        }
324        update_cost_and_signal(
325            num_histograms as u32,
326            ix,
327            min_cost,
328            block_switch_cost,
329            cost,
330            switch_signal,
331        );
332    }
333    {
334        let mut byte_ix: usize = length.wrapping_sub(1);
335        let mut ix: usize = byte_ix.wrapping_mul(bitmaplen);
336        let mut cur_id: u8 = block_id[byte_ix];
337        while byte_ix > 0usize {
338            let mask: u8 = (1u32 << (cur_id as i32 & 7i32)) as u8;
339            byte_ix -= 1;
340            ix = ix.wrapping_sub(bitmaplen);
341            if switch_signal[ix.wrapping_add((cur_id as i32 >> 3) as usize)] as i32 & mask as i32
342                != 0
343                && cur_id as i32 != block_id[byte_ix] as i32
344            {
345                cur_id = block_id[byte_ix];
346                num_blocks = num_blocks.wrapping_add(1);
347            }
348            block_id[byte_ix] = cur_id;
349        }
350    }
351    num_blocks
352}
353
354fn RemapBlockIds(
355    block_ids: &mut [u8],
356    length: usize,
357    new_id: &mut [u16],
358    num_histograms: usize,
359) -> usize {
360    static kInvalidId: u16 = 256u16;
361    let mut next_id: u16 = 0u16;
362    for i in 0usize..num_histograms {
363        new_id[i] = kInvalidId;
364    }
365    for i in 0usize..length {
366        if new_id[(block_ids[i] as usize)] as i32 == kInvalidId as i32 {
367            new_id[(block_ids[i] as usize)] = {
368                let _old = next_id;
369                next_id = (next_id as i32 + 1) as u16;
370                _old
371            };
372        }
373    }
374    for i in 0usize..length {
375        block_ids[i] = new_id[(block_ids[i] as usize)] as u8;
376    }
377    next_id as usize
378}
379
380fn BuildBlockHistograms<
381    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors,
382    IntegerType: Sized + Clone,
383>(
384    data: &[IntegerType],
385    length: usize,
386    block_ids: &[u8],
387    num_histograms: usize,
388    histograms: &mut [HistogramType],
389) where
390    u64: core::convert::From<IntegerType>,
391{
392    ClearHistograms(histograms, num_histograms);
393    for i in 0usize..length {
394        HistogramAddItem(
395            &mut histograms[(block_ids[i] as usize)],
396            u64::from(data[i].clone()) as usize,
397        );
398    }
399}
400
401fn ClusterBlocks<
402    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors + core::default::Default + Clone,
403    Alloc: alloc::Allocator<u8>
404        + alloc::Allocator<u32>
405        + alloc::Allocator<HistogramType>
406        + alloc::Allocator<HistogramPair>,
407    IntegerType: Sized + Clone,
408>(
409    alloc: &mut Alloc,
410    data: &[IntegerType],
411    length: usize,
412    num_blocks: usize,
413    scratch_space: &mut HistogramType::i32vec,
414    block_ids: &mut [u8],
415    split: &mut BlockSplit<Alloc>,
416) where
417    u64: core::convert::From<IntegerType>,
418{
419    let mut histogram_symbols = allocate::<u32, _>(alloc, num_blocks);
420    let mut block_lengths = allocate::<u32, _>(alloc, num_blocks);
421    let expected_num_clusters: usize = (16usize)
422        .wrapping_mul(num_blocks.wrapping_add(64).wrapping_sub(1))
423        .wrapping_div(64);
424    let mut all_histograms_size: usize = 0usize;
425    let mut all_histograms_capacity: usize = expected_num_clusters;
426    let mut all_histograms = allocate::<HistogramType, _>(alloc, all_histograms_capacity);
427    let mut cluster_size_size: usize = 0usize;
428    let mut cluster_size_capacity: usize = expected_num_clusters;
429    let mut cluster_size = allocate::<u32, _>(alloc, cluster_size_capacity);
430    let mut num_clusters: usize = 0usize;
431    let mut histograms = allocate::<HistogramType, _>(alloc, min(num_blocks, 64));
432    let mut max_num_pairs: usize = (64i32 * 64i32 / 2i32) as usize;
433    let pairs_capacity: usize = max_num_pairs.wrapping_add(1);
434    let mut pairs = allocate::<HistogramPair, _>(alloc, pairs_capacity);
435    let mut pos: usize = 0usize;
436    let mut clusters: <Alloc as Allocator<u32>>::AllocatedMemory;
437
438    static kInvalidIndex: u32 = u32::MAX;
439    let mut i: usize;
440    let mut sizes: [u32; 64] = [0; 64];
441    let mut new_clusters: [u32; 64] = [0; 64];
442    let mut symbols: [u32; 64] = [0; 64];
443    let mut remap: [u32; 64] = [0; 64];
444    {
445        let mut block_idx: usize = 0usize;
446        i = 0usize;
447        while i < length {
448            {
449                {
450                    let _rhs = 1;
451                    let _lhs = &mut block_lengths.slice_mut()[block_idx];
452                    *_lhs = (*_lhs).wrapping_add(_rhs as u32);
453                }
454                if i.wrapping_add(1) == length
455                    || block_ids[i] as i32 != block_ids[i.wrapping_add(1)] as i32
456                {
457                    block_idx = block_idx.wrapping_add(1);
458                }
459            }
460            i = i.wrapping_add(1);
461        }
462    }
463    i = 0usize;
464    while i < num_blocks {
465        {
466            let num_to_combine: usize = min(num_blocks.wrapping_sub(i), 64);
467
468            for j in 0usize..num_to_combine {
469                HistogramClear(&mut histograms.slice_mut()[j]);
470                for _k in 0usize..block_lengths.slice()[i.wrapping_add(j)] as usize {
471                    HistogramAddItem(
472                        &mut histograms.slice_mut()[j],
473                        u64::from(data[pos].clone()) as usize,
474                    );
475                    pos = pos.wrapping_add(1);
476                }
477                let new_cost = BrotliPopulationCost(&histograms.slice()[j], scratch_space);
478                (histograms.slice_mut()[j]).set_bit_cost(new_cost);
479
480                new_clusters[j] = j as u32;
481                symbols[j] = j as u32;
482                sizes[j] = 1u32;
483            }
484            let num_new_clusters: usize = BrotliHistogramCombine(
485                histograms.slice_mut(),
486                &mut sizes[..],
487                &mut symbols[..],
488                &mut new_clusters[..],
489                pairs.slice_mut(),
490                num_to_combine,
491                num_to_combine,
492                64usize,
493                max_num_pairs,
494                scratch_space,
495            );
496            {
497                if all_histograms_capacity < all_histograms_size.wrapping_add(num_new_clusters) {
498                    let mut _new_size: usize = if all_histograms_capacity == 0usize {
499                        all_histograms_size.wrapping_add(num_new_clusters)
500                    } else {
501                        all_histograms_capacity
502                    };
503                    while _new_size < all_histograms_size.wrapping_add(num_new_clusters) {
504                        _new_size = _new_size.wrapping_mul(2);
505                    }
506                    let mut new_array = allocate::<HistogramType, _>(alloc, _new_size);
507                    new_array.slice_mut()[..all_histograms_capacity]
508                        .clone_from_slice(&all_histograms.slice()[..all_histograms_capacity]);
509                    <Alloc as Allocator<HistogramType>>::free_cell(
510                        alloc,
511                        core::mem::replace(&mut all_histograms, new_array),
512                    );
513                    all_histograms_capacity = _new_size;
514                }
515            }
516            {
517                if cluster_size_capacity < cluster_size_size.wrapping_add(num_new_clusters) {
518                    let mut _new_size: usize = if cluster_size_capacity == 0usize {
519                        cluster_size_size.wrapping_add(num_new_clusters)
520                    } else {
521                        cluster_size_capacity
522                    };
523                    while _new_size < cluster_size_size.wrapping_add(num_new_clusters) {
524                        _new_size = _new_size.wrapping_mul(2);
525                    }
526                    let mut new_array = allocate::<u32, _>(alloc, _new_size);
527                    new_array.slice_mut()[..cluster_size_capacity]
528                        .clone_from_slice(&cluster_size.slice()[..cluster_size_capacity]);
529                    <Alloc as Allocator<u32>>::free_cell(
530                        alloc,
531                        core::mem::replace(&mut cluster_size, new_array),
532                    );
533                    cluster_size_capacity = _new_size;
534                }
535            }
536            for j in 0usize..num_new_clusters {
537                all_histograms.slice_mut()[all_histograms_size] =
538                    histograms.slice()[new_clusters[j] as usize].clone();
539                all_histograms_size = all_histograms_size.wrapping_add(1);
540                cluster_size.slice_mut()[cluster_size_size] = sizes[new_clusters[j] as usize];
541                cluster_size_size = cluster_size_size.wrapping_add(1);
542                remap[new_clusters[j] as usize] = j as u32;
543            }
544            for j in 0usize..num_to_combine {
545                histogram_symbols.slice_mut()[i.wrapping_add(j)] =
546                    (num_clusters as u32).wrapping_add(remap[symbols[j] as usize]);
547            }
548            num_clusters = num_clusters.wrapping_add(num_new_clusters);
549        }
550        i = i.wrapping_add(64);
551    }
552    <Alloc as Allocator<HistogramType>>::free_cell(alloc, core::mem::take(&mut histograms));
553    max_num_pairs = min(
554        (64usize).wrapping_mul(num_clusters),
555        num_clusters.wrapping_div(2).wrapping_mul(num_clusters),
556    );
557    if pairs_capacity < max_num_pairs.wrapping_add(1) {
558        let new_cell = allocate::<HistogramPair, _>(alloc, max_num_pairs.wrapping_add(1));
559        <Alloc as Allocator<HistogramPair>>::free_cell(
560            alloc,
561            core::mem::replace(&mut pairs, new_cell),
562        );
563    }
564    clusters = allocate::<u32, _>(alloc, num_clusters);
565    i = 0usize;
566    for item in clusters.slice_mut()[..num_clusters].iter_mut() {
567        *item = i as u32;
568        i = i.wrapping_add(1);
569    }
570    let num_final_clusters: usize = BrotliHistogramCombine(
571        all_histograms.slice_mut(),
572        cluster_size.slice_mut(),
573        histogram_symbols.slice_mut(),
574        clusters.slice_mut(),
575        pairs.slice_mut(),
576        num_clusters,
577        num_blocks,
578        256usize,
579        max_num_pairs,
580        scratch_space,
581    );
582    <Alloc as Allocator<HistogramPair>>::free_cell(alloc, core::mem::take(&mut pairs));
583    <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::take(&mut cluster_size));
584
585    let mut new_index = allocate::<u32, _>(alloc, num_clusters);
586    for item in new_index.slice_mut().iter_mut() {
587        *item = kInvalidIndex;
588    }
589    pos = 0usize;
590    {
591        let mut next_index: u32 = 0u32;
592        for i in 0usize..num_blocks {
593            let mut histo: HistogramType = HistogramType::default();
594            let mut best_out: u32;
595            let mut best_bits: floatX;
596            HistogramClear(&mut histo);
597            for _j in 0usize..block_lengths.slice()[i] as usize {
598                HistogramAddItem(&mut histo, u64::from(data[pos].clone()) as usize);
599                pos = pos.wrapping_add(1);
600            }
601            best_out = if i == 0usize {
602                histogram_symbols.slice()[0]
603            } else {
604                histogram_symbols.slice()[i.wrapping_sub(1)]
605            };
606            best_bits = BrotliHistogramBitCostDistance(
607                &mut histo,
608                &mut all_histograms.slice_mut()[(best_out as usize)],
609                scratch_space,
610            );
611            for j in 0usize..num_final_clusters {
612                let cur_bits: floatX = BrotliHistogramBitCostDistance(
613                    &mut histo,
614                    &mut all_histograms.slice_mut()[(clusters.slice()[j] as usize)],
615                    scratch_space,
616                );
617                if cur_bits < best_bits {
618                    best_bits = cur_bits;
619                    best_out = clusters.slice()[j];
620                }
621            }
622            histogram_symbols.slice_mut()[i] = best_out;
623            if new_index.slice()[best_out as usize] == kInvalidIndex {
624                new_index.slice_mut()[best_out as usize] = next_index;
625                next_index = next_index.wrapping_add(1);
626            }
627        }
628    }
629    <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::take(&mut clusters));
630    <Alloc as Allocator<HistogramType>>::free_cell(alloc, core::mem::take(&mut all_histograms));
631    {
632        if split.types_alloc_size() < num_blocks {
633            let mut _new_size: usize = if split.types_alloc_size() == 0usize {
634                num_blocks
635            } else {
636                split.types_alloc_size()
637            };
638            while _new_size < num_blocks {
639                _new_size = _new_size.wrapping_mul(2);
640            }
641            let mut new_array = allocate::<u8, _>(alloc, _new_size);
642            new_array.slice_mut()[..split.types_alloc_size()]
643                .clone_from_slice(&split.types.slice()[..split.types_alloc_size()]);
644            <Alloc as Allocator<u8>>::free_cell(
645                alloc,
646                core::mem::replace(&mut split.types, new_array),
647            );
648        }
649    }
650    {
651        if split.lengths_alloc_size() < num_blocks {
652            let mut _new_size: usize = if split.lengths_alloc_size() == 0usize {
653                num_blocks
654            } else {
655                split.lengths_alloc_size()
656            };
657            while _new_size < num_blocks {
658                _new_size = _new_size.wrapping_mul(2);
659            }
660            let mut new_array = allocate::<u32, _>(alloc, _new_size);
661            new_array.slice_mut()[..split.lengths_alloc_size()]
662                .clone_from_slice(split.lengths.slice());
663            <Alloc as Allocator<u32>>::free_cell(
664                alloc,
665                core::mem::replace(&mut split.lengths, new_array),
666            );
667        }
668    }
669    {
670        let mut cur_length: u32 = 0u32;
671        let mut block_idx: usize = 0usize;
672        let mut max_type: u8 = 0u8;
673        for i in 0usize..num_blocks {
674            cur_length = cur_length.wrapping_add(block_lengths.slice()[i]);
675            if i.wrapping_add(1) == num_blocks
676                || histogram_symbols.slice()[i] != histogram_symbols.slice()[i.wrapping_add(1)]
677            {
678                let id: u8 = new_index.slice()[(histogram_symbols.slice()[i] as usize)] as u8;
679                split.types.slice_mut()[block_idx] = id;
680                split.lengths.slice_mut()[block_idx] = cur_length;
681                max_type = max(max_type, id);
682                cur_length = 0u32;
683                block_idx = block_idx.wrapping_add(1);
684            }
685        }
686        split.num_blocks = block_idx;
687        split.num_types = (max_type as usize).wrapping_add(1);
688    }
689    <Alloc as Allocator<u32>>::free_cell(alloc, new_index);
690    <Alloc as Allocator<u32>>::free_cell(alloc, block_lengths);
691    <Alloc as Allocator<u32>>::free_cell(alloc, histogram_symbols);
692}
693
694fn SplitByteVector<
695    HistogramType: SliceWrapper<u32> + SliceWrapperMut<u32> + CostAccessors + core::default::Default + Clone,
696    Alloc: alloc::Allocator<u8>
697        + alloc::Allocator<u16>
698        + alloc::Allocator<u32>
699        + alloc::Allocator<floatX>
700        + alloc::Allocator<Mem256f>
701        + alloc::Allocator<HistogramType>
702        + alloc::Allocator<HistogramPair>,
703    IntegerType: Sized + Clone,
704>(
705    alloc: &mut Alloc,
706    data: &[IntegerType],
707    length: usize,
708    literals_per_histogram: usize,
709    max_histograms: usize,
710    sampling_stride_length: usize,
711    block_switch_cost: floatX,
712    params: &BrotliEncoderParams,
713    scratch_space: &mut HistogramType::i32vec,
714    split: &mut BlockSplit<Alloc>,
715) where
716    u64: core::convert::From<IntegerType>,
717{
718    let data_size: usize = HistogramType::default().slice().len();
719    let mut num_histograms: usize = length.wrapping_div(literals_per_histogram).wrapping_add(1);
720    if num_histograms > max_histograms {
721        num_histograms = max_histograms;
722    }
723    if length == 0usize {
724        split.num_types = 1;
725        return;
726    } else if length < kMinLengthForBlockSplitting {
727        {
728            if split.types_alloc_size() < split.num_blocks.wrapping_add(1) {
729                let mut _new_size: usize = if split.types_alloc_size() == 0usize {
730                    split.num_blocks.wrapping_add(1)
731                } else {
732                    split.types_alloc_size()
733                };
734
735                while _new_size < split.num_blocks.wrapping_add(1) {
736                    _new_size = _new_size.wrapping_mul(2);
737                }
738                let mut new_array = allocate::<u8, _>(alloc, _new_size);
739                new_array.slice_mut()[..split.types_alloc_size()]
740                    .clone_from_slice(&split.types.slice()[..split.types_alloc_size()]);
741                <Alloc as Allocator<u8>>::free_cell(
742                    alloc,
743                    core::mem::replace(&mut split.types, new_array),
744                );
745            }
746        }
747        {
748            if split.lengths_alloc_size() < split.num_blocks.wrapping_add(1) {
749                let mut _new_size: usize = if split.lengths_alloc_size() == 0usize {
750                    split.num_blocks.wrapping_add(1)
751                } else {
752                    split.lengths_alloc_size()
753                };
754                while _new_size < split.num_blocks.wrapping_add(1) {
755                    _new_size = _new_size.wrapping_mul(2);
756                }
757                let mut new_array = allocate::<u32, _>(alloc, _new_size);
758                new_array.slice_mut()[..split.lengths_alloc_size()]
759                    .clone_from_slice(&split.lengths.slice()[..split.lengths_alloc_size()]);
760                <Alloc as Allocator<u32>>::free_cell(
761                    alloc,
762                    core::mem::replace(&mut split.lengths, new_array),
763                );
764            }
765        }
766        split.num_types = 1;
767        split.types.slice_mut()[split.num_blocks] = 0u8;
768        split.lengths.slice_mut()[split.num_blocks] = length as u32;
769        split.num_blocks = split.num_blocks.wrapping_add(1);
770        return;
771    }
772    let mut histograms = allocate::<HistogramType, _>(alloc, num_histograms);
773
774    InitialEntropyCodes(
775        data,
776        length,
777        sampling_stride_length,
778        num_histograms,
779        histograms.slice_mut(),
780    );
781    RefineEntropyCodes(
782        data,
783        length,
784        sampling_stride_length,
785        num_histograms,
786        histograms.slice_mut(),
787    );
788    {
789        let mut block_ids = allocate::<u8, _>(alloc, length);
790        let mut num_blocks: usize = 0usize;
791        let bitmaplen: usize = num_histograms.wrapping_add(7) >> 3;
792        let mut insert_cost = allocate::<floatX, _>(alloc, data_size.wrapping_mul(num_histograms));
793        let mut cost = allocate::<Mem256f, _>(alloc, ((num_histograms + 7) >> 3));
794        let mut switch_signal = allocate::<u8, _>(alloc, length.wrapping_mul(bitmaplen));
795        let mut new_id = allocate::<u16, _>(alloc, num_histograms);
796        let iters: usize = (if params.quality <= 11 { 3i32 } else { 10i32 }) as usize;
797        for _i in 0usize..iters {
798            num_blocks = FindBlocks(
799                data,
800                length,
801                block_switch_cost,
802                num_histograms,
803                histograms.slice_mut(),
804                insert_cost.slice_mut(),
805                cost.slice_mut(),
806                switch_signal.slice_mut(),
807                block_ids.slice_mut(),
808            );
809            num_histograms = RemapBlockIds(
810                block_ids.slice_mut(),
811                length,
812                new_id.slice_mut(),
813                num_histograms,
814            );
815            BuildBlockHistograms(
816                data,
817                length,
818                block_ids.slice(),
819                num_histograms,
820                histograms.slice_mut(),
821            );
822        }
823        <Alloc as Allocator<floatX>>::free_cell(alloc, insert_cost);
824        <Alloc as Allocator<Mem256f>>::free_cell(alloc, cost);
825        <Alloc as Allocator<u8>>::free_cell(alloc, switch_signal);
826        <Alloc as Allocator<u16>>::free_cell(alloc, new_id);
827        <Alloc as Allocator<HistogramType>>::free_cell(alloc, histograms);
828        ClusterBlocks::<HistogramType, Alloc, IntegerType>(
829            alloc,
830            data,
831            length,
832            num_blocks,
833            scratch_space,
834            block_ids.slice_mut(),
835            split,
836        );
837        <Alloc as Allocator<u8>>::free_cell(alloc, block_ids);
838    }
839}
840
841pub fn BrotliSplitBlock<
842    Alloc: alloc::Allocator<u8>
843        + alloc::Allocator<u16>
844        + alloc::Allocator<u32>
845        + alloc::Allocator<floatX>
846        + alloc::Allocator<Mem256f>
847        + alloc::Allocator<HistogramLiteral>
848        + alloc::Allocator<HistogramCommand>
849        + alloc::Allocator<HistogramDistance>
850        + alloc::Allocator<HistogramPair>,
851>(
852    alloc: &mut Alloc,
853    cmds: &[Command],
854    num_commands: usize,
855    data: &[u8],
856    pos: usize,
857    mask: usize,
858    params: &BrotliEncoderParams,
859    lit_scratch_space: &mut <HistogramLiteral as CostAccessors>::i32vec,
860    cmd_scratch_space: &mut <HistogramCommand as CostAccessors>::i32vec,
861    dst_scratch_space: &mut <HistogramDistance as CostAccessors>::i32vec,
862    literal_split: &mut BlockSplit<Alloc>,
863    insert_and_copy_split: &mut BlockSplit<Alloc>,
864    dist_split: &mut BlockSplit<Alloc>,
865) {
866    {
867        /*for (i, cmd) in cmds[..num_commands].iter().enumerate() {
868            println_stderr!("C {:} {:} {:} {:} {:} {:}",
869                            i, cmd.insert_len_, cmd.copy_len_, cmd.dist_extra_, cmd.cmd_prefix_, cmd.dist_prefix_);
870        }*/
871        let literals_count: usize = CountLiterals(cmds, num_commands);
872        let mut literals = allocate::<u8, _>(alloc, literals_count);
873        CopyLiteralsToByteArray(cmds, num_commands, data, pos, mask, literals.slice_mut());
874        SplitByteVector::<HistogramLiteral, Alloc, u8>(
875            alloc,
876            literals.slice(),
877            literals_count,
878            kSymbolsPerLiteralHistogram,
879            kMaxLiteralHistograms,
880            kLiteralStrideLength,
881            kLiteralBlockSwitchCost,
882            params,
883            lit_scratch_space,
884            literal_split,
885        );
886        <Alloc as Allocator<u8>>::free_cell(alloc, literals);
887    }
888    {
889        let mut insert_and_copy_codes = allocate::<u16, _>(alloc, num_commands);
890        for i in 0..min(num_commands, cmds.len()) {
891            insert_and_copy_codes.slice_mut()[i] = (cmds[i]).cmd_prefix_;
892        }
893        SplitByteVector::<HistogramCommand, Alloc, u16>(
894            alloc,
895            insert_and_copy_codes.slice(),
896            num_commands,
897            kSymbolsPerCommandHistogram,
898            kMaxCommandHistograms,
899            kCommandStrideLength,
900            kCommandBlockSwitchCost,
901            params,
902            cmd_scratch_space,
903            insert_and_copy_split,
904        );
905        <Alloc as Allocator<u16>>::free_cell(alloc, insert_and_copy_codes);
906    }
907    {
908        let mut distance_prefixes = allocate::<u16, _>(alloc, num_commands);
909        let mut j: usize = 0usize;
910        for i in 0usize..num_commands {
911            let cmd = &cmds[i];
912            if cmd.copy_len() != 0 && cmd.cmd_prefix_ >= 128 {
913                distance_prefixes.slice_mut()[j] = cmd.dist_prefix_ & 0x03ff;
914                j = j.wrapping_add(1);
915            }
916        }
917        SplitByteVector::<HistogramDistance, Alloc, u16>(
918            alloc,
919            distance_prefixes.slice(),
920            j,
921            kSymbolsPerDistanceHistogram,
922            kMaxCommandHistograms,
923            kCommandStrideLength,
924            kDistanceBlockSwitchCost,
925            params,
926            dst_scratch_space,
927            dist_split,
928        );
929        <Alloc as Allocator<u16>>::free_cell(alloc, distance_prefixes);
930    }
931}