brotli 3.3.1

A brotli compressor and decompressor that with an interface avoiding the rust stdlib. This makes it suitable for embedded devices and kernels. It is designed with a pluggable allocator so that the standard lib's allocator may be employed. The default build also includes a stdlib allocator and stream interface. Disable this with --features=no-stdlib. All included code is safe.
Documentation
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
#![cfg(test)]
use core;
use super::{s16, v8};
extern crate alloc_no_stdlib;
extern crate brotli_decompressor;
use super::cluster::HistogramPair;
use super::ZopfliNode;
use super::encode::{BrotliEncoderCreateInstance, BrotliEncoderSetParameter,
                    BrotliEncoderDestroyInstance, BrotliEncoderIsFinished,
                    BrotliEncoderCompressStream, BrotliEncoderParameter, BrotliEncoderOperation};
use super::histogram::{ContextType, HistogramLiteral, HistogramCommand, HistogramDistance};
use super::super::alloc::{AllocatedStackMemory, Allocator, SliceWrapper, SliceWrapperMut,
                          StackAllocator, bzero};
use enc::util::brotli_min_size_t;
use super::StaticCommand;
extern "C" {
  fn calloc(n_elem: usize, el_size: usize) -> *mut u8;
}
extern "C" {
  fn free(ptr: *mut u8);
}
use super::pdf::PDF;
use super::command::Command;
use super::entropy_encode::HuffmanTree;
use super::combined_alloc::CombiningAllocator;
pub use super::super::{BrotliDecompressStream, BrotliResult, BrotliState};
use brotli_decompressor::HuffmanCode;
use core::ops;
use super::interface;

declare_stack_allocator_struct!(MemPool, 128, stack);
declare_stack_allocator_struct!(CallocatedFreelist4096, 128, calloc);
declare_stack_allocator_struct!(CallocatedFreelist2048, 64, calloc);
declare_stack_allocator_struct!(CallocatedFreelist1024, 32, calloc);

