#![cfg(any(windows, target_os = "linux"))]
use std::alloc::{GlobalAlloc, Layout, alloc_zeroed, dealloc, realloc};
use std::sync::mpsc;
use std::thread;
use bomalloc::{BoAllocError, BoGlobalAllocator, Config, TrimMode};
#[global_allocator]
static GLOBAL: BoGlobalAllocator = BoGlobalAllocator::new();
#[test]
fn rust_allocations_use_bomalloc() {
let mut values = Vec::with_capacity(16_384);
values.extend(0_u64..16_384);
assert_eq!(values.iter().copied().sum::<u64>(), 134_209_536);
let text = "global bomalloc ".repeat(8_192);
assert!(text.starts_with("global bomalloc"));
let stats = GLOBAL.stats().unwrap();
assert!(stats.requested_live_bytes >= values.len() * size_of::<u64>());
GLOBAL.validate().unwrap();
}
#[test]
fn zeroed_and_reallocated_memory_preserves_contents_and_alignment() {
let old_layout = Layout::from_size_align(257, 256).unwrap();
unsafe {
let pointer = alloc_zeroed(old_layout);
assert!(!pointer.is_null());
assert_eq!(pointer as usize % old_layout.align(), 0);
assert!((0..old_layout.size()).all(|index| pointer.add(index).read() == 0));
for index in 0..old_layout.size() {
pointer.add(index).write((index % 251) as u8);
}
let new_size = 96 * 1024;
let grown = realloc(pointer, old_layout, new_size);
assert!(!grown.is_null());
assert_eq!(grown as usize % old_layout.align(), 0);
assert!((0..old_layout.size()).all(|index| grown.add(index).read() == (index % 251) as u8));
let grown_layout = Layout::from_size_align(new_size, old_layout.align()).unwrap();
dealloc(grown, grown_layout);
}
}
#[test]
fn standard_objects_can_cross_thread_boundaries() {
let (sender, receiver) = mpsc::channel();
let producer = thread::spawn(move || {
let payload = (0_u32..32_768).collect::<Vec<_>>().into_boxed_slice();
sender.send(payload).unwrap();
});
let payload = receiver.recv().unwrap();
producer.join().unwrap();
assert_eq!(payload[12_345], 12_345);
drop(payload);
GLOBAL.validate().unwrap();
let _ = GLOBAL.trim(TrimMode::Excess).unwrap();
}
#[test]
fn invalid_global_configuration_falls_back_to_system() {
const INVALID: Config = Config {
recent_spans_per_class: 0,
..Config::new()
};
let allocator = BoGlobalAllocator::with_config(INVALID);
let layout = Layout::from_size_align(4096, 64).unwrap();
unsafe {
let pointer = allocator.alloc(layout);
assert!(!pointer.is_null());
pointer.write_bytes(0x5a, layout.size());
allocator.dealloc(pointer, layout);
}
assert_eq!(allocator.initialize(), Err(BoAllocError::InvalidConfig));
}