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
#![cfg_attr(not(feature = "std"), allow(unused_imports))]
#[macro_use]
pub mod vectorization;
pub mod backward_references;
pub mod bit_cost;
pub mod block_split;
pub mod brotli_bit_stream;
pub mod cluster;
pub mod combined_alloc;
pub mod command;
pub mod constants;
pub mod dictionary_hash;
pub mod entropy_encode;
pub mod fast_log;
pub mod histogram;
pub mod input_pair;
pub mod literal_cost;
pub mod static_dict;
pub mod static_dict_lut;
pub mod utf8_util;
pub mod util;
pub use self::backward_references::hash_to_binary_tree;
pub use self::backward_references::hq as backward_references_hq;
pub mod block_splitter;
pub mod compress_fragment;
pub mod compress_fragment_two_pass;
pub mod context_map_entropy;
pub mod encode;
pub mod find_stride;
pub mod interface;
pub mod ir_interpret;
pub mod metablock;
pub mod pdf;
pub mod prior_eval;
pub mod reader;
pub mod stride_eval;
pub mod writer;
pub use self::combined_alloc::{BrotliAlloc, CombiningAllocator};
mod compat;
pub mod fixed_queue;
pub mod multithreading;
pub mod singlethreading;
pub mod threading;
pub mod worker_pool;
#[cfg(feature = "simd")]
pub type s16 = core::simd::i16x16;
#[cfg(feature = "simd")]
pub type v8 = core::simd::f32x8;
#[cfg(feature = "simd")]
pub type s8 = core::simd::i32x8;
#[cfg(not(feature = "simd"))]
pub type s16 = compat::Compat16x16;
#[cfg(not(feature = "simd"))]
pub type v8 = compat::CompatF8;
#[cfg(not(feature = "simd"))]
pub type s8 = compat::Compat32x8;

mod parameters;
mod test;
mod weights;
pub use self::backward_references::{BrotliEncoderParams, UnionHasher};
use self::encode::{BrotliEncoderDestroyInstance, BrotliEncoderOperation};
pub use self::encode::{
    BrotliEncoderInitParams, BrotliEncoderMaxCompressedSize, BrotliEncoderMaxCompressedSizeMulti,
};
pub use self::hash_to_binary_tree::ZopfliNode;
pub use self::interface::StaticCommand;
pub use self::pdf::PDF;
pub use self::util::floatX;
pub use self::vectorization::{v256, v256i, Mem256f};
use brotli_decompressor::{CustomRead, CustomWrite};
pub use interface::{InputPair, InputReference, InputReferenceMut};

pub use alloc::{AllocatedStackMemory, Allocator, SliceWrapper, SliceWrapperMut, StackAllocator};
#[cfg(feature = "std")]
pub use alloc_stdlib::StandardAlloc;
#[cfg(feature = "std")]
use std::io;
#[cfg(feature = "std")]
use std::io::{Error, ErrorKind, Read, Write};

#[cfg(feature = "std")]
pub use brotli_decompressor::{IntoIoReader, IoReaderWrapper, IoWriterWrapper};
use enc::encode::BrotliEncoderStateStruct;

#[cfg(not(feature = "std"))]
pub use self::singlethreading::{compress_worker_pool, new_work_pool, WorkerPool};
pub use self::threading::{
    BatchSpawnableLite, BrotliEncoderThreadError, CompressionThreadResult, Owned, SendAlloc,
};
#[cfg(feature = "std")]
pub use self::worker_pool::{compress_worker_pool, new_work_pool, WorkerPool};
#[cfg(feature = "std")]
pub fn compress_multi<
    Alloc: BrotliAlloc + Send + 'static,
    SliceW: SliceWrapper<u8> + Send + 'static + Sync,
>(
    params: &BrotliEncoderParams,
    owned_input: &mut Owned<SliceW>,
    output: &mut [u8],
    alloc_per_thread: &mut [SendAlloc<
        CompressionThreadResult<Alloc>,
        backward_references::UnionHasher<Alloc>,
        Alloc,
        <WorkerPool<
            CompressionThreadResult<Alloc>,
            backward_references::UnionHasher<Alloc>,
            Alloc,
            (SliceW, BrotliEncoderParams),
        > as BatchSpawnableLite<
            CompressionThreadResult<Alloc>,
            backward_references::UnionHasher<Alloc>,
            Alloc,
            (SliceW, BrotliEncoderParams),
        >>::JoinHandle,
    >],
) -> Result<usize, BrotliEncoderThreadError>
where
    <Alloc as Allocator<u8>>::AllocatedMemory: Send,
    <Alloc as Allocator<u16>>::AllocatedMemory: Send + Sync,
    <Alloc as Allocator<u32>>::AllocatedMemory: Send + Sync,
{
    let mut work_pool = self::worker_pool::new_work_pool(alloc_per_thread.len() - 1);
    compress_worker_pool(
        params,
        owned_input,
        output,
        alloc_per_thread,
        &mut work_pool,
    )
}

#[cfg(feature = "std")]
pub use self::multithreading::compress_multi as compress_multi_no_threadpool;
#[cfg(not(feature = "std"))]
pub use self::singlethreading::compress_multi;
#[cfg(not(feature = "std"))]
pub use self::singlethreading::compress_multi as compress_multi_no_threadpool;

#[cfg(feature = "std")]
pub fn BrotliCompress<InputType, OutputType>(
    r: &mut InputType,
    w: &mut OutputType,
    params: &BrotliEncoderParams,
) -> Result<usize, io::Error>
where
    InputType: Read,
    OutputType: Write,
{
    let mut input_buffer: [u8; 4096] = [0; 4096];
    let mut output_buffer: [u8; 4096] = [0; 4096];
    BrotliCompressCustomAlloc(
        r,
        w,
        &mut input_buffer[..],
        &mut output_buffer[..],
        params,
        StandardAlloc::default(),
    )
}