fn oneshot_compress(input: &[u8],
                    output: &mut [u8],
                    quality: u32,
                    lgwin: u32,
                    magic: bool,
                    in_batch_size: usize,
                    out_batch_size: usize)
                    -> (i32, usize) {
  let stack_u8_buffer =
    unsafe { define_allocator_memory_pool!(96, u8, [0; 24 * 1024 * 1024], calloc) };
  let stack_u16_buffer =
    unsafe { define_allocator_memory_pool!(96, u16, [0; 128 * 1024], calloc) };
  let stack_i32_buffer =
    unsafe { define_allocator_memory_pool!(96, i32, [0; 128 * 1024], calloc) };
  let stack_u32_buffer =
    unsafe { define_allocator_memory_pool!(96, u32, [0; 32 * 1024 * 1024], calloc) };
  let stack_u64_buffer =
    unsafe { define_allocator_memory_pool!(96, u64, [0; 32 * 1024], calloc) };
  let stack_f64_buffer =
    unsafe { define_allocator_memory_pool!(48, super::util::floatX, [0; 128 * 1024], calloc) };
  let stack_f8_buffer =
    unsafe { define_allocator_memory_pool!(48, v8, [0; 128 * 1024], calloc) };
  let stack_16x16_buffer =
    unsafe { define_allocator_memory_pool!(48, s16, [0; 128 * 1024], calloc) };
  let stack_hl_buffer =
    unsafe { define_allocator_memory_pool!(48, HistogramLiteral, [0; 128 * 1024], calloc) };
  let stack_hc_buffer =
    unsafe { define_allocator_memory_pool!(48, HistogramCommand, [0; 128 * 1024], calloc) };
  let stack_hd_buffer =
    unsafe { define_allocator_memory_pool!(48, HistogramDistance, [0; 128 * 1024], calloc) };
  let stack_hp_buffer =
    unsafe { define_allocator_memory_pool!(48, HistogramPair, [0; 128 * 1024], calloc) };
  let stack_ct_buffer =
    unsafe { define_allocator_memory_pool!(48, ContextType, [0; 128 * 1024], calloc) };
  let stack_ht_buffer =
    unsafe { define_allocator_memory_pool!(48, HuffmanTree, [0; 128 * 1024], calloc) };
  let stack_zn_buffer =
    unsafe { define_allocator_memory_pool!(48, ZopfliNode, [0; 1024], calloc) };
  let stack_mc_buffer =
    unsafe { define_allocator_memory_pool!(48, Command, [0; 128 * 1024], calloc) };
  let stack_pdf_buffer =
    unsafe { define_allocator_memory_pool!(48, PDF, [0; 1], calloc) };
  let stack_sc_buffer =
    unsafe { define_allocator_memory_pool!(48, StaticCommand, [0; 100], calloc) };
  let stack_u8_allocator = CallocatedFreelist4096::<u8>::new_allocator(stack_u8_buffer.data, bzero);
  let stack_u16_allocator = CallocatedFreelist4096::<u16>::new_allocator(stack_u16_buffer.data,
                                                                         bzero);
  let stack_i32_allocator = CallocatedFreelist1024::<i32>::new_allocator(stack_i32_buffer.data,
                                                                         bzero);
  let stack_u32_allocator = CallocatedFreelist4096::<u32>::new_allocator(stack_u32_buffer.data,
                                                                         bzero);
  let stack_u64_allocator = CallocatedFreelist1024::<u64>::new_allocator(stack_u64_buffer.data,
                                                                         bzero);
  let stack_zn_allocator = CallocatedFreelist1024::<ZopfliNode>::new_allocator(stack_zn_buffer.data,
                                                                         bzero);
  let mf64 = CallocatedFreelist2048::<super::util::floatX>::new_allocator(stack_f64_buffer.data, bzero);
  let mf8 = CallocatedFreelist2048::<v8>::new_allocator(stack_f8_buffer.data, bzero);
  let m16x16 = CallocatedFreelist2048::<s16>::new_allocator(stack_16x16_buffer.data, bzero);
  let mpdf = CallocatedFreelist2048::<PDF>::new_allocator(stack_pdf_buffer.data, bzero);
  let msc = CallocatedFreelist2048::<StaticCommand>::new_allocator(stack_sc_buffer.data, bzero);
  let stack_mc_allocator = CallocatedFreelist2048::<Command>::new_allocator(stack_mc_buffer.data,
                                                                            bzero);
  let mhl = CallocatedFreelist2048::<HistogramLiteral>::new_allocator(stack_hl_buffer.data,
                                                                          bzero);
  let mhc = CallocatedFreelist2048::<HistogramCommand>::new_allocator(stack_hc_buffer.data,
                                                                          bzero);
  let mhd = CallocatedFreelist2048::<HistogramDistance>::new_allocator(stack_hd_buffer.data,
                                                                           bzero);
  let mhp = CallocatedFreelist2048::<HistogramPair>::new_allocator(stack_hp_buffer.data, bzero);
  let mct = CallocatedFreelist2048::<ContextType>::new_allocator(stack_ct_buffer.data, bzero);
  let mht = CallocatedFreelist2048::<HuffmanTree>::new_allocator(stack_ht_buffer.data, bzero);
  let mut s_orig = BrotliEncoderCreateInstance(CombiningAllocator::new(
      stack_u8_allocator,
      stack_u16_allocator,
      stack_i32_allocator,
      stack_u32_allocator,
      stack_u64_allocator,
      stack_mc_allocator,
      mf64,
      mf8,
      m16x16,
      mpdf,
     msc,
      mhl,
     mhc,
      mhd,
      mhp,
      mct,
      mht,
     stack_zn_allocator,
  ));
  let mut next_in_offset: usize = 0;
  let mut next_out_offset: usize = 0;
  {
    let s = &mut s_orig;

    BrotliEncoderSetParameter(s,
                              BrotliEncoderParameter::BROTLI_PARAM_QUALITY,
                              quality as (u32));
    if magic {
      BrotliEncoderSetParameter(s,
                                BrotliEncoderParameter::BROTLI_PARAM_MAGIC_NUMBER,
                                magic as (u32));

    }
    if quality >= 10 {
        BrotliEncoderSetParameter(s,
                                  BrotliEncoderParameter::BROTLI_PARAM_Q9_5,
                                  1);
    }
    BrotliEncoderSetParameter(s,
                              BrotliEncoderParameter::BROTLI_PARAM_LGWIN,
                              lgwin as (u32));
    BrotliEncoderSetParameter(s, BrotliEncoderParameter::BROTLI_PARAM_MODE, 0 as (u32)); // gen, text, font
    BrotliEncoderSetParameter(s,
                              BrotliEncoderParameter::BROTLI_PARAM_SIZE_HINT,
                              input.len() as (u32));
    loop {
      let mut available_in: usize = brotli_min_size_t(input.len() - next_in_offset, in_batch_size);
      let mut available_out: usize = brotli_min_size_t(output.len() - next_out_offset,
                                                       out_batch_size);
      if available_out == 0 {
        panic!("No output buffer space");
      }
      let mut total_out = Some(0usize);
      let op: BrotliEncoderOperation;
      if available_in == input.len() - next_in_offset {
        op = BrotliEncoderOperation::BROTLI_OPERATION_FINISH;
      } else {
        op = BrotliEncoderOperation::BROTLI_OPERATION_PROCESS;
      }
      let mut nop_callback = |_data:&mut interface::PredictionModeContextMap<interface::InputReferenceMut>,
                              _cmds: &mut [interface::StaticCommand],
                              _mb: interface::InputPair,
                              _mfv:&mut CombiningAllocator<_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_>|();

      let result = BrotliEncoderCompressStream(s,
                                               op,
                                               &mut available_in,
                                               input,
                                               &mut next_in_offset,
                                               &mut available_out,
                                               output,
                                               &mut next_out_offset,
                                               &mut total_out,
                                               &mut nop_callback);
      if result <= 0 {
        return (result, next_out_offset);
      }
      if BrotliEncoderIsFinished(s) != 0 {
        break;
      }
    }

    BrotliEncoderDestroyInstance(s);
  }

  return (1, next_out_offset);
}

