use cheetah_string::CheetahString;
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use std::hint::black_box;
use std::sync::Arc;
struct CountingAllocator;
std::thread_local! {
static TRACKING: Cell<bool> = const { Cell::new(false) };
static ALLOCATION_COUNT: Cell<usize> = const { Cell::new(0) };
static ALLOCATED_BYTES: Cell<usize> = const { Cell::new(0) };
}
fn record_allocation(size: usize) {
let _ = TRACKING.try_with(|tracking| {
if tracking.get() {
let _ = ALLOCATION_COUNT.try_with(|count| count.set(count.get() + 1));
let _ = ALLOCATED_BYTES.try_with(|bytes| bytes.set(bytes.get() + size));
}
});
}
unsafe impl GlobalAlloc for CountingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
record_allocation(layout.size());
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 {
record_allocation(new_size);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static GLOBAL: CountingAllocator = CountingAllocator;
fn measure<T>(operation: impl FnOnce() -> T) -> (usize, usize, T) {
TRACKING.with(|tracking| tracking.set(false));
ALLOCATION_COUNT.with(|count| count.set(0));
ALLOCATED_BYTES.with(|bytes| bytes.set(0));
TRACKING.with(|tracking| tracking.set(true));
let result = black_box(operation());
TRACKING.with(|tracking| tracking.set(false));
(
ALLOCATION_COUNT.with(Cell::get),
ALLOCATED_BYTES.with(Cell::get),
result,
)
}
fn assert_clone_allocations(value: &CheetahString) {
let pointer = value.as_bytes().as_ptr();
let (count, bytes, cloned) = measure(|| black_box(value).clone());
assert_eq!(
(count, bytes),
(0, 0),
"clone must only adjust ownership metadata"
);
assert_eq!(cloned.as_bytes().as_ptr(), pointer);
assert_eq!(&cloned, value);
}
fn exact_string(len: usize) -> String {
let mut value = String::with_capacity(len);
value.extend(std::iter::repeat_n('x', len));
assert_eq!(value.len(), value.capacity());
value
}
fn spare_string(len: usize) -> String {
let mut value = String::with_capacity(len * 2);
value.extend(std::iter::repeat_n('x', len));
assert!(value.capacity() > value.len());
value
}
#[test]
fn arc_str_char_and_short_concat_are_zero_allocation_fast_paths() {
let source: Arc<str> = Arc::from("a".repeat(1024));
let source_pointer = source.as_ptr();
let (count, bytes, shared) = measure(|| CheetahString::from(black_box(source)));
assert_eq!((count, bytes), (0, 0));
assert_eq!(shared.as_bytes().as_ptr(), source_pointer);
let short_source: Arc<str> = Arc::from("short");
let short_pointer = short_source.as_ptr();
let (count, bytes, short) = measure(|| CheetahString::from(black_box(short_source)));
assert_eq!((count, bytes), (0, 0));
assert_ne!(short.as_bytes().as_ptr(), short_pointer);
let (count, bytes, ()) = measure(|| {
for scalar in 0..=char::MAX as u32 {
if let Some(character) = char::from_u32(scalar) {
let value = CheetahString::from(black_box(character));
let mut encoded = [0; 4];
assert_eq!(value.as_str(), character.encode_utf8(&mut encoded));
black_box(value);
}
}
});
assert_eq!((count, bytes), (0, 0), "every Unicode scalar is inline");
let left = CheetahString::from("inline");
let (count, bytes, combined) = measure(|| black_box(left) + black_box("-value"));
assert_eq!((count, bytes), (0, 0));
assert_eq!(combined, "inline-value");
let left = CheetahString::from("inline");
let owned_right = String::from("-owned");
let (count, bytes, combined) = measure(|| black_box(left) + black_box(owned_right));
assert_eq!((count, bytes), (0, 0));
assert_eq!(combined, "inline-owned");
}
#[test]
fn exact_and_spare_capacity_freeze_costs_are_explicit() {
let exact_input = exact_string(1024);
let (count, _, exact) = measure(|| CheetahString::from_string(exact_input));
assert_eq!(count, 1, "exact-capacity String freeze creates Arc backing");
assert_eq!(exact.len(), 1024);
let spare_input = spare_string(1024);
let (count, _, spare) = measure(|| CheetahString::from_string(spare_input));
assert_eq!(
count, 1,
"spare-capacity String freeze copies into Arc backing without shrinking"
);
assert_eq!(spare.len(), 1024);
let mut exact_builder = cheetah_string::CheetahBuilder::with_capacity(1024);
exact_builder.push_str(&"x".repeat(1024));
assert_eq!(exact_builder.len(), exact_builder.capacity());
let (count, _, exact) = measure(|| exact_builder.finish());
assert_eq!(
count, 1,
"exact-capacity builder freeze creates Arc backing"
);
assert_eq!(exact.len(), 1024);
let mut spare_builder = cheetah_string::CheetahBuilder::with_capacity(2048);
spare_builder.push_str(&"x".repeat(1024));
assert!(spare_builder.capacity() > spare_builder.len());
let (count, _, spare) = measure(|| spare_builder.finish());
assert_eq!(
count, 1,
"spare-capacity builder freeze copies into Arc backing without shrinking"
);
assert_eq!(spare.len(), 1024);
}
#[test]
fn v3_allocation_and_clone_contracts() {
let (count, bytes, inline) = measure(|| CheetahString::from(black_box("inline")));
assert_eq!((count, bytes), (0, 0));
assert_eq!(inline, "inline");
let (count, bytes, inline_clone) = measure(|| black_box(&inline).clone());
assert_eq!((count, bytes), (0, 0));
assert_eq!(inline_clone, inline);
let (count, bytes, static_value) = measure(|| {
CheetahString::from_static_str(black_box(
"a static string longer than the twenty-three-byte inline boundary",
))
});
assert_eq!((count, bytes), (0, 0));
assert!(static_value.len() > 23);
assert_clone_allocations(&static_value);
let borrowed = "b".repeat(1024);
let (count, _, borrowed_value) = measure(|| CheetahString::from(black_box(borrowed.as_str())));
assert_eq!(count, 1, "long borrowed input has one shared allocation");
assert_eq!(borrowed_value, borrowed);
assert_clone_allocations(&borrowed_value);
let mut exact_owned = String::with_capacity(1024);
exact_owned.extend(std::iter::repeat_n('o', 1024));
assert_eq!(exact_owned.len(), exact_owned.capacity());
let (count, bytes, owned_value) =
measure(|| CheetahString::from_string(black_box(exact_owned)));
assert_eq!(count, 1, "freezing owned input creates Arc backing");
assert!(bytes >= owned_value.len());
let (count, bytes, owned_clone) = measure(|| black_box(&owned_value).clone());
assert_eq!((count, bytes), (0, 0), "v3 clone only increments Arc");
assert_eq!(
owned_clone.as_bytes().as_ptr(),
owned_value.as_bytes().as_ptr()
);
assert_eq!(owned_clone, owned_value);
let shared_source = "s".repeat(1024);
let shared_value = CheetahString::from_string_shared(shared_source);
let (count, bytes, shared_clone) = measure(|| black_box(&shared_value).clone());
assert_eq!((count, bytes), (0, 0), "Shared clone only increments Arc");
assert_eq!(
shared_clone.as_bytes().as_ptr(),
shared_value.as_bytes().as_ptr()
);
assert_eq!(shared_clone, shared_value);
#[cfg(feature = "bytes")]
{
use cheetah_string::CheetahBytes;
let raw = bytes::Bytes::from_static(b"zero-copy-payload");
let payload_pointer = raw.as_ptr();
let (count, allocated, cheetah_bytes) =
measure(|| CheetahBytes::from(black_box(raw.clone())));
assert_eq!((count, allocated), (0, 0));
assert_eq!(cheetah_bytes.as_bytes().as_ptr(), payload_pointer);
let (count, allocated, roundtrip) =
measure(|| bytes::Bytes::from(black_box(cheetah_bytes)));
assert_eq!((count, allocated), (0, 0));
assert_eq!(roundtrip.as_ptr(), payload_pointer);
}
}
#[test]
fn exact_length_assembly_allocates_at_most_once() {
let (count, bytes, short) =
measure(|| CheetahString::concat(black_box(&["orders", "@", "group-a"])));
assert_eq!((count, bytes), (0, 0), "short concat stays inline");
assert_eq!(short, "orders@group-a");
let parts = ["%RETRY%order-consumer-group", "@", "broker-a-instance-0001"];
let (count, _, long) = measure(|| CheetahString::concat(black_box(&parts)));
assert_eq!(count, 1, "long concat writes straight into its Arc backing");
assert_eq!(long, parts.concat().as_str());
let left = CheetahString::from("a left side longer than the inline limit");
let (count, _, added) = measure(|| black_box(left) + black_box("-and-a-right-side"));
assert_eq!(count, 1, "long addition allocates only its result");
assert_eq!(added.len(), 57);
let base = CheetahString::from("orders@group-a;tag=pay;tag=refund;tag=pay");
let (count, bytes, unchanged) = measure(|| black_box(&base).replace("missing", "x"));
assert_eq!(
(count, bytes),
(0, 0),
"replace without a match reuses the value"
);
assert_eq!(unchanged.as_bytes().as_ptr(), base.as_bytes().as_ptr());
let (count, _, replaced) = measure(|| black_box(&base).replace("pay", "PAYMENT"));
assert_eq!(count, 1, "long replace allocates only its result");
assert_eq!(replaced, base.as_str().replace("pay", "PAYMENT").as_str());
let short_base = CheetahString::from("a.b.c.d");
let (count, bytes, short_replaced) = measure(|| black_box(&short_base).replace(".", "::"));
assert_eq!((count, bytes), (0, 0), "short replace result stays inline");
assert_eq!(short_replaced, "a::b::c::d");
let topic = CheetahString::from("order-topic");
let (count, bytes, upper) = measure(|| black_box(&topic).to_uppercase());
assert_eq!(
(count, bytes),
(0, 0),
"short ASCII case mapping stays inline"
);
assert_eq!(upper, "ORDER-TOPIC");
let long_topic = CheetahString::from("rmq_sys_trace_topic_with_a_long_name");
let (count, _, long_upper) = measure(|| black_box(&long_topic).to_uppercase());
assert_eq!(
count, 1,
"long ASCII case mapping copies once and maps in place"
);
assert_eq!(long_upper, "RMQ_SYS_TRACE_TOPIC_WITH_A_LONG_NAME");
let (count, bytes, same) = measure(|| black_box(&long_upper).to_uppercase());
assert_eq!(
(count, bytes),
(0, 0),
"an already upper-case value is reused"
);
assert_eq!(same.as_bytes().as_ptr(), long_upper.as_bytes().as_ptr());
let (count, bytes, interleaved) = measure(|| black_box(&short_base).replace("", "|"));
assert_eq!(
(count, bytes),
(0, 0),
"empty-pattern replace with a short result stays inline"
);
assert_eq!(interleaved, "|a|.|b|.|c|.|d|");
let (count, bytes, untouched) = measure(|| black_box(&base).replacen("", "x", 0));
assert_eq!(
(count, bytes),
(0, 0),
"a zero-count replace reuses the value"
);
assert_eq!(untouched.as_bytes().as_ptr(), base.as_bytes().as_ptr());
let unit = CheetahString::from("ab");
let (count, bytes, repeated) = measure(|| black_box(&unit).repeat(5));
assert_eq!((count, bytes), (0, 0), "short repeat stays inline");
assert_eq!(repeated, "ababababab");
let (count, _, copied) = measure(|| String::from(black_box(&long_topic)));
assert_eq!(count, 1, "String::from(&CheetahString) copies once");
assert_eq!(copied.capacity(), copied.len());
}
#[cfg(feature = "bytes")]
#[test]
fn bytes_backed_text_never_copies_validated_or_sliced_text() {
use cheetah_string::CheetahText;
let frame = bytes::Bytes::from_static(
b"KEYS=order-10001;TAGS=paid;UNIQ_KEY=7F00000100002A9F000000000001",
);
let (count, bytes, text) =
measure(|| CheetahText::try_from_bytes(black_box(frame.clone())).unwrap());
assert_eq!(
(count, bytes),
(0, 0),
"validating a Bytes buffer keeps its storage"
);
let (count, bytes, value) = measure(|| black_box(&text).slice(36..));
assert_eq!(
(count, bytes),
(0, 0),
"slicing a static buffer allocates nothing"
);
assert_eq!(value, "7F00000100002A9F000000000001");
let (count, bytes, key) = measure(|| {
let text = black_box(&text);
text.slice_ref(text.split(';').next().unwrap())
});
assert_eq!(
(count, bytes),
(0, 0),
"slice_ref of a static buffer allocates nothing"
);
assert_eq!(key, "KEYS=order-10001");
let long = CheetahString::from("a shared value that is longer than the inline limit");
let (count, _, adopted) = measure(|| CheetahText::from(black_box(long.clone())));
assert_eq!(
count, 1,
"a shared CheetahString becomes the buffer owner without a copy"
);
assert_eq!(adopted.as_bytes().as_ptr(), long.as_bytes().as_ptr());
}
#[test]
fn formatting_short_values_does_not_allocate() {
use cheetah_string::cheetah_format;
let (topic, queue_id) = ("orders", 4i64);
let (count, bytes, key) =
measure(|| cheetah_format!("{}@{}", black_box(topic), black_box(queue_id)));
assert_eq!((count, bytes), (0, 0), "short formatted values stay inline");
assert_eq!(key, "orders@4");
let (count, bytes, literal) = measure(|| cheetah_format!("TopicTest"));
assert_eq!(
(count, bytes),
(0, 0),
"a literal format string is borrowed"
);
assert_eq!(literal, "TopicTest");
let group = "%RETRY%order-consumer-group";
let (count, _, long) =
measure(|| cheetah_format!("{}@{}", black_box(group), black_box(queue_id)));
assert!(count >= 1, "long formatted values need shared storage");
assert_eq!(long, "%RETRY%order-consumer-group@4");
}
#[test]
fn building_a_short_key_does_not_allocate() {
use cheetah_string::CheetahBuilder;
let (topic, group) = ("orders", "group-a");
let (count, bytes, key) = measure(|| {
let mut builder = CheetahBuilder::with_capacity(black_box(topic).len() + 1 + group.len());
builder.push_str(black_box(topic));
builder.push('@');
builder.push_str(black_box(group));
builder.finish()
});
assert_eq!(
(count, bytes),
(0, 0),
"a short key is built and frozen inline"
);
assert_eq!(key, "orders@group-a");
let (count, _, spilled) = measure(|| {
let mut builder = CheetahBuilder::new();
builder.push_str(black_box("%RETRY%order-consumer-group"));
builder.push('@');
builder.push_str(black_box("broker-a"));
builder.finish()
});
assert_eq!(
count, 2,
"a spilled builder allocates its buffer once and the Arc once"
);
assert_eq!(spilled, "%RETRY%order-consumer-group@broker-a");
}