#[cfg(feature = "std")]
pub fn BrotliCompressCustomAlloc<InputType, OutputType, Alloc: BrotliAlloc>(
    r: &mut InputType,
    w: &mut OutputType,
    input_buffer: &mut [u8],
    output_buffer: &mut [u8],
    params: &BrotliEncoderParams,
    alloc: Alloc,
) -> Result<usize, io::Error>
where
    InputType: Read,
    OutputType: Write,
{
    let mut nop_callback = |_data: &mut interface::PredictionModeContextMap<InputReferenceMut>,
                            _cmds: &mut [interface::StaticCommand],
                            _mb: interface::InputPair,
                            _m: &mut Alloc| ();
    BrotliCompressCustomIo(
        &mut IoReaderWrapper::<InputType>(r),
        &mut IoWriterWrapper::<OutputType>(w),
        input_buffer,
        output_buffer,
        params,
        alloc,
        &mut nop_callback,
        Error::new(ErrorKind::UnexpectedEof, "Unexpected EOF"),
    )
}

pub fn BrotliCompressCustomIo<
    ErrType,
    InputType,
    OutputType,
    Alloc: BrotliAlloc,
    MetablockCallback: FnMut(
        &mut interface::PredictionModeContextMap<InputReferenceMut>,
        &mut [interface::StaticCommand],
        interface::InputPair,
        &mut Alloc,
    ),
>(
    r: &mut InputType,
    w: &mut OutputType,
    input_buffer: &mut [u8],
    output_buffer: &mut [u8],
    params: &BrotliEncoderParams,
    alloc: Alloc,
    metablock_callback: &mut MetablockCallback,
    unexpected_eof_error_constant: ErrType,
) -> Result<usize, ErrType>
where
    InputType: CustomRead<ErrType>,
    OutputType: CustomWrite<ErrType>,
{
    BrotliCompressCustomIoCustomDict(
        r,
        w,
        input_buffer,
        output_buffer,
        params,
        alloc,
        metablock_callback,
        &[],
        unexpected_eof_error_constant,
    )
}
pub fn BrotliCompressCustomIoCustomDict<
    ErrType,
    InputType,
    OutputType,
    Alloc: BrotliAlloc,
    MetablockCallback: FnMut(
        &mut interface::PredictionModeContextMap<InputReferenceMut>,
        &mut [interface::StaticCommand],
        interface::InputPair,
        &mut Alloc,
    ),
>(
    r: &mut InputType,
    w: &mut OutputType,
    input_buffer: &mut [u8],
    output_buffer: &mut [u8],
    params: &BrotliEncoderParams,
    alloc: Alloc,
    metablock_callback: &mut MetablockCallback,
    dict: &[u8],
    unexpected_eof_error_constant: ErrType,
) -> Result<usize, ErrType>
where
    InputType: CustomRead<ErrType>,
    OutputType: CustomWrite<ErrType>,
{
    assert!(!input_buffer.is_empty());
    assert!(!output_buffer.is_empty());
    let mut s_orig = BrotliEncoderStateStruct::new(alloc);
    s_orig.params = params.clone();
    if !dict.is_empty() {
        s_orig.set_custom_dictionary(dict.len(), dict);
    }
    let mut next_in_offset: usize = 0;
    let mut next_out_offset: usize = 0;
    let mut total_out = Some(0);
    let mut read_err: Result<(), ErrType> = Ok(());
    {
        let s = &mut s_orig;

        //BrotliEncoderSetParameter(s, BrotliEncoderParameter::BROTLI_PARAM_MODE, 0 as u32); // gen, text, font
        //BrotliEncoderSetParameter(s,
        //                          BrotliEncoderParameter::BROTLI_PARAM_SIZE_HINT,
        //                          input.len() as u32);
        let mut available_in: usize = 0;
        let mut available_out: usize = output_buffer.len();
        let mut eof = false;
        loop {
            if available_in == 0 && !eof {
                next_in_offset = 0;
                match r.read(input_buffer) {
                    Err(e) => {
                        read_err = Err(e);
                        available_in = 0;
                        eof = true;
                    }
                    Ok(size) => {
                        if size == 0 {
                            eof = true;
                        }
                        available_in = size;
                    }
                }
            }
            let op: BrotliEncoderOperation;
            if available_in == 0 {
                op = BrotliEncoderOperation::BROTLI_OPERATION_FINISH;
            } else {
                op = BrotliEncoderOperation::BROTLI_OPERATION_PROCESS;
            }
            let result = s.compress_stream(
                op,
                &mut available_in,
                input_buffer,
                &mut next_in_offset,
                &mut available_out,
                output_buffer,
                &mut next_out_offset,
                &mut total_out,
                metablock_callback,
            );
            let fin = s.is_finished();
            if available_out == 0 || fin {
                let lim = output_buffer.len() - available_out;
                assert_eq!(next_out_offset, lim);
                next_out_offset = 0;
                while next_out_offset < lim {
                    match w.write(&mut output_buffer[next_out_offset..lim]) {
                        Err(e) => {
                            BrotliEncoderDestroyInstance(s);
                            read_err?;
                            return Err(e);
                        }
                        Ok(size) => {
                            next_out_offset += size;
                        }
                    }
                }
                available_out = output_buffer.len();
                next_out_offset = 0;
            }
            if !result {
                if read_err.is_ok() {
                    read_err = Err(unexpected_eof_error_constant);
                }
                break;
            }
            if fin {
                break;
            }
        }
        BrotliEncoderDestroyInstance(s);
    }
    read_err?;
    Ok(total_out.unwrap())
}