smol-bytes 0.2.0

High-performance, clone-efficient byte buffers optimized for small data.
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use core::{borrow::Borrow, ops::RangeBounds, str};

use super::{
  bytes::{RawBytes, strategy::ImmutableStorage, visible_subslice_range},
  error::*,
  utf8_buf::{Utf8Buf, range_bounds_to_start_end, sealed, validate_char_boundary},
};

mod cmp;
mod fmt;
mod from;
mod iter;
mod ops;

#[cfg(feature = "arbitrary")]
mod arbitrary;
#[cfg(feature = "borsh")]
mod borsh;
#[cfg(feature = "quickcheck")]
mod quickcheck;
#[cfg(feature = "serde")]
mod serde;

#[cfg(feature = "pyo3")]
mod python;
#[cfg(feature = "pyo3")]
pub use python::PyCompactUtf8Bytes;
#[cfg(feature = "pyo3")]
pub use python::PySharedUtf8Bytes;

#[cfg(feature = "wasm")]
pub(crate) mod wasm;

/// Immutable UTF-8 string with inline/heap storage, generic over the
/// immutable storage strategy `S`.
///
/// Guarantees valid UTF-8. Supports zero-copy cloning via reference counting.
///
/// # Examples
///
/// ```
/// use smol_bytes::Utf8Bytes;
///
/// let bytes = Utf8Bytes::from("hello world");
/// let slice = bytes.slice(0..5);
/// assert_eq!(slice.as_str(), "hello");
/// ```
pub struct Utf8Bytes<S> {
  pub(crate) inner: RawBytes<S>,
}

impl<S> Clone for Utf8Bytes<S> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      inner: self.inner.clone(),
    }
  }
}

impl<S> sealed::Sealed for Utf8Bytes<S> {}

impl<S> Default for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  fn default() -> Self {
    Self::new()
  }
}

