#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cmp::Ordering;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use db_collation::Collation;
struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, AtomicOrdering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
ALLOCS.fetch_add(1, AtomicOrdering::Relaxed);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
fn allocs_of<F: FnOnce()>(f: F) -> usize {
let before = ALLOCS.load(AtomicOrdering::Relaxed);
f();
ALLOCS.load(AtomicOrdering::Relaxed) - before
}
fn assert_no_alloc(c: &Collation, len: usize) {
let a = "a".repeat(len);
let b = "a".repeat(len);
let late_a = "a".repeat(len);
let late_b = format!("{}b", "a".repeat(len - 1));
let expansion = "\u{bd}".repeat(len); let expansion_b = "\u{bd}".repeat(len);
let _ = c.compare(&a, &b).unwrap();
assert_eq!(
allocs_of(|| assert_eq!(c.compare(&a, &b).unwrap(), Ordering::Equal)),
0,
"equal keys, len={len}"
);
assert_eq!(
allocs_of(|| assert_eq!(c.compare(&late_a, &late_b).unwrap(), Ordering::Less)),
0,
"late diff, len={len}"
);
assert_eq!(
allocs_of(|| assert_eq!(
c.compare(&expansion, &expansion_b).unwrap(),
Ordering::Equal
)),
0,
"expansion, len={len}"
);
}
#[test]
fn test_compare_does_not_allocate() {
let binary = Collation::binary();
for len in [1, 16, 64, 1000] {
assert_no_alloc(&binary, len);
}
#[cfg(feature = "mysql-uca")]
{
let mysql = Collation::mysql_0900_ai_ci();
for len in [1, 16, 64, 1000] {
assert_no_alloc(&mysql, len);
}
}
}