fn oneshot_decompress(compressed: &[u8], mut output: &mut [u8]) -> (BrotliResult, usize, usize) {
  let mut available_in: usize = compressed.len();
  let mut available_out: usize = output.len();
  let mut stack_u8_buffer = define_allocator_memory_pool!(128, u8, [0; 100 * 1024], stack);
  let mut stack_u32_buffer = define_allocator_memory_pool!(128, u32, [0; 36 * 1024], stack);
  let mut stack_hc_buffer = define_allocator_memory_pool!(128,
                                                          HuffmanCode,
                                                          [HuffmanCode::default(); 116 * 1024],
                                                          stack);

  let stack_u8_allocator = MemPool::<u8>::new_allocator(&mut stack_u8_buffer, bzero);
  let stack_u32_allocator = MemPool::<u32>::new_allocator(&mut stack_u32_buffer, bzero);
  let stack_hc_allocator = MemPool::<HuffmanCode>::new_allocator(&mut stack_hc_buffer, bzero);
  let mut input_offset: usize = 0;
  let mut output_offset: usize = 0;
  let mut written: usize = 0;
  let mut brotli_state =
    BrotliState::new(stack_u8_allocator, stack_u32_allocator, stack_hc_allocator);
  let result = BrotliDecompressStream(&mut available_in,
                                      &mut input_offset,
                                      &compressed[..],
                                      &mut available_out,
                                      &mut output_offset,
                                      &mut output,
                                      &mut written,
                                      &mut brotli_state);
  return (result, input_offset, output_offset);

}

fn oneshot(input: &[u8],
           compressed: &mut [u8],
           output: &mut [u8],
           q: u32,
           lg: u32,
           magic: bool,
           in_buffer_size: usize,
           out_buffer_size: usize)
           -> (BrotliResult, usize, usize) {
  let (success, mut available_in) =
    oneshot_compress(input, compressed, q, lg, magic, in_buffer_size, out_buffer_size);
  if success == 0 {
    //return (BrotliResult::ResultFailure, 0, 0);
    available_in = compressed.len();
  }
  return oneshot_decompress(&mut compressed[..available_in], output);
}

