mod common;
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use std::io::Cursor;
use std::sync::Mutex;
struct CountingAlloc;
thread_local! {
static ALLOCATIONS: Cell<usize> = const { Cell::new(0) };
}
fn count_one() {
let _ = ALLOCATIONS.try_with(|c| c.set(c.get() + 1));
}
fn allocations() -> usize {
ALLOCATIONS.with(|c| c.get())
}
unsafe impl GlobalAlloc for CountingAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
count_one();
System.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout)
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
count_one();
System.alloc_zeroed(layout)
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
count_one();
System.realloc(ptr, layout, new_size)
}
}
#[global_allocator]
static GLOBAL: CountingAlloc = CountingAlloc;
use y4m_codec::{Decoder, EncoderBuilder, Error};
static SERIAL: Mutex<()> = Mutex::new(());
fn on_measurement_thread<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
let _serial = SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
std::thread::Builder::new()
.name("zero-alloc-measurement".into())
.spawn(f)
.expect("spawn measurement thread")
.join()
.expect("measurement thread panicked")
}
#[test]
fn counter_detects_allocations() {
on_measurement_thread(|| {
let before = allocations();
let v: Vec<u8> = std::hint::black_box(vec![1u8; 64]);
let after = allocations();
drop(v);
assert!(after > before, "thread-local counter missed an allocation");
});
}
#[test]
fn counter_is_thread_local() {
on_measurement_thread(|| {
let before = allocations();
std::thread::spawn(|| {
let v: Vec<u8> = std::hint::black_box(vec![1u8; 4096]);
drop(v);
})
.join()
.unwrap();
let middle = allocations();
std::thread::spawn(|| {}).join().unwrap();
let after = allocations();
assert_eq!(
middle - before,
after - middle,
"child-thread allocation leaked into this thread's counter"
);
});
}
fn assert_zero_alloc_roundtrip(fixture: &str) {
let bytes = common::fixture_bytes(fixture);
let mut decoder = Decoder::new(Cursor::new(&bytes)).unwrap();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut encoder = EncoderBuilder::new(decoder.width(), decoder.height(), decoder.framerate())
.raw_params(decoder.raw_params())
.unwrap()
.write_header(&mut out)
.unwrap();
let before = allocations();
let mut frames = 0usize;
loop {
match decoder.read_frame() {
Ok(frame) => {
std::hint::black_box(frame.y());
encoder
.write_frame_with_params([frame.y(), frame.u(), frame.v()], frame.raw_params())
.unwrap();
frames += 1;
}
Err(Error::EndOfStream) => break,
Err(e) => panic!("{fixture}: {e}"),
}
}
let after = allocations();
assert_eq!(
after - before,
0,
"{fixture}: hot path allocated over {frames} frames"
);
assert!(frames > 0, "{fixture}: no frames decoded");
assert_eq!(out, bytes, "{fixture}: round-trip bytes differ");
}
#[test]
fn zero_alloc_hot_path() {
on_measurement_thread(|| {
assert_zero_alloc_roundtrip("fixtures/frame_params_2x2_2f.y4m");
assert_zero_alloc_roundtrip("fixtures/c420p10_2x2_2f_LE.y4m");
});
}
#[test]
fn zero_alloc_u16_encode_path() {
on_measurement_thread(|| {
let bytes = common::fixture_bytes("fixtures/c420p10_2x2_2f_LE.y4m");
let mut decoder = Decoder::new(Cursor::new(&bytes)).unwrap();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut encoder = EncoderBuilder::new(2, 2, decoder.framerate())
.interlace(y4m_codec::Interlace::Progressive)
.pixel_aspect(y4m_codec::Ratio::new(1, 1))
.colorspace(y4m_codec::Colorspace::C420P10)
.write_header(&mut out)
.unwrap();
let before = allocations();
let mut frames = 0usize;
loop {
match decoder.read_frame() {
Ok(frame) => {
encoder
.write_frame_u16([
frame.plane_u16(0).unwrap(),
frame.plane_u16(1).unwrap(),
frame.plane_u16(2).unwrap(),
])
.unwrap();
frames += 1;
}
Err(Error::EndOfStream) => break,
Err(e) => panic!("decode: {e}"),
}
}
let after = allocations();
assert_eq!(after - before, 0, "u16 encode path allocated");
assert_eq!(frames, 2);
assert_eq!(out, bytes);
});
}