cheetah-string 3.2.0

An immutable, clone-cheap UTF-8 string with explicit construction and byte interoperability
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
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! {
    // Test-harness bookkeeping may allocate on a different thread while this
    // binary is running. Count only the thread executing the measured closure.
    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));
        }
    });
}

// SAFETY: Every operation delegates to the process System allocator.
unsafe impl GlobalAlloc for CountingAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        record_allocation(layout.size());
        // SAFETY: The caller provided a valid allocation layout.
        unsafe { System.alloc(layout) }
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        // SAFETY: ptr/layout originated from System.
        unsafe { System.dealloc(ptr, layout) }
    }

    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        record_allocation(new_size);
        // SAFETY: ptr/layout originated from System and new_size is forwarded.
        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() {
    // Keep all measurements in one test. Run this binary with --test-threads=1
    // so unrelated harness allocations cannot contaminate the global counter.
    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");
}