turbocow 0.3.0-beta.2

Compact, clone-on-write vectors, strings, maps and sets with inline + referenced storage — a superset of ecow.
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
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
//! A clone-on-write, small-buffer-optimized byte string.

use alloc::string::String;
use alloc::vec::Vec;
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt::{self, Debug, Formatter};
use core::hash::{Hash, Hasher};
use core::ops::Deref;

use crate::allocator::Global;
use crate::dynamic::{DynamicVec, InlineVec, LIMIT};

/// An economical byte string with inline storage and clone-on-write semantics.
///
/// This is the byte-oriented counterpart of [`EcoString`](super::EcoString).
/// It stores arbitrary `[u8]` data (not necessarily valid UTF-8) with the same
/// 16-byte footprint, 15-byte inline storage, and clone-on-write heap
/// fallback.
///
/// # Example
/// ```
/// use turbocow::EcoByteString;
///
/// let small = EcoByteString::from(&b"hello"[..]);
/// assert_eq!(&*small, b"hello");
///
/// let mut big = EcoByteString::from(&[0xffu8; 20][..]);
/// big.push(0x00);
/// assert_eq!(big.len(), 21);
/// ```
#[derive(Clone)]
pub struct EcoByteString(DynamicVec<'static>);

impl EcoByteString {
    /// Maximum number of bytes for an inline `EcoByteString` before spilling
    /// to the heap.
    ///
    /// # Note
    /// This value is semver exempt and can be changed with any update.
    pub const INLINE_LIMIT: usize = LIMIT;

    /// Create a new, empty byte string.
    #[inline]
    pub const fn new() -> Self {
        Self(DynamicVec::new())
    }

    /// Create a new, inline byte string.
    ///
    /// Panics if the slice length exceeds the capacity of the inline storage.
    #[inline]
    #[track_caller]
    pub fn inline(bytes: &[u8]) -> Self {
        let Ok(inline) = InlineVec::from_slice(bytes) else {
            exceeded_inline_capacity();
        };
        Self(DynamicVec::from_inline(inline))
    }

    /// Create a byte string that **borrows** a `'static` byte slice without
    /// copying (the Referenced variant).
    ///
    /// Construction is essentially free — no allocation or copy occurs.
    #[inline]
    pub fn from_static(bytes: &'static [u8]) -> Self {
        Self(DynamicVec::from_slice_in(bytes, Global))
    }

    /// Create a new, empty byte string with the given `capacity`.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self(DynamicVec::with_capacity(capacity))
    }

    /// Create an instance from a byte slice.
    #[inline]
    pub fn from_bytes(bytes: &[u8]) -> Self {
        Self(DynamicVec::from_slice(bytes))
    }

    /// Whether the byte string is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The length of the byte string in bytes.
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// A byte slice containing the entire byte string.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_slice()
    }

    /// Produce a mutable byte slice containing the entire byte string.
    ///
    /// Clones the byte string if its reference count is larger than 1.
    #[inline]
    pub fn make_mut(&mut self) -> &mut [u8] {
        self.0.make_mut(0)
    }

    /// Append the given byte at the end.
    #[inline]
    pub fn push(&mut self, byte: u8) {
        self.0.push(byte);
    }

    /// Append the given byte slice at the end.
    #[inline]
    pub fn extend_from_slice(&mut self, bytes: &[u8]) {
        self.0.extend_from_slice(bytes);
    }

    /// Remove and return the last byte, or `None` if empty.
    #[inline]
    pub fn pop(&mut self) -> Option<u8> {
        if self.is_empty() {
            return None;
        }
        let last = self.0.as_slice()[self.len() - 1];
        self.0.truncate(self.len() - 1);
        Some(last)
    }

    /// Clear the byte string.
    #[inline]
    pub fn clear(&mut self) {
        self.0.clear();
    }

    /// Shortens the byte string to the specified length.
    ///
    /// If `new_len` is greater than or equal to the current length, this has
    /// no effect.
    #[inline]
    pub fn truncate(&mut self, new_len: usize) {
        if new_len <= self.len() {
            self.0.truncate(new_len);
        }
    }

    /// Try to convert this byte string into an [`EcoString`](super::EcoString).
    ///
    /// Returns `Ok(EcoString)` if the bytes are valid UTF-8, or `Err(self)`
    /// if they are not.  This is a zero-copy operation — the underlying
    /// `DynamicVec` is moved directly into the `EcoString` wrapper.
    #[inline]
    pub fn into_eco_string(self) -> Result<super::EcoString, Self> {
        if core::str::from_utf8(self.as_bytes()).is_ok() {
            // Safety: just validated UTF-8.
            Ok(super::EcoString::from_raw(self.0))
        } else {
            Err(self)
        }
    }

    /// Convert this byte string into an [`EcoString`](super::EcoString),
    /// replacing invalid UTF-8 sequences with `U+FFFD REPLACEMENT CHARACTER`.
    ///
    /// If the bytes are already valid UTF-8, no allocation occurs beyond
    /// what the `EcoString` itself needs.
    pub fn into_eco_string_lossy(self) -> super::EcoString {
        match self.into_eco_string() {
            Ok(s) => s,
            Err(bytes) => {
                let lossy = String::from_utf8_lossy(bytes.as_bytes());
                super::EcoString::from(lossy.as_ref())
            }
        }
    }

    /// Repeat this byte string `n` times.
    pub fn repeat(&self, n: usize) -> Self {
        let slice = self.as_bytes();
        let capacity = slice.len().saturating_mul(n);
        let mut vec = DynamicVec::with_capacity(capacity);
        for _ in 0..n {
            vec.extend_from_slice(slice);
        }
        Self(vec)
    }
}

