#![cfg(test)]
#![cfg(feature = "std")]
use super::*;
use crate::memory::{try_alloc_cell, SliceWrapper};
use alloc_stdlib::StandardAlloc;
use core::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone, Copy)]
enum PanicIn {
Caller,
Worker,
Neither,
}
struct PanickingSlice {
caller: std::thread::ThreadId,
panic_in: PanicIn,
started_workers: AtomicUsize,
}
impl PanickingSlice {
fn new(panic_in: PanicIn) -> Self {
Self {
caller: std::thread::current().id(),
panic_in,
started_workers: AtomicUsize::new(0),
}
}
}
impl SliceWrapper<u8> for PanickingSlice {
fn len(&self) -> usize {
if std::thread::current().id() == self.caller {
assert!(!matches!(self.panic_in, PanicIn::Caller), "caller panic");
} else {
let started = self.started_workers.fetch_add(1, Ordering::SeqCst);
if started == 0 && matches!(self.panic_in, PanicIn::Worker) {
panic!("worker panic");
}
}
self.slice().len()
}
fn slice(&self) -> &[u8] {
b"test input across multiple jobs"
}
}
#[test]
fn pool_drains_jobs_after_caller_or_worker_panics() {
let params = BrotliEncoderParams {
quality: 5,
favor_cpu_efficiency: false,
..Default::default()
};
let mut pool = crate::enc::new_work_pool(1);
for panic_in in [PanicIn::Caller, PanicIn::Worker, PanicIn::Neither] {
let mut input = Owned::new(PanickingSlice::new(panic_in));
let mut output = [0; 256];
let mut allocators =
[0; 3].map(|_| SendAlloc::new(StandardAlloc::default(), UnionHasher::Uninit));
let result = CompressMulti(¶ms, &mut input, &mut output, &mut allocators, &mut pool);
match panic_in {
PanicIn::Neither => assert!(result.unwrap() > 0),
_ => assert!(matches!(
result,
Err(BrotliEncoderThreadError::ThreadExecError(_))
)),
}
assert_eq!(input.view().started_workers.load(Ordering::SeqCst), 2);
}
}
#[test]
fn pool_survives_reusing_slots_after_worker_panic() {
let params = BrotliEncoderParams {
quality: 5,
favor_cpu_efficiency: false,
..Default::default()
};
let mut pool = crate::enc::new_work_pool(1);
let mut allocators =
[0; 3].map(|_| SendAlloc::new(StandardAlloc::default(), UnionHasher::Uninit));
for panic_in in [PanicIn::Worker, PanicIn::Neither] {
let mut input = Owned::new(PanickingSlice::new(panic_in));
let mut output = [0; 256];
let result = CompressMulti(¶ms, &mut input, &mut output, &mut allocators, &mut pool);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::ThreadExecError(_))
));
input.view();
}
for slot in &mut allocators {
if !matches!(slot.0, InternalSendAlloc::A(..)) {
*slot = SendAlloc::new(StandardAlloc::default(), UnionHasher::Uninit);
}
}
let mut input = Owned::new(PanickingSlice::new(PanicIn::Neither));
let mut output = [0; 256];
let result = CompressMulti(¶ms, &mut input, &mut output, &mut allocators, &mut pool);
assert!(result.unwrap() > 0);
}
#[test]
fn dedicated_worker_panic_is_a_join_error() {
let params = BrotliEncoderParams {
quality: 5,
favor_cpu_efficiency: false,
..Default::default()
};
let mut input = Owned::new(PanickingSlice::new(PanicIn::Worker));
let mut output = [0; 256];
let mut allocators =
[0; 3].map(|_| SendAlloc::new(StandardAlloc::default(), UnionHasher::Uninit));
let result =
crate::enc::compress_multi_no_threadpool(¶ms, &mut input, &mut output, &mut allocators);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::ThreadExecError(_))
));
assert_eq!(input.view().started_workers.load(Ordering::SeqCst), 2);
}
#[test]
fn dropping_unjoined_pool_job_aborts() {
const CHILD: &str = "BROTLI_UNJOINED_WORKER_TEST";
if std::env::var_os(CHILD).is_some() {
let mut pool = crate::enc::worker_pool::WorkerPool::<(), (), StandardAlloc, ()>::new(1);
let mut input = pool.make_spawner(&mut Owned::new(()));
let mut work = SendAlloc::new(StandardAlloc::default(), ());
pool.spawn(&mut input, &mut work, 0, 1, |_, _, _, _, _| ());
std::eprintln!("dropping unjoined worker handle");
drop(work);
std::process::exit(0);
}
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(&[
"--exact",
"enc::threading::test::dropping_unjoined_pool_job_aborts",
"--nocapture",
])
.env(CHILD, "1")
.output()
.unwrap();
assert!(!child.status.success());
assert_ne!(child.status.code(), Some(101));
#[cfg(unix)]
assert!(child.status.code().is_none(), "{:?}", child.status);
assert!(std::string::String::from_utf8_lossy(&child.stderr)
.contains("dropping unjoined worker handle"));
}
#[test]
fn pool_oom_remains_recoverable() {
let mut pool = crate::enc::new_work_pool(1);
for (favor_cpu_efficiency, failed_worker) in [(false, 0), (false, 1), (true, 1)] {
let params = BrotliEncoderParams {
quality: 5,
favor_cpu_efficiency,
..Default::default()
};
let mut input = Owned::new(TestSlice(b"test input"));
let mut output = [0; 256];
let mut allocators = [0, 1].map(|worker| {
let fail_at = usize::from(worker == failed_worker);
let alloc = if favor_cpu_efficiency {
ShortAllocator::new::<u32>(fail_at)
} else {
ShortAllocator::new::<u8>(fail_at)
};
SendAlloc::new(alloc, UnionHasher::Uninit)
});
let result = CompressMulti(¶ms, &mut input, &mut output, &mut allocators, &mut pool);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(input.view().slice(), b"test input");
for allocator in &mut allocators {
assert_eq!(allocator.unwrap_view_mut().0.live_allocations, 0);
}
}
}
static JOINED_AFTER_JOIN_ERROR: AtomicUsize = AtomicUsize::new(0);
static JOINED_AFTER_SETUP_ERROR: AtomicUsize = AtomicUsize::new(0);
static DRAINED_AFTER_STREAM_PHASE: AtomicUsize = AtomicUsize::new(0);
struct TestSlice(&'static [u8]);
impl SliceWrapper<u8> for TestSlice {
fn slice(&self) -> &[u8] {
self.0
}
}
#[derive(Default)]
struct MissingOutputAllocator {
allocations: usize,
}
impl<T: Clone + Default> Allocator<T> for MissingOutputAllocator {
type AllocatedMemory = <StandardAlloc as Allocator<T>>::AllocatedMemory;
fn alloc_cell(&mut self, len: usize) -> Self::AllocatedMemory {
self.allocations += 1;
if self.allocations == 1 {
Self::AllocatedMemory::default()
} else {
try_alloc_cell::<T, _>(&mut StandardAlloc::default(), len).unwrap()
}
}
fn free_cell(&mut self, memory: Self::AllocatedMemory) {
assert!(!memory.slice().is_empty());
StandardAlloc::default().free_cell(memory);
}
}
impl BrotliAlloc for MissingOutputAllocator {}
#[test]
fn compress_part_rejects_missing_output_buffer() {
let input = (TestSlice(b"test input"), BrotliEncoderParams::default());
let result = compress_part(
UnionHasher::Uninit,
0,
1,
&input,
MissingOutputAllocator::default(),
);
assert!(matches!(
result.compressed,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(result.alloc.allocations, 1);
}
struct ShortAllocator {
allocation_type: core::any::TypeId,
fail_at: usize,
matching_allocations: usize,
live_allocations: usize,
}
impl ShortAllocator {
fn new<T: 'static>(fail_at: usize) -> Self {
Self {
allocation_type: core::any::TypeId::of::<T>(),
fail_at,
matching_allocations: 0,
live_allocations: 0,
}
}
}
impl<T: Clone + Default + 'static> Allocator<T> for ShortAllocator {
type AllocatedMemory = <StandardAlloc as Allocator<T>>::AllocatedMemory;
fn alloc_cell(&mut self, mut len: usize) -> Self::AllocatedMemory {
if len != 0 && core::any::TypeId::of::<T>() == self.allocation_type {
self.matching_allocations += 1;
if self.matching_allocations == self.fail_at {
len -= 1;
}
}
if len != 0 {
self.live_allocations += 1;
}
try_alloc_cell::<T, _>(&mut StandardAlloc::default(), len).unwrap()
}
fn free_cell(&mut self, memory: Self::AllocatedMemory) {
if !memory.slice().is_empty() {
self.live_allocations -= 1;
}
StandardAlloc::default().free_cell(memory);
}
}
impl BrotliAlloc for ShortAllocator {}
#[test]
fn compress_multi_slice_rejects_short_input_copy() {
let mut allocators = [SendAlloc::new(
ShortAllocator::new::<u8>(1),
UnionHasher::Uninit,
)];
let result = CompressMultiSlice(
&BrotliEncoderParams::default(),
b"test input",
&mut [0; 256],
&mut allocators,
&mut crate::enc::singlethreading::SingleThreadedSpawner::default(),
);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(allocators[0].unwrap_view_mut().0.live_allocations, 0);
}
#[test]
fn compress_part_rejects_short_fast_encoder_buffers() {
use crate::enc::entropy_encode::HuffmanTree;
fn check<T: 'static>(quality: i32, worker: usize, fail_at: usize) {
let input = (
TestSlice(include_bytes!("../../../testdata/alice29.txt")),
BrotliEncoderParams {
quality,
..Default::default()
},
);
let result = compress_part(
UnionHasher::Uninit,
worker,
2,
&input,
ShortAllocator::new::<T>(fail_at),
);
assert!(
matches!(
result.compressed,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
),
"quality {}, worker {}, type {}, allocation {}",
quality,
worker,
core::any::type_name::<T>(),
fail_at
);
assert_eq!(result.alloc.matching_allocations, fail_at);
assert_eq!(result.alloc.live_allocations, 0);
}
for worker in 0..2 {
for quality in 0..=1 {
check::<i32>(quality, worker, 1); }
check::<u32>(1, worker, 1); check::<u8>(1, worker, if worker == 0 { 2 } else { 4 }); for quality in 0..=2 {
check::<HuffmanTree>(quality, worker, 1);
}
}
}
#[test]
fn compress_part_rejects_short_encoder_storage() {
for quality in [1, 11] {
let input = (
TestSlice(&[b'a'; 1024]),
BrotliEncoderParams {
quality,
..Default::default()
},
);
let result = compress_part(
UnionHasher::Uninit,
0,
1,
&input,
ShortAllocator::new::<u8>(3),
);
assert!(
matches!(
result.compressed,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
),
"quality {}",
quality
);
assert_eq!(result.alloc.matching_allocations, 3);
assert_eq!(result.alloc.live_allocations, 0);
}
}
#[test]
fn compress_part_rejects_short_ring_and_command_buffers() {
use crate::enc::command::Command;
fn check<T: 'static>(worker: usize, fail_at: usize) {
let input = (TestSlice(&[b'a'; 1024]), BrotliEncoderParams::default());
let result = compress_part(
UnionHasher::Uninit,
worker,
2,
&input,
ShortAllocator::new::<T>(fail_at),
);
assert!(matches!(
result.compressed,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(result.alloc.matching_allocations, fail_at);
assert_eq!(result.alloc.live_allocations, 0);
}
check::<u8>(0, 2); check::<u8>(1, 2); check::<u8>(1, 3); check::<Command>(0, 1);
check::<Command>(1, 1);
}
fn assert_hasher_allocation_failure<T: 'static>(
params: &BrotliEncoderParams,
num_threads: usize,
failing_worker: usize,
fail_at: usize,
) {
static INPUT: &[u8] = &[b'a'; 1024];
let mut input = Owned::new(TestSlice(INPUT));
let mut output = [0; 4096];
let mut allocators: std::vec::Vec<_> = (0..num_threads)
.map(|worker| {
SendAlloc::new(
ShortAllocator::new::<T>(if worker == failing_worker { fail_at } else { 0 }),
UnionHasher::Uninit,
)
})
.collect();
let result =
crate::enc::compress_multi_no_threadpool(params, &mut input, &mut output, &mut allocators);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(input.view().slice(), INPUT);
for allocator in &mut allocators {
assert_eq!(allocator.unwrap_view_mut().0.live_allocations, 0);
}
}
fn assert_h10_allocation_failure(
num_threads: usize,
favor_cpu_efficiency: bool,
failing_worker: usize,
fail_at: usize,
) {
let params = BrotliEncoderParams {
lgwin: 10,
favor_cpu_efficiency,
..Default::default()
};
assert_hasher_allocation_failure::<u32>(¶ms, num_threads, failing_worker, fail_at);
}
#[test]
fn compress_multi_rejects_short_basic_hasher_allocations() {
for (quality, size_hint) in [(2, 0), (3, 0), (4, 0), (4, 1 << 20)] {
let mut params = BrotliEncoderParams {
quality,
size_hint,
..Default::default()
};
assert_hasher_allocation_failure::<u32>(¶ms, 2, 0, 1);
assert_hasher_allocation_failure::<u32>(¶ms, 2, 1, 1);
params.favor_cpu_efficiency = true;
assert_hasher_allocation_failure::<u32>(¶ms, 2, 1, 1);
assert_hasher_allocation_failure::<u32>(¶ms, 3, 1, 1);
}
}
#[test]
fn compress_multi_rejects_short_advanced_hasher_allocations() {
fn check<T: 'static>(quality: i32, size_hint: usize) {
let mut params = BrotliEncoderParams {
quality,
size_hint,
..Default::default()
};
assert_hasher_allocation_failure::<T>(¶ms, 2, 0, 1); assert_hasher_allocation_failure::<T>(¶ms, 2, 1, 1); params.favor_cpu_efficiency = true;
assert_hasher_allocation_failure::<T>(¶ms, 2, 1, 1); assert_hasher_allocation_failure::<T>(¶ms, 3, 1, 1); if cfg!(debug_assertions) {
assert_hasher_allocation_failure::<T>(¶ms, 2, 1, 2); }
}
for (quality, size_hint) in [(5, 0), (7, 0), (8, 0), (8, (1 << 22) + 1)] {
check::<u16>(quality, size_hint);
check::<u32>(quality, size_hint);
}
}
#[test]
fn compress_multi_rejects_short_h9_allocations() {
fn check<T: 'static>() {
let mut params = BrotliEncoderParams {
quality: 10,
q9_5: true,
lgwin: 10,
..Default::default()
};
assert_hasher_allocation_failure::<T>(¶ms, 2, 1, 1); assert_hasher_allocation_failure::<T>(¶ms, 2, 0, 1); params.favor_cpu_efficiency = true;
assert_hasher_allocation_failure::<T>(¶ms, 2, 1, 1); assert_hasher_allocation_failure::<T>(¶ms, 3, 1, 1); if cfg!(debug_assertions) {
assert_hasher_allocation_failure::<T>(¶ms, 2, 1, 2); }
}
check::<u16>(); check::<u32>(); }
#[test]
fn compress_multi_rejects_short_h10_bucket_allocations() {
assert_h10_allocation_failure(2, false, 0, 1); assert_h10_allocation_failure(2, false, 1, 1); assert_h10_allocation_failure(2, true, 1, 1); assert_h10_allocation_failure(3, true, 1, 1); if cfg!(debug_assertions) {
assert_h10_allocation_failure(2, true, 1, 3); }
}
#[test]
fn compress_multi_rejects_short_h10_forest_allocations() {
assert_h10_allocation_failure(2, false, 0, 2); assert_h10_allocation_failure(2, false, 1, 2); assert_h10_allocation_failure(2, true, 1, 2); assert_h10_allocation_failure(3, true, 1, 2); if cfg!(debug_assertions) {
assert_h10_allocation_failure(2, true, 1, 4); }
}
#[test]
fn compress_multi_propagates_zopfli_allocation_failure() {
use crate::enc::hash_to_binary_tree::ZopfliNode;
static INPUT: &[u8] = &[b'a'; 1024];
for quality in [10, 11] {
let params = BrotliEncoderParams {
quality,
lgwin: 10,
..Default::default()
};
let mut input = Owned::new(TestSlice(INPUT));
let mut allocators = [
SendAlloc::new(ShortAllocator::new::<ZopfliNode>(0), UnionHasher::Uninit),
SendAlloc::new(ShortAllocator::new::<ZopfliNode>(1), UnionHasher::Uninit),
];
let result = crate::enc::compress_multi_no_threadpool(
¶ms,
&mut input,
&mut [], &mut allocators,
);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(input.view().slice(), INPUT);
for allocator in &mut allocators {
assert_eq!(allocator.unwrap_view_mut().0.live_allocations, 0);
}
}
}
#[test]
fn compress_multi_rejects_short_block_id_remap_buffer() {
static INPUT: &[u8] = include_bytes!("../../../testdata/alice29.txt");
let params = BrotliEncoderParams::default();
let mut output = std::vec![0; crate::enc::BrotliEncoderMaxCompressedSizeMulti(INPUT.len(), 2)];
for failed_worker in 0..2 {
let mut input = Owned::new(TestSlice(INPUT));
let mut allocators = [0, 1].map(|worker| {
SendAlloc::new(
ShortAllocator::new::<u16>(usize::from(worker == failed_worker)),
UnionHasher::Uninit,
)
});
let result = crate::enc::compress_multi_no_threadpool(
¶ms,
&mut input,
&mut output,
&mut allocators,
);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(input.view().slice(), INPUT);
assert_eq!(
allocators[failed_worker]
.unwrap_view_mut()
.0
.matching_allocations,
1
);
for allocator in &mut allocators {
assert_eq!(allocator.unwrap_view_mut().0.live_allocations, 0);
}
}
}
#[test]
fn compress_part_propagates_meta_block_allocation_failures() {
use crate::enc::cluster::HistogramPair;
use crate::enc::entropy_encode::HuffmanTree;
use crate::enc::histogram::{ContextType, HistogramCommand};
fn check<T: 'static>(quality: i32, input: &'static [u8]) {
let input = (
TestSlice(input),
BrotliEncoderParams {
quality,
..Default::default()
},
);
let result = compress_part(
UnionHasher::Uninit,
0,
1,
&input,
ShortAllocator::new::<T>(1),
);
assert!(matches!(
result.compressed,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(result.alloc.matching_allocations, 1);
assert_eq!(result.alloc.live_allocations, 0);
}
let alice = &include_bytes!("../../../testdata/alice29.txt")[..8192];
check::<HistogramCommand>(4, alice); check::<HistogramPair>(10, alice); check::<ContextType>(11, alice); check::<HuffmanTree>(11, alice);
check::<HistogramPair>(11, &[b'a'; 1024]);
}
#[test]
fn compress_part_rejects_short_huffman_code_tables() {
static INPUT: &[u8] = include_bytes!("../../../testdata/alice29.txt");
let input = (TestSlice(INPUT), BrotliEncoderParams::default());
let compress = |fail_at| {
compress_part(
UnionHasher::Uninit,
1,
2,
&input,
ShortAllocator::new::<u16>(fail_at),
)
};
let mut baseline = compress(0);
let output = baseline.compressed.expect("baseline compression failed");
baseline.alloc.free_cell(output.data_backing);
assert_eq!(baseline.alloc.live_allocations, 0);
let allocations = baseline.alloc.matching_allocations;
assert!(allocations >= 3);
for fail_at in allocations - 2..=allocations {
let result = compress(fail_at);
assert!(matches!(
result.compressed,
Err(BrotliEncoderThreadError::InsufficientOutputSpace)
));
assert_eq!(result.alloc.matching_allocations, fail_at);
assert_eq!(result.alloc.live_allocations, 0);
}
}
#[test]
fn one_shot_compression_propagates_allocation_failure() {
use crate::enc::backward_references::BrotliEncoderMode;
use crate::enc::encode::encoder_compress;
use crate::enc::hash_to_binary_tree::ZopfliNode;
fn check<T: 'static>(quality: i32) {
let input = [b'a'; 1024];
let mut output = [0; 4096];
let mut output_len = output.len();
let mut alloc = ShortAllocator::new::<T>(1);
assert!(!encoder_compress(
ShortAllocator::new::<T>(0),
&mut alloc,
quality,
10,
BrotliEncoderMode::BROTLI_MODE_GENERIC,
input.len(),
&input,
&mut output_len,
&mut output,
&mut |_, _, _, _| (),
));
assert_eq!(output_len, 0);
assert_eq!(alloc.matching_allocations, 1);
assert_eq!(alloc.live_allocations, 0);
}
check::<ZopfliNode>(11);
check::<u16>(10);
check::<u32>(10);
}
#[test]
fn std_io_propagates_out_of_memory() {
use crate::enc::hash_to_binary_tree::ZopfliNode;
use crate::enc::reader::CompressorReaderCustomAlloc;
use crate::enc::writer::CompressorWriterCustomAlloc;
use std::io::{ErrorKind, Read, Write};
use std::vec::Vec;
let input = [b'a'; 1024];
let params = BrotliEncoderParams {
quality: 11,
lgwin: 10,
..Default::default()
};
let mut output = Vec::new();
let error = crate::BrotliCompressCustomAlloc(
&mut &input[..],
&mut output,
&mut [0; 1024],
&mut [0; 1024],
¶ms,
ShortAllocator::new::<ZopfliNode>(1),
)
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::OutOfMemory);
assert!(output.is_empty());
let mut reader = CompressorReaderCustomAlloc::new(
&input[..],
try_alloc_cell::<u8, _>(&mut StandardAlloc::default(), 1024).unwrap(),
ShortAllocator::new::<ZopfliNode>(1),
11,
10,
);
for _ in 0..2 {
assert_eq!(
reader.read(&mut [0; 1024]).unwrap_err().kind(),
ErrorKind::OutOfMemory
);
}
let mut writer = CompressorWriterCustomAlloc::new(
Vec::new(),
try_alloc_cell::<u8, _>(&mut StandardAlloc::default(), 1024).unwrap(),
ShortAllocator::new::<ZopfliNode>(1),
11,
10,
);
writer.write_all(&input).unwrap();
assert_eq!(writer.flush().unwrap_err().kind(), ErrorKind::OutOfMemory);
assert_eq!(writer.finish().unwrap_err().kind(), ErrorKind::OutOfMemory);
}
struct CountingJoinable {
result: Option<Result<CompressionThreadResult<StandardAlloc>, BrotliEncoderThreadError>>,
joined_count: &'static AtomicUsize,
}
impl Joinable<CompressionThreadResult<StandardAlloc>, BrotliEncoderThreadError>
for CountingJoinable
{
fn join(mut self) -> Result<CompressionThreadResult<StandardAlloc>, BrotliEncoderThreadError> {
self.joined_count.fetch_add(1, Ordering::SeqCst);
self.result.take().unwrap()
}
}
struct TestOwnedRetriever<U: Send + 'static> {
input: Option<U>,
fail_views: bool,
}
impl<U: Send + 'static> OwnedRetriever<U> for TestOwnedRetriever<U> {
fn view<Output, Func: FnOnce(&U) -> Output>(
&self,
func: Func,
) -> Result<Output, PoisonedThreadError> {
if self.fail_views {
Err(PoisonedThreadError::default())
} else {
Ok(func(self.input.as_ref().unwrap()))
}
}
fn unwrap(self) -> Result<U, PoisonedThreadError> {
Ok(self.input.unwrap())
}
}
struct CountingSpawner {
joined_count: &'static AtomicUsize,
join_error_index: Option<usize>,
fail_views: bool,
}
impl
BatchSpawnableLite<
CompressionThreadResult<StandardAlloc>,
UnionHasher<StandardAlloc>,
StandardAlloc,
(TestSlice, BrotliEncoderParams),
> for CountingSpawner
{
type JoinHandle = CountingJoinable;
type FinalJoinHandle = TestOwnedRetriever<(TestSlice, BrotliEncoderParams)>;
fn make_spawner(
&mut self,
input: &mut Owned<(TestSlice, BrotliEncoderParams)>,
) -> Self::FinalJoinHandle {
TestOwnedRetriever {
input: Some(mem::replace(input, Owned(InternalOwned::Borrowed)).unwrap()),
fail_views: self.fail_views,
}
}
fn spawn(
&mut self,
_handle: &mut Self::FinalJoinHandle,
alloc_per_thread: &mut SendAlloc<
CompressionThreadResult<StandardAlloc>,
UnionHasher<StandardAlloc>,
StandardAlloc,
Self::JoinHandle,
>,
index: usize,
_num_threads: usize,
_func: fn(
UnionHasher<StandardAlloc>,
usize,
usize,
&(TestSlice, BrotliEncoderParams),
StandardAlloc,
) -> CompressionThreadResult<StandardAlloc>,
) {
let (alloc, _extra_input) = alloc_per_thread.replace_with_default();
let result = if self.join_error_index == Some(index) {
Err(BrotliEncoderThreadError::OtherThreadPanic)
} else {
Ok(CompressionThreadResult {
compressed: Err(BrotliEncoderThreadError::InsufficientOutputSpace),
alloc,
})
};
alloc_per_thread.0 = InternalSendAlloc::Join(CountingJoinable {
result: Some(result),
joined_count: self.joined_count,
});
}
}
type TestSendAlloc = SendAlloc<
CompressionThreadResult<StandardAlloc>,
UnionHasher<StandardAlloc>,
StandardAlloc,
CountingJoinable,
>;
fn test_alloc() -> TestSendAlloc {
SendAlloc::new(StandardAlloc::default(), UnionHasher::Uninit)
}
struct RealChunkSpawner {
joined_count: &'static AtomicUsize,
compressed_error_index: Option<usize>,
}
impl
BatchSpawnableLite<
CompressionThreadResult<StandardAlloc>,
UnionHasher<StandardAlloc>,
StandardAlloc,
(TestSlice, BrotliEncoderParams),
> for RealChunkSpawner
{
type JoinHandle = CountingJoinable;
type FinalJoinHandle = TestOwnedRetriever<(TestSlice, BrotliEncoderParams)>;
fn make_spawner(
&mut self,
input: &mut Owned<(TestSlice, BrotliEncoderParams)>,
) -> Self::FinalJoinHandle {
TestOwnedRetriever {
input: Some(mem::replace(input, Owned(InternalOwned::Borrowed)).unwrap()),
fail_views: false,
}
}
fn spawn(
&mut self,
handle: &mut Self::FinalJoinHandle,
alloc_per_thread: &mut SendAlloc<
CompressionThreadResult<StandardAlloc>,
UnionHasher<StandardAlloc>,
StandardAlloc,
Self::JoinHandle,
>,
index: usize,
num_threads: usize,
_func: fn(
UnionHasher<StandardAlloc>,
usize,
usize,
&(TestSlice, BrotliEncoderParams),
StandardAlloc,
) -> CompressionThreadResult<StandardAlloc>,
) {
let (alloc, _extra_input) = alloc_per_thread.replace_with_default();
let result = if self.compressed_error_index == Some(index) {
Ok(CompressionThreadResult {
compressed: Err(BrotliEncoderThreadError::ConcatenationDidNotProcessFullFile),
alloc,
})
} else {
Ok(handle
.view(|input_and_params| {
compress_part(
UnionHasher::Uninit,
index,
num_threads,
input_and_params,
alloc,
)
})
.unwrap())
};
alloc_per_thread.0 = InternalSendAlloc::Join(CountingJoinable {
result: Some(result),
joined_count: self.joined_count,
});
}
}
#[test]
fn compress_multi_joins_remaining_workers_after_join_error() {
static INPUT: &[u8] = b"join all workers before returning";
JOINED_AFTER_JOIN_ERROR.store(0, Ordering::SeqCst);
let mut spawner = CountingSpawner {
joined_count: &JOINED_AFTER_JOIN_ERROR,
join_error_index: Some(0),
fail_views: false,
};
let mut alloc_per_thread = [test_alloc(), test_alloc(), test_alloc(), test_alloc()];
let mut params = BrotliEncoderParams::default();
params.quality = 1;
let mut owned_input = Owned::new(TestSlice(INPUT));
let mut output = [0u8; 256];
let result = CompressMulti(
¶ms,
&mut owned_input,
&mut output,
&mut alloc_per_thread[..],
&mut spawner,
);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::OtherThreadPanic)
));
assert_eq!(JOINED_AFTER_JOIN_ERROR.load(Ordering::SeqCst), 3);
assert_eq!(owned_input.view().slice(), INPUT);
}
#[test]
fn compress_multi_joins_spawned_worker_after_setup_view_error() {
static INPUT: &[u8] = b"restore input after setup failure";
JOINED_AFTER_SETUP_ERROR.store(0, Ordering::SeqCst);
let mut spawner = CountingSpawner {
joined_count: &JOINED_AFTER_SETUP_ERROR,
join_error_index: None,
fail_views: true,
};
let mut alloc_per_thread = [test_alloc(), test_alloc()];
let mut params = BrotliEncoderParams::default();
params.favor_cpu_efficiency = true;
let mut owned_input = Owned::new(TestSlice(INPUT));
let mut output = [0u8; 256];
let result = CompressMulti(
¶ms,
&mut owned_input,
&mut output,
&mut alloc_per_thread[..],
&mut spawner,
);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::OtherThreadPanic)
));
assert_eq!(JOINED_AFTER_SETUP_ERROR.load(Ordering::SeqCst), 1);
assert_eq!(owned_input.view().slice(), INPUT);
}
#[test]
fn compress_multi_preserves_first_worker_error_through_stream_phase() {
static INPUT: &[u8] =
b"a sufficiently long body of text so every worker produces a real brotli chunk";
DRAINED_AFTER_STREAM_PHASE.store(0, Ordering::SeqCst);
let mut spawner = RealChunkSpawner {
joined_count: &DRAINED_AFTER_STREAM_PHASE,
compressed_error_index: Some(0),
};
let mut alloc_per_thread = [test_alloc(), test_alloc(), test_alloc()];
let mut params = BrotliEncoderParams::default();
params.quality = 1;
params.magic_number = true;
let mut owned_input = Owned::new(TestSlice(INPUT));
let mut output = [0u8; 4096];
let result = CompressMulti(
¶ms,
&mut owned_input,
&mut output,
&mut alloc_per_thread[..],
&mut spawner,
);
assert!(matches!(
result,
Err(BrotliEncoderThreadError::ConcatenationDidNotProcessFullFile)
));
assert_eq!(DRAINED_AFTER_STREAM_PHASE.load(Ordering::SeqCst), 2);
assert_eq!(owned_input.view().slice(), INPUT);
}