-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcheetah_string.rs
More file actions
577 lines (522 loc) · 15.6 KB
/
cheetah_string.rs
File metadata and controls
577 lines (522 loc) · 15.6 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use core::fmt;
use core::str::Utf8Error;
use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::fmt::Display;
use std::hash::Hash;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::Arc;
#[derive(Clone)]
#[repr(transparent)]
pub struct CheetahString {
pub(super) inner: InnerString,
}
impl Default for CheetahString {
fn default() -> Self {
CheetahString {
inner: InnerString::Inline {
len: 0,
data: [0; INLINE_CAPACITY],
},
}
}
}
impl From<String> for CheetahString {
#[inline]
fn from(s: String) -> Self {
CheetahString::from_string(s)
}
}
impl From<Arc<String>> for CheetahString {
#[inline]
fn from(s: Arc<String>) -> Self {
CheetahString::from_arc_string(s)
}
}
impl<'a> From<&'a str> for CheetahString {
#[inline]
fn from(s: &'a str) -> Self {
CheetahString::from_slice(s)
}
}
/// # Safety Warning
///
/// This implementation uses `unsafe` code and may cause undefined behavior
/// if the bytes are not valid UTF-8. Consider using `CheetahString::try_from_bytes()`
/// for safe UTF-8 validation.
///
/// This implementation will be deprecated in a future version.
impl From<&[u8]> for CheetahString {
#[inline]
fn from(b: &[u8]) -> Self {
// SAFETY: This is unsafe and may cause UB if bytes are not valid UTF-8.
// This will be deprecated in favor of try_from_bytes in the next version.
CheetahString::from_slice(unsafe { std::str::from_utf8_unchecked(b) })
}
}
impl FromStr for CheetahString {
type Err = std::string::ParseError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(CheetahString::from_slice(s))
}
}
/// # Safety Warning
///
/// This implementation uses `unsafe` code and may cause undefined behavior
/// if the bytes are not valid UTF-8. Consider using `CheetahString::try_from_vec()`
/// for safe UTF-8 validation.
///
/// This implementation will be deprecated in a future version.
impl From<Vec<u8>> for CheetahString {
#[inline]
fn from(v: Vec<u8>) -> Self {
// SAFETY: This is unsafe and may cause UB if bytes are not valid UTF-8.
// This will be deprecated in favor of try_from_vec in the next version.
CheetahString::from_slice(unsafe { std::str::from_utf8_unchecked(&v) })
}
}
impl From<Cow<'static, str>> for CheetahString {
#[inline]
fn from(cow: Cow<'static, str>) -> Self {
match cow {
Cow::Borrowed(s) => CheetahString::from_static_str(s),
Cow::Owned(s) => CheetahString::from_string(s),
}
}
}
impl From<Cow<'_, String>> for CheetahString {
#[inline]
fn from(cow: Cow<'_, String>) -> Self {
match cow {
Cow::Borrowed(s) => CheetahString::from_slice(s),
Cow::Owned(s) => CheetahString::from_string(s),
}
}
}
impl From<char> for CheetahString {
/// Allocates an owned [`CheetahString`] from a single character.
///
/// # Example
/// ```rust
/// use cheetah_string::CheetahString;
/// let c: char = 'a';
/// let s: CheetahString = CheetahString::from(c);
/// assert_eq!("a", &s[..]);
/// ```
#[inline]
fn from(c: char) -> Self {
CheetahString::from_string(c.to_string())
}
}
impl<'a> FromIterator<&'a char> for CheetahString {
#[inline]
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> CheetahString {
let mut buf = String::new();
buf.extend(iter);
CheetahString::from_string(buf)
}
}
impl<'a> FromIterator<&'a str> for CheetahString {
fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> CheetahString {
let mut buf = String::new();
buf.extend(iter);
CheetahString::from_string(buf)
}
}
impl FromIterator<String> for CheetahString {
#[inline]
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
let mut buf = String::new();
buf.extend(iter);
CheetahString::from_string(buf)
}
}
impl<'a> FromIterator<&'a String> for CheetahString {
#[inline]
fn from_iter<T: IntoIterator<Item = &'a String>>(iter: T) -> Self {
let mut buf = String::new();
buf.extend(iter.into_iter().map(|s| s.as_str()));
CheetahString::from_string(buf)
}
}
#[cfg(feature = "bytes")]
impl From<bytes::Bytes> for CheetahString {
#[inline]
fn from(b: bytes::Bytes) -> Self {
CheetahString::from_bytes(b)
}
}
impl From<&CheetahString> for CheetahString {
#[inline]
fn from(s: &CheetahString) -> Self {
s.clone()
}
}
impl From<CheetahString> for String {
#[inline]
fn from(s: CheetahString) -> Self {
match s {
CheetahString {
inner: InnerString::Inline { len, data },
} => {
// SAFETY: Inline strings are always valid UTF-8
unsafe { String::from_utf8_unchecked(data[..len as usize].to_vec()) }
}
CheetahString {
inner: InnerString::StaticStr(s),
} => s.to_string(),
CheetahString {
inner: InnerString::ArcString(s),
} => s.as_ref().clone(),
CheetahString {
inner: InnerString::ArcVecString(s),
} => {
// SAFETY: ArcVecString should only be created from valid UTF-8 sources
unsafe { String::from_utf8_unchecked(s.to_vec()) }
}
#[cfg(feature = "bytes")]
CheetahString {
inner: InnerString::Bytes(b),
} => {
// SAFETY: Bytes variant should only be created from valid UTF-8 sources
unsafe { String::from_utf8_unchecked(b.to_vec()) }
}
}
}
}
impl Deref for CheetahString {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl AsRef<str> for CheetahString {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<[u8]> for CheetahString {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl AsRef<CheetahString> for CheetahString {
#[inline]
fn as_ref(&self) -> &CheetahString {
self
}
}
impl From<&String> for CheetahString {
#[inline]
fn from(s: &String) -> Self {
CheetahString::from_slice(s)
}
}
impl CheetahString {
#[inline]
pub const fn empty() -> Self {
CheetahString {
inner: InnerString::Inline {
len: 0,
data: [0; INLINE_CAPACITY],
},
}
}
#[inline]
pub fn new() -> Self {
CheetahString::default()
}
#[inline]
pub const fn from_static_str(s: &'static str) -> Self {
CheetahString {
inner: InnerString::StaticStr(s),
}
}
#[inline]
pub fn from_vec(s: Vec<u8>) -> Self {
CheetahString {
inner: InnerString::ArcVecString(Arc::new(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> {
// Validate UTF-8
std::str::from_utf8(&v)?;
Ok(CheetahString {
inner: InnerString::ArcVecString(Arc::new(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 = std::str::from_utf8(b)?;
Ok(CheetahString::from_slice(s))
}
#[inline]
pub fn from_arc_vec(s: Arc<Vec<u8>>) -> Self {
CheetahString {
inner: InnerString::ArcVecString(s),
}
}
#[inline]
pub fn from_slice(s: &str) -> Self {
if s.len() <= INLINE_CAPACITY {
// Use inline storage for short strings
let mut data = [0u8; INLINE_CAPACITY];
data[..s.len()].copy_from_slice(s.as_bytes());
CheetahString {
inner: InnerString::Inline {
len: s.len() as u8,
data,
},
}
} else {
// Use Arc for long strings
CheetahString {
inner: InnerString::ArcString(Arc::new(s.to_owned())),
}
}
}
#[inline]
pub fn from_string(s: String) -> Self {
if s.len() <= INLINE_CAPACITY {
// Use inline storage for short strings
let mut data = [0u8; INLINE_CAPACITY];
data[..s.len()].copy_from_slice(s.as_bytes());
CheetahString {
inner: InnerString::Inline {
len: s.len() as u8,
data,
},
}
} else {
// Use Arc for long strings
CheetahString {
inner: InnerString::ArcString(Arc::new(s)),
}
}
}
#[inline]
pub fn from_arc_string(s: Arc<String>) -> Self {
CheetahString {
inner: InnerString::ArcString(s),
}
}
#[inline]
#[cfg(feature = "bytes")]
pub fn from_bytes(b: bytes::Bytes) -> Self {
CheetahString {
inner: InnerString::Bytes(b),
}
}
#[inline]
pub fn as_str(&self) -> &str {
match &self.inner {
InnerString::Inline { len, data } => {
// SAFETY: Inline strings are only created from valid UTF-8 sources.
// The data is always valid UTF-8 up to len bytes.
unsafe { std::str::from_utf8_unchecked(&data[..*len as usize]) }
}
InnerString::StaticStr(s) => s,
InnerString::ArcString(s) => s.as_str(),
InnerString::ArcVecString(s) => {
// SAFETY: ArcVecString is only created from validated UTF-8 sources.
// All constructors ensure this invariant is maintained.
unsafe { std::str::from_utf8_unchecked(s.as_ref()) }
}
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => {
// SAFETY: Bytes variant is only created from validated UTF-8 sources.
// The from_bytes constructor ensures this invariant.
unsafe { std::str::from_utf8_unchecked(b.as_ref()) }
}
}
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
match &self.inner {
InnerString::Inline { len, data } => &data[..*len as usize],
InnerString::StaticStr(s) => s.as_bytes(),
InnerString::ArcString(s) => s.as_bytes(),
InnerString::ArcVecString(s) => s.as_ref(),
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => b.as_ref(),
}
}
#[inline]
pub fn len(&self) -> usize {
match &self.inner {
InnerString::Inline { len, .. } => *len as usize,
InnerString::StaticStr(s) => s.len(),
InnerString::ArcString(s) => s.len(),
InnerString::ArcVecString(s) => s.len(),
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => b.len(),
}
}
#[inline]
pub fn is_empty(&self) -> bool {
match &self.inner {
InnerString::Inline { len, .. } => *len == 0,
InnerString::StaticStr(s) => s.is_empty(),
InnerString::ArcString(s) => s.is_empty(),
InnerString::ArcVecString(s) => s.is_empty(),
#[cfg(feature = "bytes")]
InnerString::Bytes(b) => b.is_empty(),
}
}
}
impl PartialEq for CheetahString {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl PartialEq<str> for CheetahString {
#[inline]
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<String> for CheetahString {
#[inline]
fn eq(&self, other: &String) -> bool {
self.as_str() == other.as_str()
}
}
impl PartialEq<Vec<u8>> for CheetahString {
#[inline]
fn eq(&self, other: &Vec<u8>) -> bool {
self.as_bytes() == other.as_slice()
}
}
impl<'a> PartialEq<&'a str> for CheetahString {
#[inline]
fn eq(&self, other: &&'a str) -> bool {
self.as_str() == *other
}
}
impl PartialEq<CheetahString> for str {
#[inline]
fn eq(&self, other: &CheetahString) -> bool {
self == other.as_str()
}
}
impl PartialEq<CheetahString> for String {
#[inline]
fn eq(&self, other: &CheetahString) -> bool {
self.as_str() == other.as_str()
}
}
impl PartialEq<CheetahString> for &str {
#[inline]
fn eq(&self, other: &CheetahString) -> bool {
*self == other.as_str()
}
}
impl Eq for CheetahString {}
impl PartialOrd for CheetahString {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for CheetahString {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.as_str().cmp(other.as_str())
}
}
impl Hash for CheetahString {
#[inline]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
impl Display for CheetahString {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.as_str().fmt(f)
}
}
impl std::fmt::Debug for CheetahString {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
impl Borrow<str> for CheetahString {
#[inline]
fn borrow(&self) -> &str {
self.as_str()
}
}
/// Maximum capacity for inline string storage (23 bytes + 1 byte for length = 24 bytes total)
const INLINE_CAPACITY: usize = 23;
/// The `InnerString` enum represents different types of string storage.
///
/// This enum uses Small String Optimization (SSO) to avoid heap allocations for short strings.
///
/// Variants:
///
/// * `Inline` - Inline storage for strings <= 23 bytes (zero heap allocations).
/// * `StaticStr(&'static str)` - A static string slice (zero heap allocations).
/// * `ArcString(Arc<String>)` - A reference-counted string (one heap allocation).
/// * `ArcVecString(Arc<Vec<u8>>)` - A reference-counted byte vector.
/// * `Bytes(bytes::Bytes)` - A byte buffer (available when the "bytes" feature is enabled).
#[derive(Clone)]
pub(super) enum InnerString {
/// Inline storage for short strings (up to 23 bytes).
/// Stores the length and data directly without heap allocation.
Inline {
len: u8,
data: [u8; INLINE_CAPACITY],
},
/// Static string slice with 'static lifetime.
StaticStr(&'static str),
/// Reference-counted heap-allocated string.
ArcString(Arc<String>),
/// Reference-counted heap-allocated byte vector.
ArcVecString(Arc<Vec<u8>>),
/// Bytes type integration (requires "bytes" feature).
#[cfg(feature = "bytes")]
Bytes(bytes::Bytes),
}