impl<S> Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  /// Creates a new, empty `Utf8Bytes`.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// const EMPTY: Utf8Bytes = Utf8Bytes::new();
  /// assert_eq!(EMPTY.as_str(), "");
  /// ```
  pub const fn new() -> Self {
    Self {
      inner: RawBytes::new(),
    }
  }

  /// Creates a `Utf8Bytes` from a static string slice.
  ///
  /// A string that fits the inline capacity is copied into the inline
  /// buffer; a longer one borrows the static allocation. Both paths are
  /// evaluable at compile time.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// const GREETING: Utf8Bytes = Utf8Bytes::from_static("hello");
  /// assert_eq!(GREETING.as_str(), "hello");
  /// ```
  pub const fn from_static(s: &'static str) -> Self {
    Self {
      inner: RawBytes::from_static(s.as_bytes()),
    }
  }

  /// Validates owned raw bytes as UTF-8 without losing their storage strategy
  /// or current view on failure.
  pub fn from_utf8(bytes: RawBytes<S>) -> Result<Self, FromUtf8Error<RawBytes<S>>> {
    match core::str::from_utf8(bytes.as_ref()) {
      Ok(_) => Ok(Self { inner: bytes }),
      Err(error) => Err(FromUtf8Error::new(bytes, error)),
    }
  }

  /// Decodes owned bytes as UTF-8, replacing malformed sequences with
  /// `U+FFFD`.
  ///
  /// Valid input keeps its storage strategy and current view. Invalid input is
  /// converted through an owned [`String`](std::string::String).
  ///
  /// ```
  /// use smol_bytes::{Bytes, Utf8Bytes};
  ///
  /// let text = Utf8Bytes::from_utf8_lossy(Bytes::from(&b"hi\xff"[..]));
  /// assert_eq!(text.as_str(), "hi\u{FFFD}");
  /// ```
  pub fn from_utf8_lossy(bytes: RawBytes<S>) -> Self {
    match Self::from_utf8(bytes) {
      Ok(value) => value,
      Err(error) => Self::from(std::string::String::from_utf8_lossy(error.as_bytes()).into_owned()),
    }
  }

  /// Returns a reference to the inner `RawBytes`.
  ///
  /// Note: named `as_inner` (not `as_bytes`) to avoid shadowing
  /// [`str::as_bytes`], which is reachable via [`Deref`](core::ops::Deref)
  /// to `str`. Use `self.as_ref::<[u8]>()` or `(*self).as_bytes()` if you
  /// want the raw `&[u8]`.
  pub const fn as_inner(&self) -> &RawBytes<S> {
    &self.inner
  }

  /// Consumes `self` and returns the inner `RawBytes`.
  pub fn into_inner(self) -> RawBytes<S> {
    self.inner
  }

  /// Tries to convert this view into mutable UTF-8 bytes without copying.
  ///
  /// The conversion succeeds when the underlying immutable bytes are uniquely
  /// owned and cover their full allocation. On failure, this exact view and
  /// storage strategy are returned unchanged.
  pub fn try_into_mut(self) -> Result<crate::Utf8BytesMut, Self> {
    match self.inner.try_into_mut() {
      Ok(inner) => Ok(crate::Utf8BytesMut { inner }),
      Err(inner) => Err(Self { inner }),
    }
  }

  /// Returns the contents as a string slice.
  #[inline]
  pub fn as_str(&self) -> &str {
    // SAFETY: Utf8Bytes guarantees valid UTF-8
    unsafe { str::from_utf8_unchecked(self.inner.as_ref()) }
  }

  /// Returns the length in bytes.
  #[inline]
  pub fn len(&self) -> usize {
    self.inner.len()
  }

  /// Returns `true` if the buffer has length 0.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.inner.is_empty()
  }

  /// Returns whether the bytes are stored inline.
  #[inline]
  pub fn is_inline(&self) -> bool {
    self.inner.is_inline()
  }

  /// Returns whether the bytes are stored on the heap.
  #[inline]
  pub fn is_heap(&self) -> bool {
    self.inner.is_heap()
  }

  /// Returns whether this is the only reference to its heap allocation.
  ///
  /// Inline values and static backing never report uniqueness.
  #[inline]
  pub fn is_unique(&self) -> bool {
    self.inner.is_unique()
  }

  /// Clears this value's visible view without changing the immutable payload.
  #[inline]
  pub fn clear(&mut self) {
    self.inner.clear();
  }

  /// Truncates this value's visible view at a UTF-8 character boundary.
  pub fn truncate(&mut self, new_len: usize) {
    self
      .try_truncate(new_len)
      .expect("new_len must lie on a UTF-8 character boundary");
  }

  /// Tries to truncate this value's visible view at a UTF-8 character boundary.
  pub fn try_truncate(&mut self, new_len: usize) -> Result<(), Utf8IndexError> {
    if new_len >= self.len() {
      return Ok(());
    }
    validate_char_boundary(self.as_str(), new_len)?;
    self.inner.truncate(new_len);
    Ok(())
  }

  /// Removes and returns the last Unicode scalar value.
  ///
  /// This operates on Unicode scalar values, not grapheme clusters. It never
  /// allocates; storage changes continue to follow the selected strategy.
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// let mut text = Utf8Bytes::from("aé");
  /// assert_eq!(text.pop(), Some('é'));
  /// assert_eq!(text.as_str(), "a");
  /// ```
  pub fn pop(&mut self) -> Option<char> {
    let ch = self.as_str().chars().next_back()?;
    self.truncate(self.len() - ch.len_utf8());
    Some(ch)
  }

  /// Advances this value's visible view by `cnt` UTF-8 bytes.
  pub fn advance(&mut self, cnt: usize) {
    self.try_advance(cnt).expect("advance failed");
  }

  /// Tries to advance this value's visible view by `cnt` UTF-8 bytes.
  pub fn try_advance(&mut self, cnt: usize) -> Result<(), Utf8IndexError> {
    validate_char_boundary(self.as_str(), cnt)?;
    self.inner.try_advance(cnt).expect("already checked bounds");
    Ok(())
  }

  /// Splits the bytes at the given index.
  ///
  /// # Panics
  ///
  /// Panics if `at` is not on a character boundary or is out of bounds.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// let mut bytes = Utf8Bytes::from("hello world");
  /// let head = bytes.split_to(5);
  ///
  /// assert_eq!(head.as_str(), "hello");
  /// assert_eq!(bytes.as_str(), " world");
  /// ```
  pub fn split_to(&mut self, at: usize) -> Self {
    self.try_split_to(at).expect("split_to failed")
  }

  /// Tries to split the bytes at the given index.
  ///
  /// # Errors
  ///
  /// Returns an error if `at` is out of bounds or not on a character boundary.
  pub fn try_split_to(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    <Self as Utf8Buf>::try_split_to(self, at)
  }

  /// Splits the bytes at the given index, returning the tail.
  ///
  /// # Panics
  ///
  /// Panics if `at` is not on a character boundary or is out of bounds.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// let mut bytes = Utf8Bytes::from("hello world");
  /// let tail = bytes.split_off(6);
  ///
  /// assert_eq!(bytes.as_str(), "hello ");
  /// assert_eq!(tail.as_str(), "world");
  /// ```
  pub fn split_off(&mut self, at: usize) -> Self {
    self.try_split_off(at).expect("split_off failed")
  }

  /// Tries to split the bytes at the given index, returning the tail.
  ///
  /// # Errors
  ///
  /// Returns an error if `at` is out of bounds or not on a character boundary.
  pub fn try_split_off(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    <Self as Utf8Buf>::try_split_off(self, at)
  }

  /// Returns a slice of this buffer.
  ///
  /// # Panics
  ///
  /// Panics if the range is not on character boundaries or is out of bounds.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// let bytes = Utf8Bytes::from("hello world");
  /// let slice = bytes.slice(0..5);
  ///
  /// assert_eq!(slice.as_str(), "hello");
  /// ```
  pub fn slice(&self, range: impl RangeBounds<usize>) -> Self {
    self.try_slice(range).expect("slice failed")
  }

  /// Tries to return a slice of this buffer.
  ///
  /// # Errors
  ///
  /// Returns an error if the range is out of bounds or not on character boundaries.
  pub fn try_slice(&self, range: impl RangeBounds<usize>) -> Result<Self, Utf8IndexError> {
    <Self as Utf8Buf>::try_slice(self, range)
  }

  /// Returns a slice identified by a string reference into this value's
  /// current visible view.
  ///
  /// A non-empty `subset` must be address-contained in the current view.
  /// Empty subsets always return the canonical empty value. The containment
  /// check is `O(1)`; shared heap views retain their allocation while compact
  /// short views may be inlined by the existing slice strategy.
  ///
  /// # Panics
  ///
  /// Panics when a non-empty subset is not contained in the current visible
  /// view.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// let text = Utf8Bytes::from("café");
  /// let accent = text.slice_ref(&text.as_str()[3..]);
  /// assert_eq!(accent.as_str(), "é");
  /// ```
  pub fn slice_ref(&self, subset: &str) -> Self {
    self
      .try_slice_ref(subset)
      .expect("slice_ref subset must be contained in the current visible view")
  }

  /// Attempts to return a slice identified by a string reference into this
  /// value's current visible view.
  ///
  /// Empty subsets are accepted regardless of origin. Existing UTF-8 slice
  /// validation remains responsible for validating the resulting byte range.
  ///
  /// # Examples
  ///
  /// ```
  /// use smol_bytes::Utf8Bytes;
  ///
  /// let text = Utf8Bytes::from("  café  ");
  /// let trimmed = text.try_slice_ref(text.as_str().trim()).unwrap();
  /// assert_eq!(trimmed.as_str(), "café");
  /// assert!(text.try_slice_ref("café").is_none());
  /// ```
  pub fn try_slice_ref(&self, subset: &str) -> Option<Self> {
    if subset.is_empty() {
      return Some(Self::new());
    }

    let range = visible_subslice_range(self.as_str().as_bytes(), subset.as_bytes())?;
    self.try_slice(range).ok()
  }
}

