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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::str::{self, Utf8Error};
use super::repr::{InnerString, INLINE_CAPACITY};
use super::CheetahString;
use crate::inline::InlineStr;
impl CheetahString {
/// Creates an empty inline string.
#[inline]
pub const fn empty() -> Self {
CheetahString {
inner: InnerString::Inline(InlineStr::empty()),
}
}
/// Creates an empty string.
#[inline]
pub fn new() -> Self {
CheetahString::default()
}
/// Wraps an inline value built elsewhere in the crate.
#[inline]
pub(crate) fn from_inline(inline: InlineStr) -> Self {
CheetahString {
inner: InnerString::Inline(inline),
}
}
/// Creates a string that borrows a static string slice without allocation.
///
/// Explicit static construction takes precedence over inline storage,
/// including when `s` is 23 bytes or shorter.
#[inline]
pub const fn from_static_str(s: &'static str) -> Self {
CheetahString {
inner: InnerString::Static(s),
}
}
/// Creates a `CheetahString` from a byte vector without validating UTF-8.
///
/// # Safety
///
/// The caller must guarantee that `s` contains valid UTF-8 for the entire
/// lifetime of the returned `CheetahString`.
#[inline]
pub unsafe fn from_utf8_unchecked_vec(s: Vec<u8>) -> Self {
// SAFETY: the caller guarantees that the complete vector is valid UTF-8.
unsafe { CheetahString::from_validated_vec_unchecked(s) }
}
#[inline]
unsafe fn from_validated_vec_unchecked(s: Vec<u8>) -> Self {
if s.len() <= INLINE_CAPACITY {
// SAFETY: Callers validate UTF-8 before reaching this helper.
let value = unsafe { str::from_utf8_unchecked(&s) };
let inline = InlineStr::from_str(value).expect("short str must fit inline storage");
return CheetahString {
inner: InnerString::Inline(inline),
};
}
// SAFETY: Callers validate UTF-8 before reaching this helper.
CheetahString::from_string(unsafe { String::from_utf8_unchecked(s) })
}
/// Creates a `CheetahString` from a byte vector with UTF-8 validation.
///
/// # Errors
///
/// Returns an error if the bytes are not valid UTF-8.
///
/// # Examples
///
/// ```
/// use cheetah_string::CheetahString;
///
/// let bytes = vec![104, 101, 108, 108, 111]; // "hello"
/// let s = CheetahString::try_from_vec(bytes).unwrap();
/// assert_eq!(s, "hello");
///
/// let invalid = vec![0xFF, 0xFE];
/// assert!(CheetahString::try_from_vec(invalid).is_err());
/// ```
pub fn try_from_vec(v: Vec<u8>) -> Result<Self, Utf8Error> {
str::from_utf8(&v)?;
// SAFETY: validation above covers the complete owned buffer.
Ok(unsafe { CheetahString::from_validated_vec_unchecked(v) })
}
/// Creates a `CheetahString` from a byte slice with UTF-8 validation.
///
/// # Errors
///
/// Returns an error if the bytes are not valid UTF-8.
///
/// # Examples
///
/// ```
/// use cheetah_string::CheetahString;
///
/// let bytes = b"hello";
/// let s = CheetahString::try_from_bytes(bytes).unwrap();
/// assert_eq!(s, "hello");
///
/// let invalid = &[0xFF, 0xFE];
/// assert!(CheetahString::try_from_bytes(invalid).is_err());
/// ```
pub fn try_from_bytes(b: &[u8]) -> Result<Self, Utf8Error> {
let s = str::from_utf8(b)?;
Ok(CheetahString::from_slice(s))
}
/// Creates a `CheetahString` from a byte slice without validating UTF-8.
///
/// # Safety
///
/// The caller must guarantee that `b` contains valid UTF-8.
#[inline]
pub unsafe fn from_utf8_unchecked_bytes(b: &[u8]) -> Self {
// SAFETY: The caller guarantees that `b` contains valid UTF-8.
CheetahString::from_slice(unsafe { str::from_utf8_unchecked(b) })
}
/// Creates a `CheetahString` from a shared byte vector with UTF-8 validation.
///
/// # Errors
///
/// Returns an error if the bytes are not valid UTF-8.
#[inline]
pub fn try_from_arc_vec(s: Arc<Vec<u8>>) -> Result<Self, Utf8Error> {
match Arc::try_unwrap(s) {
Ok(v) => CheetahString::try_from_vec(v),
Err(s) => {
let s = str::from_utf8(s.as_slice())?;
Ok(CheetahString::from_slice(s))
}
}
}
/// Creates a `CheetahString` from a shared byte vector without validating UTF-8.
///
/// # Safety
///
/// The caller must guarantee that `s` contains valid UTF-8.
#[inline]
pub unsafe fn from_utf8_unchecked_arc_vec(s: Arc<Vec<u8>>) -> Self {
// SAFETY: the caller guarantees that the complete shared vector is valid UTF-8.
unsafe { CheetahString::from_validated_arc_vec_unchecked(s) }
}
#[inline]
unsafe fn from_validated_arc_vec_unchecked(s: Arc<Vec<u8>>) -> Self {
match Arc::try_unwrap(s) {
// SAFETY: this helper inherits the valid UTF-8 precondition.
Ok(v) => unsafe { CheetahString::from_validated_vec_unchecked(v) },
Err(s) => {
// SAFETY: Callers validate UTF-8 before reaching this helper.
unsafe { CheetahString::from_utf8_unchecked_bytes(s.as_slice()) }
}
}
}
/// Creates a value from a borrowed string slice.
///
/// Values up to 23 bytes use inline storage; longer values are copied into
/// a shared immutable allocation.
#[inline]
pub fn from_slice(s: &str) -> Self {
if let Some(inline) = InlineStr::from_str(s) {
CheetahString {
inner: InnerString::Inline(inline),
}
} else {
// Use Arc<str> for long borrowed strings to avoid the extra String header.
let arc_str: Arc<str> = Arc::from(s);
CheetahString {
inner: InnerString::Shared(arc_str),
}
}
}
/// Freezes an owned string into inline or shared immutable storage.
#[inline]
pub fn from_string(s: String) -> Self {
CheetahString::from_string_shared(s)
}
/// Freezes an owned string into the canonical immutable representation.
///
/// This compatibility constructor no longer promises to retain spare
/// capacity. Use [`CheetahString::from_string`] for immutable values or
/// [`crate::CheetahBuilder`] when mutation must continue.
#[deprecated(since = "3.0.0", note = "use from_string(), CheetahBuilder, or String")]
#[inline]
pub fn from_string_owned(s: String) -> Self {
Self::from_string(s)
}
/// Creates a `CheetahString` from an owned `String` using shared storage
/// for long immutable strings.
///
/// This is the same storage policy used by
/// [`CheetahString::from_string`]. The explicit name is retained for
/// source compatibility.
#[inline]
pub fn from_string_shared(s: String) -> Self {
if let Some(inline) = InlineStr::from_str(&s) {
CheetahString {
inner: InnerString::Inline(inline),
}
} else {
// Arc<str> is the final backing and needs its own allocation for
// the reference counts. Copying straight from the String skips the
// shrink-to-fit reallocation that `into_boxed_str` would perform
// when the String has spare capacity.
let arc_str: Arc<str> = Arc::from(s.as_str());
CheetahString {
inner: InnerString::Shared(arc_str),
}
}
}
/// Concatenates string slices into one value with a single copy.
///
/// Results of up to 23 bytes are stored inline without allocating.
/// Longer results are written straight into one shared allocation, with no
/// intermediate `String`. This is the cheapest way to build composite keys
/// such as `topic@group`.
///
/// # Panics
///
/// Panics if the total length overflows `usize`.
///
/// # Examples
///
/// ```
/// use cheetah_string::CheetahString;
///
/// let key = CheetahString::concat(&["orders", "@", "group-a"]);
/// assert_eq!(key, "orders@group-a");
/// ```
#[must_use]
#[inline]
pub fn concat(parts: &[&str]) -> Self {
let len = parts
.iter()
.try_fold(0usize, |total, part| total.checked_add(part.len()))
.expect("concatenated string length overflow");
super::assemble::assemble(len, |writer| {
for part in parts {
writer.push_str(part);
}
})
}
/// Creates a value from an owned `Arc<str>`.
///
/// Values up to 23 bytes are copied into canonical inline storage. Longer
/// values reuse the `Arc<str>` payload without allocation or copying.
#[inline]
pub fn from_arc_str(s: Arc<str>) -> Self {
if let Some(inline) = InlineStr::from_str(&s) {
CheetahString {
inner: InnerString::Inline(inline),
}
} else {
CheetahString {
inner: InnerString::Shared(s),
}
}
}
/// Creates a value from a shared owned `String`.
///
/// A uniquely owned input can be consumed directly. A shared input is
/// copied because `Arc<String>` cannot be reinterpreted as `Arc<str>`.
#[inline]
pub fn from_arc_string(s: Arc<String>) -> Self {
match Arc::try_unwrap(s) {
Ok(s) => CheetahString::from_string(s),
Err(s) => CheetahString::from_slice(s.as_str()),
}
}
#[inline]
#[cfg(feature = "bytes")]
/// Validates and copies a `bytes::Bytes` buffer into text storage.
///
/// # Errors
///
/// Returns an error that retains the original buffer when UTF-8
/// validation fails.
pub fn try_copy_from_bytes(b: bytes::Bytes) -> Result<Self, crate::FromUtf8BytesError> {
match str::from_utf8(b.as_ref()) {
Ok(value) => Ok(CheetahString::from_slice(value)),
Err(error) => Err(crate::FromUtf8BytesError::new(b, error)),
}
}
#[deprecated(
since = "2.2.0",
note = "use try_copy_from_bytes; its error preserves the original buffer"
)]
/// Validates and copies a `bytes::Bytes` buffer into text storage.
///
/// This compatibility method discards the original buffer on error. New
/// code should use [`CheetahString::try_copy_from_bytes`] instead.
///
/// # Errors
///
/// Returns the UTF-8 validation error when the buffer is not valid text.
#[inline]
#[cfg(feature = "bytes")]
pub fn try_from_bytes_buf(b: bytes::Bytes) -> Result<Self, Utf8Error> {
CheetahString::try_copy_from_bytes(b).map_err(|error| error.into_parts().1)
}
/// Creates a `CheetahString` from `bytes::Bytes` without validating UTF-8.
///
/// # Safety
///
/// The caller must guarantee that `b` contains valid UTF-8.
#[inline]
#[cfg(feature = "bytes")]
pub unsafe fn from_utf8_unchecked_bytes_buf(b: bytes::Bytes) -> Self {
// SAFETY: the caller guarantees that the complete buffer is valid UTF-8.
unsafe { CheetahString::from_validated_bytes_unchecked(b) }
}
#[inline]
#[cfg(feature = "bytes")]
unsafe fn from_validated_bytes_unchecked(b: bytes::Bytes) -> Self {
// SAFETY: Callers validate UTF-8 before reaching this helper.
unsafe { CheetahString::from_utf8_unchecked_bytes(b.as_ref()) }
}
/// Borrows the value as a string slice.
#[inline]
pub fn as_str(&self) -> &str {
match &self.inner {
InnerString::Inline(inline) => inline.as_str(),
InnerString::Static(s) => s,
InnerString::Shared(s) => s.as_ref(),
}
}
/// Borrows the UTF-8 encoding as bytes.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
match &self.inner {
InnerString::Inline(inline) => inline.as_bytes(),
InnerString::Static(s) => s.as_bytes(),
InnerString::Shared(s) => s.as_bytes(),
}
}
/// Returns the UTF-8 length in bytes.
#[inline]
pub fn len(&self) -> usize {
match &self.inner {
InnerString::Inline(inline) => inline.len(),
InnerString::Static(s) => s.len(),
InnerString::Shared(s) => s.len(),
}
}
/// Returns `true` when the value contains no bytes.
#[inline]
pub fn is_empty(&self) -> bool {
match &self.inner {
InnerString::Inline(inline) => inline.is_empty(),
InnerString::Static(s) => s.is_empty(),
InnerString::Shared(s) => s.is_empty(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn long_borrowed_str_uses_shared_storage() {
let value = "a".repeat(INLINE_CAPACITY + 1);
let s = CheetahString::from_slice(&value);
match &s.inner {
InnerString::Shared(inner) => assert_eq!(inner.as_ref(), value.as_str()),
other => panic!(
"expected Shared for long borrowed input, got {:?}",
core::mem::discriminant(other)
),
}
}
#[test]
fn try_from_vec_short_input_uses_inline_storage() {
let s = CheetahString::try_from_vec(b"hello".to_vec()).expect("valid utf-8");
match &s.inner {
InnerString::Inline(inline) => {
assert_eq!(inline.len(), 5);
assert_eq!(inline.as_bytes(), b"hello");
}
other => panic!(
"expected inline storage for short validated Vec<u8>, got {:?}",
core::mem::discriminant(other)
),
}
}
#[test]
fn long_vec_conversion_uses_shared_storage() {
let value = "a".repeat(INLINE_CAPACITY + 1).into_bytes();
let s = CheetahString::try_from_vec(value).expect("valid utf-8");
match &s.inner {
InnerString::Shared(inner) => {
assert_eq!(inner.len(), INLINE_CAPACITY + 1);
assert!(inner.bytes().all(|byte| byte == b'a'));
}
other => panic!(
"expected Shared for long Vec<u8> conversion, got {:?}",
core::mem::discriminant(other)
),
}
}
}