#[test]
fn test_roundtrip_10x10y() {
  const BUFFER_SIZE: usize = 128;
  let mut compressed: [u8; 13] = [0; 13];
  let mut output = [0u8; BUFFER_SIZE];
  let mut input = ['x' as u8, 'x' as u8, 'x' as u8, 'x' as u8, 'x' as u8, 'x' as u8, 'x' as u8,
                   'x' as u8, 'x' as u8, 'x' as u8, 'y' as u8, 'y' as u8, 'y' as u8, 'y' as u8,
                   'y' as u8, 'y' as u8, 'y' as u8, 'y' as u8, 'y' as u8, 'y' as u8];
  let (result, compressed_offset, output_offset) = oneshot(&mut input[..],
                                                           &mut compressed,
                                                           &mut output[..],
                                                           9,
                                                           10,
                                                           false,
                                                           1,
                                                           1);
  match result {
    BrotliResult::ResultSuccess => {}
    _ => assert!(false),
  }
  let mut i: usize = 0;
  while i < 10 {
    assert_eq!(output[i], 'x' as u8);
    assert_eq!(output[i + 10], 'y' as u8);
    i += 1;
  }
  assert_eq!(output_offset, 20);
  assert_eq!(compressed_offset, compressed.len());
}

macro_rules! test_roundtrip_file {
  ($filedata : expr, $bufsize: expr, $quality: expr, $lgwin: expr, $magic: expr, $in_buf:expr, $out_buf:expr) => {{
    let stack_u8_buffer = unsafe{define_allocator_memory_pool!(4096, u8, [0; 18 * 1024 * 1024], calloc)};
    let mut stack_u8_allocator = CallocatedFreelist4096::<u8>::new_allocator(stack_u8_buffer.data, bzero);

    let mut compressed = stack_u8_allocator.alloc_cell($bufsize);
    let inp = $filedata;
    let mut output = stack_u8_allocator.alloc_cell(inp.len() + 16);
    let (result, compressed_offset, output_offset) = oneshot(&inp[..],
                                                          compressed.slice_mut(),
                                                             output.slice_mut(),
                                                             $quality,
                                                             $lgwin,
                                                             $magic,
                                                             $in_buf,
                                                             $out_buf);
    match result {
      BrotliResult::ResultSuccess => {}
      _ => assert!(false),
    }
    for i in 0..inp.len() {
        if inp[i] != output[i] {
            assert_eq!((i,inp[i]), (i,output[i]));
        }
        assert_eq!(inp[i], output[i]);
    }
    assert!(compressed_offset <= compressed.slice().len());
    assert_eq!(output_offset, inp.len());
    stack_u8_allocator.free_cell(output);
    stack_u8_allocator.free_cell(compressed);
  }};
}

#[test]
fn test_roundtrip_64x() {
  test_roundtrip_file!(include_bytes!("../../testdata/64x"), 72, 9, 10, false, 3, 2);
}
#[test]
fn test_roundtrip_ukkonooa() {
  test_roundtrip_file!(include_bytes!("../../testdata/ukkonooa"), 82, 9, 10, true, 3, 2);
}
#[test]
fn test_roundtrip_backward65536() {
  test_roundtrip_file!(include_bytes!("../../testdata/backward65536"), 72000, 9, 10, false, 3, 2);
}
#[test]
fn test_roundtrip_aaabaaaa() {
  test_roundtrip_file!(include_bytes!("../../testdata/aaabaaaa"), 72000, 9, 10, true, 3, 2);
}
#[test]
fn test_roundtrip_monkey() {
  test_roundtrip_file!(include_bytes!("../../testdata/monkey"), 72000, 9, 10, false, 16, 15);
}
#[test]
fn test_roundtrip_quickfox_repeated() {
  test_roundtrip_file!(include_bytes!("../../testdata/quickfox_repeated"), 16384, 9, 10, true, 257, 255);
}