impl<S> AsRef<str> for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  fn as_ref(&self) -> &str {
    self.as_str()
  }
}

impl<S> AsRef<[u8]> for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  fn as_ref(&self) -> &[u8] {
    self.as_str().as_bytes()
  }
}

impl<S> Borrow<str> for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  fn borrow(&self) -> &str {
    self.as_str()
  }
}

impl<S> core::ops::Deref for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  type Target = str;

  fn deref(&self) -> &Self::Target {
    self.as_str()
  }
}

#[cfg(feature = "std")]
impl<S> AsRef<std::ffi::OsStr> for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  fn as_ref(&self) -> &std::ffi::OsStr {
    std::ffi::OsStr::new(self.as_str())
  }
}

#[cfg(feature = "std")]
impl<S> AsRef<std::path::Path> for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  fn as_ref(&self) -> &std::path::Path {
    std::path::Path::new(self.as_str())
  }
}

// The trait impl holds the real bodies. Inherent methods (above) forward
// here via explicit `<Self as Utf8Buf>::method` UFCS so there is no
// ambiguity about which impl is called and no fragile reliance on the
// inherent-over-trait method resolution rule.
impl<S> Utf8Buf for Utf8Bytes<S>
where
  RawBytes<S>: ImmutableStorage,
{
  fn try_split_to(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    validate_char_boundary(self.as_str(), at)?;
    Ok(Self {
      inner: self.inner.try_split_to(at).expect("already checked bounds"),
    })
  }

  fn try_split_off(&mut self, at: usize) -> Result<Self, Utf8IndexError> {
    validate_char_boundary(self.as_str(), at)?;
    Ok(Self {
      inner: self
        .inner
        .try_split_off(at)
        .expect("already checked bounds"),
    })
  }

  fn try_slice(&self, range: impl RangeBounds<usize>) -> Result<Self, Utf8IndexError> {
    let (start, end) = range_bounds_to_start_end(self.as_str(), range)?;
    Ok(Self {
      inner: self
        .inner
        .try_slice(start..end)
        .expect("already checked bounds"),
    })
  }
}