impl Deref for EcoByteString {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Default for EcoByteString {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Debug for EcoByteString {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Debug::fmt(self.as_bytes(), f)
    }
}

impl Eq for EcoByteString {}

impl PartialEq for EcoByteString {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl PartialEq<[u8]> for EcoByteString {
    #[inline]
    fn eq(&self, other: &[u8]) -> bool {
        self.as_bytes() == other
    }
}

impl PartialEq<&[u8]> for EcoByteString {
    #[inline]
    fn eq(&self, other: &&[u8]) -> bool {
        self.as_bytes() == *other
    }
}

impl<const N: usize> PartialEq<[u8; N]> for EcoByteString {
    #[inline]
    fn eq(&self, other: &[u8; N]) -> bool {
        self.as_bytes() == other.as_slice()
    }
}

impl<const N: usize> PartialEq<&[u8; N]> for EcoByteString {
    #[inline]
    fn eq(&self, other: &&[u8; N]) -> bool {
        self.as_bytes() == other.as_slice()
    }
}

impl PartialEq<EcoByteString> for [u8] {
    #[inline]
    fn eq(&self, other: &EcoByteString) -> bool {
        self == other.as_bytes()
    }
}

impl PartialEq<EcoByteString> for &[u8] {
    #[inline]
    fn eq(&self, other: &EcoByteString) -> bool {
        *self == other.as_bytes()
    }
}

impl Ord for EcoByteString {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_bytes().cmp(other.as_bytes())
    }
}

impl PartialOrd for EcoByteString {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Hash for EcoByteString {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_bytes().hash(state);
    }
}

impl AsRef<[u8]> for EcoByteString {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Borrow<[u8]> for EcoByteString {
    #[inline]
    fn borrow(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl From<&[u8]> for EcoByteString {
    #[inline]
    fn from(bytes: &[u8]) -> Self {
        Self::from_bytes(bytes)
    }
}

impl<const N: usize> From<&[u8; N]> for EcoByteString {
    #[inline]
    fn from(bytes: &[u8; N]) -> Self {
        Self::from_bytes(bytes.as_slice())
    }
}

impl From<Vec<u8>> for EcoByteString {
    /// When the data does not fit inline, this needs to allocate to change
    /// the layout.
    #[inline]
    fn from(v: Vec<u8>) -> Self {
        Self::from_bytes(&v)
    }
}

impl From<&Vec<u8>> for EcoByteString {
    #[inline]
    fn from(v: &Vec<u8>) -> Self {
        Self::from_bytes(v.as_slice())
    }
}

impl From<&EcoByteString> for EcoByteString {
    #[inline]
    fn from(s: &EcoByteString) -> Self {
        s.clone()
    }
}

impl From<super::EcoString> for EcoByteString {
    /// Zero-cost conversion: moves the underlying `DynamicVec` directly.
    #[inline]
    fn from(s: super::EcoString) -> Self {
        Self(s.into_raw())
    }
}

impl From<&super::EcoString> for EcoByteString {
    #[inline]
    fn from(s: &super::EcoString) -> Self {
        Self::from_bytes(s.as_bytes())
    }
}

impl TryFrom<EcoByteString> for super::EcoString {
    type Error = EcoByteString;

    /// Zero-copy conversion if the bytes are valid UTF-8.
    ///
    /// Delegates to [`EcoByteString::into_eco_string`].
    #[inline]
    fn try_from(value: EcoByteString) -> Result<Self, Self::Error> {
        value.into_eco_string()
    }
}

impl FromIterator<u8> for EcoByteString {
    #[inline]
    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
        let mut s = Self::new();
        for byte in iter {
            s.push(byte);
        }
        s
    }
}

impl FromIterator<Self> for EcoByteString {
    #[inline]
    fn from_iter<T: IntoIterator<Item = Self>>(iter: T) -> Self {
        let mut s = Self::new();
        for piece in iter {
            s.extend_from_slice(&piece);
        }
        s
    }
}

impl<'a> FromIterator<&'a [u8]> for EcoByteString {
    #[inline]
    fn from_iter<T: IntoIterator<Item = &'a [u8]>>(iter: T) -> Self {
        let mut buf = Self::new();
        buf.extend(iter);
        buf
    }
}

impl Extend<u8> for EcoByteString {
    #[inline]
    fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
        for byte in iter {
            self.push(byte);
        }
    }
}

impl<'a> Extend<&'a [u8]> for EcoByteString {
    #[inline]
    fn extend<T: IntoIterator<Item = &'a [u8]>>(&mut self, iter: T) {
        iter.into_iter().for_each(move |s| self.extend_from_slice(s));
    }
}

impl From<EcoByteString> for Vec<u8> {
    /// This needs to allocate to change the layout.
    #[inline]
    fn from(s: EcoByteString) -> Self {
        s.as_bytes().to_vec()
    }
}

impl From<&EcoByteString> for Vec<u8> {
    #[inline]
    fn from(s: &EcoByteString) -> Self {
        s.as_bytes().to_vec()
    }
}

#[cold]
#[track_caller]
fn exceeded_inline_capacity() -> ! {
    panic!("exceeded inline capacity");
}

#[cfg(feature = "serde")]
mod serde {
    use crate::EcoByteString;
    use core::fmt;
    use serde::de::{Deserializer, Visitor};

    impl serde::Serialize for EcoByteString {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            serializer.serialize_bytes(self.as_bytes())
        }
    }

    impl<'de> serde::Deserialize<'de> for EcoByteString {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            struct EcoByteStringVisitor;

            impl Visitor<'_> for EcoByteStringVisitor {
                type Value = EcoByteString;

                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    formatter.write_str("a byte string")
                }

                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
                where
                    E: serde::de::Error,
                {
                    Ok(EcoByteString::from(v))
                }
            }

            deserializer.deserialize_bytes(EcoByteStringVisitor)
        }
    }
}