#[test]
fn test_roundtrip_asyoulik() {
  test_roundtrip_file!(include_bytes!("../../testdata/asyoulik.txt"), 64384, 9, 15, false, 513, 511);
}

#[test]
fn test_roundtrip_asyoulik9_5() {
  test_roundtrip_file!(include_bytes!("../../testdata/asyoulik.txt"), 62384, 10, 15, true, 513, 511);
}

#[test]
fn test_roundtrip_compressed() {
  test_roundtrip_file!(include_bytes!("../../testdata/compressed_file"), 50400, 9, 10, false, 1025, 1024);
}

#[test]
fn test_roundtrip_compressed_repeated() {
  test_roundtrip_file!(include_bytes!("../../testdata/compressed_repeated"),
                       120000,
                       9,
                       16,
                       false,
                       2049,
                       2047);
}

#[test]
fn test_roundtrip_first_58_bytes_alice() {
  test_roundtrip_file!(&include_bytes!("../../testdata/alice29.txt")[..58], 50400, 2, 10, true, 1, 2);
}
#[test]
fn test_roundtrip_first_2_bytes_alice() {
  test_roundtrip_file!(&include_bytes!("../../testdata/alice29.txt")[..2], 50400, 2, 10, true, 1, 2);
}


#[test]
fn test_roundtrip_quickfox() {
  test_roundtrip_file!(include_bytes!("../../testdata/quickfox"), 256, 9, 10, false, 1, 2);
}


#[test]
fn test_roundtrip_x() {
  const BUFFER_SIZE: usize = 16384;
  let mut compressed: [u8; 6] = [0x0b, 0x00, 0x80, 0x58, 0x03, 0];
  let mut output = [0u8; BUFFER_SIZE];
  let mut input = ['X' as u8];
  let (result, compressed_offset, output_offset) = oneshot(&mut input[..],
                                                           &mut compressed[..],
                                                           &mut output[..],
                                                           9,
                                                           10,
                                                           false,
                                                           1,
                                                           2);
  match result {
    BrotliResult::ResultSuccess => {}
    _ => assert!(false),
  }
  assert_eq!(output[0], 'X' as u8);
  assert_eq!(output_offset, 1);
  assert_eq!(compressed_offset, compressed.len());
}

#[test]
fn test_roundtrip_empty() {
  let mut compressed: [u8; 2] = [0x06, 0];
  let mut output = [0u8; 1];
  let (result, compressed_offset, output_offset) =
    oneshot(&mut [], &mut compressed[..], &mut output[..], 9, 10, false, 2, 3);
  match result {
    BrotliResult::ResultSuccess => {}
    _ => assert!(false),
  }
  assert_eq!(output_offset, 0);
  assert_eq!(compressed_offset, compressed.len());
}
/*


#[cfg(feature="std")]
struct Buffer {
  data: Vec<u8>,
  read_offset: usize,
}
#[cfg(feature="std")]
impl Buffer {
  pub fn new(buf: &[u8]) -> Buffer {
    let mut ret = Buffer {
      data: Vec::<u8>::new(),
      read_offset: 0,
    };
    ret.data.extend(buf);
    return ret;
  }
}
#[cfg(feature="std")]
impl io::Read for Buffer {
  fn read(self: &mut Self, buf: &mut [u8]) -> io::Result<usize> {
    let bytes_to_read = ::core::cmp::min(buf.len(), self.data.len() - self.read_offset);
    if bytes_to_read > 0 {
      buf[0..bytes_to_read]
        .clone_from_slice(&self.data[self.read_offset..self.read_offset + bytes_to_read]);
    }
    self.read_offset += bytes_to_read;
    return Ok(bytes_to_read);
  }
}
#[cfg(feature="std")]
impl io::Write for Buffer {
  fn write(self: &mut Self, buf: &[u8]) -> io::Result<usize> {
    self.data.extend(buf);
    return Ok(buf.len());
  }
  fn flush(self: &mut Self) -> io::Result<()> {
    return Ok(());
  }
}


*/