bytestring/lib.rs
1//! A UTF-8 encoded read-only string using `Bytes` as storage.
2//!
3//! See docs for [`ByteString`].
4//!
5//! # Crate Features
6//! - `simd`: Uses `simdutf8` (`#![no_std]`) for SIMD-accelerated UTF-8 validation (NEON on
7//! `aarch64`, `simd128` on `wasm32` when enabled, and SSE4.2/AVX2 on `x86`/`x86_64` when enabled
8//! at compile time or via the `std` feature).
9//! - `std`: Enables runtime CPU feature detection (AVX2/SSE4.2) in `simdutf8` on `x86`/`x86_64`
10//! targets. `bytestring` itself remains `#![no_std]`.
11//! - `serde`: Enables `Serialize` and `Deserialize` implementations for [`ByteString`].
12
13#![no_std]
14
15extern crate alloc;
16
17#[cfg(feature = "serde")]
18mod serde;
19
20use alloc::{boxed::Box, string::String, vec::Vec};
21use core::{borrow::Borrow, fmt, hash, ops, str};
22
23use bytes::Bytes;
24
25/// An immutable UTF-8 encoded string using [`Bytes`] as the storage.
26#[doc(alias = "BytesStr")]
27#[doc(alias = "ByteStr")]
28#[doc(alias = "Str")]
29#[doc(alias = "String")]
30#[doc(alias = "SharedString")]
31#[doc(alias = "SharedStr")]
32#[doc(alias = "ArcStr")]
33#[doc(alias = "RcStr")]
34#[doc(alias = "ImmutableString")]
35#[doc(alias = "Utf8String")]
36#[doc(alias = "Utf8Bytes")]
37#[doc(alias = "UTF-8")]
38#[doc(alias = "byte string")]
39#[doc(alias = "shared string")]
40#[doc(alias = "reference counted string")]
41#[doc(alias = "immutable string")]
42#[doc(alias = "read-only string")]
43#[doc(alias = "zero-copy string")]
44#[derive(Clone, Default, Eq, PartialOrd, Ord)]
45pub struct ByteString(Bytes);
46
47impl ByteString {
48 /// Creates a new empty `ByteString`.
49 ///
50 /// # Examples
51 /// ```
52 /// # use bytestring::ByteString;
53 /// let text = ByteString::new();
54 /// assert_eq!(text, "");
55 /// ```
56 #[doc(alias = "empty")]
57 #[inline]
58 #[must_use]
59 pub const fn new() -> Self {
60 ByteString(Bytes::new())
61 }
62
63 /// Creates a new `ByteString` from a `&'static str`.
64 ///
65 /// # Examples
66 /// ```
67 /// # use bytestring::ByteString;
68 /// let text = ByteString::from_static("hello");
69 /// assert_eq!(text, "hello");
70 /// ```
71 #[doc(alias = "from_static_str")]
72 #[inline]
73 #[must_use]
74 pub const fn from_static(src: &'static str) -> ByteString {
75 Self(Bytes::from_static(src.as_bytes()))
76 }
77
78 /// Creates a string whose storage remains owned by `owner`.
79 ///
80 /// The contents are not copied. The owner is dropped when the last shared
81 /// view of the storage is dropped. See [`Bytes::from_owner`].
82 ///
83 /// # Examples
84 /// ```
85 /// # use bytestring::ByteString;
86 /// use std::sync::Arc;
87 ///
88 /// let text = ByteString::from_owner(Arc::<str>::from("hello"));
89 /// assert_eq!(text, "hello");
90 /// ```
91 #[must_use]
92 pub fn from_owner<T>(owner: T) -> Self
93 where
94 T: AsRef<str> + Send + 'static,
95 {
96 struct Owner<T>(T);
97
98 impl<T: AsRef<str>> AsRef<[u8]> for Owner<T> {
99 fn as_ref(&self) -> &[u8] {
100 self.0.as_ref().as_bytes()
101 }
102 }
103
104 // The owner's string reference guarantees that the bytes are valid UTF-8.
105 Self(Bytes::from_owner(Owner(owner)))
106 }
107
108 /// Converts bytes to a string, retaining the bytes if UTF-8 validation fails.
109 ///
110 /// # Errors
111 /// Returns [`FromUtf8Error`] if the bytes are not valid UTF-8.
112 ///
113 /// # Examples
114 /// ```
115 /// use bytes::Bytes;
116 ///
117 /// # use bytestring::ByteString;
118 /// let err = ByteString::from_utf8(Bytes::from_static(b"hello\xff")).unwrap_err();
119 /// assert_eq!(err.utf8_error().valid_up_to(), 5);
120 /// assert_eq!(err.into_bytes(), Bytes::from_static(b"hello\xff"));
121 /// ```
122 #[inline]
123 pub fn from_utf8(bytes: Bytes) -> Result<Self, FromUtf8Error> {
124 match validate_utf8(&bytes) {
125 Ok(()) => Ok(Self(bytes)),
126 Err(error) => Err(FromUtf8Error { bytes, error }),
127 }
128 }
129
130 /// Creates a new `ByteString` from a Bytes.
131 ///
132 /// # Safety
133 /// This function is unsafe because it does not check the bytes passed to it are valid UTF-8.
134 /// If this constraint is violated, it may cause memory unsafety issues with future users of
135 /// the `ByteString`, as we assume that `ByteString`s are valid UTF-8. However, the most likely
136 /// issue is that the data gets corrupted.
137 ///
138 /// # Examples
139 /// ```
140 /// # use bytestring::ByteString;
141 /// let bytes = bytes::Bytes::from_static(b"hello");
142 ///
143 /// // SAFETY: The bytes contain valid UTF-8.
144 /// let text = unsafe { ByteString::from_bytes_unchecked(bytes) };
145 /// assert_eq!(text, "hello");
146 /// ```
147 #[doc(alias = "from_utf8_unchecked")]
148 #[inline]
149 #[must_use]
150 pub const unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString {
151 Self(src)
152 }
153
154 /// Returns the length in bytes.
155 ///
156 /// # Examples
157 /// ```
158 /// # use bytestring::ByteString;
159 /// let text = ByteString::from("hello");
160 /// assert_eq!(text.len(), 5);
161 /// ```
162 #[inline]
163 #[must_use]
164 pub const fn len(&self) -> usize {
165 self.0.len()
166 }
167
168 /// Returns true if this string is empty.
169 ///
170 /// # Examples
171 /// ```
172 /// # use bytestring::ByteString;
173 /// let text = ByteString::new();
174 /// assert!(text.is_empty());
175 /// ```
176 #[inline]
177 #[must_use]
178 pub const fn is_empty(&self) -> bool {
179 self.0.is_empty()
180 }
181
182 /// Returns the string contents as a string slice.
183 ///
184 /// # Examples
185 /// ```
186 /// # use bytestring::ByteString;
187 /// let text = ByteString::from("hello");
188 /// assert_eq!(text.as_str(), "hello");
189 /// ```
190 #[inline]
191 #[must_use]
192 pub fn as_str(&self) -> &str {
193 self
194 }
195
196 /// Get a reference to the underlying `Bytes` object.
197 ///
198 /// # Examples
199 /// ```
200 /// # use bytestring::ByteString;
201 /// let text = ByteString::from("hello");
202 /// assert_eq!(text.as_bytes(), &bytes::Bytes::from_static(b"hello"));
203 /// ```
204 #[doc(alias = "as_inner")]
205 #[doc(alias = "as_ref")]
206 #[inline]
207 #[must_use]
208 pub const fn as_bytes(&self) -> &Bytes {
209 &self.0
210 }
211
212 /// Returns a shared slice for the given byte range.
213 ///
214 /// This operation does not copy the string contents.
215 ///
216 /// # Panics
217 /// Panics if the range is out of bounds, reversed, or does not start and end
218 /// on UTF-8 code point boundaries.
219 ///
220 /// # Examples
221 /// ```
222 /// # use bytestring::ByteString;
223 /// let text = ByteString::from("aµz");
224 /// assert_eq!(text.slice(1..3), "µ");
225 /// ```
226 #[must_use]
227 pub fn slice(&self, range: impl ops::RangeBounds<usize>) -> Self {
228 use ops::Bound;
229
230 let start = match range.start_bound() {
231 Bound::Included(&n) => n,
232 Bound::Excluded(&n) => n.checked_add(1).expect("range start overflow"),
233 Bound::Unbounded => 0,
234 };
235
236 let end = match range.end_bound() {
237 Bound::Included(&n) => n.checked_add(1).expect("range end overflow"),
238 Bound::Excluded(&n) => n,
239 Bound::Unbounded => self.len(),
240 };
241
242 self.slice_ref(&self[start..end])
243 }
244
245 /// Returns a new `ByteString` that is equivalent to the given `subset`.
246 ///
247 /// When processing a `ByteString` buffer with other tools, one often gets a `&str` which is in
248 /// fact a slice of the original `ByteString`; i.e., a subset of it. This function turns that
249 /// `&str` into another `ByteString`, as if one had sliced the `ByteString` with the offsets
250 /// that correspond to `subset`.
251 ///
252 /// Corresponds to [`Bytes::slice_ref`].
253 ///
254 /// This operation is `O(1)`.
255 ///
256 /// # Panics
257 /// Panics if `subset` is not a sub-slice of this byte string.
258 ///
259 /// Note that strings which are only subsets from an equality perspective do not uphold this
260 /// requirement; see examples.
261 ///
262 /// # Examples
263 /// ```
264 /// # use bytestring::ByteString;
265 /// let string = ByteString::from_static(" foo ");
266 /// let subset = string.trim();
267 /// let substring = string.slice_ref(subset);
268 /// assert_eq!(substring, "foo");
269 /// ```
270 ///
271 /// ```should_panic
272 /// # use bytestring::ByteString;
273 /// // panics because the given slice is not derived from the original byte string, despite
274 /// // being a logical subset of the string
275 /// let _ = ByteString::from_static("foo bar").slice_ref("foo");
276 /// ```
277 #[doc(alias = "slice")]
278 #[doc(alias = "substring")]
279 #[doc(alias = "substr")]
280 #[doc(alias = "subslice")]
281 #[inline]
282 #[must_use]
283 pub fn slice_ref(&self, subset: &str) -> Self {
284 Self(self.0.slice_ref(subset.as_bytes()))
285 }
286
287 /// Splits off the suffix at the given byte index, retaining the prefix.
288 ///
289 /// The returned string shares storage with this string.
290 ///
291 /// # Panics
292 /// Panics if `at` is out of bounds or is not a UTF-8 code point boundary.
293 ///
294 /// # Examples
295 /// ```
296 /// # use bytestring::ByteString;
297 /// let mut text = ByteString::from("hello world");
298 /// let suffix = text.split_off(5);
299 ///
300 /// assert_eq!(text, "hello");
301 /// assert_eq!(suffix, " world");
302 /// ```
303 #[inline]
304 #[must_use = "use truncate if the suffix is not needed"]
305 pub fn split_off(&mut self, at: usize) -> Self {
306 assert!(self.is_char_boundary(at), "invalid split boundary");
307
308 Self(self.0.split_off(at))
309 }
310
311 /// Splits off the prefix at the given byte index, retaining the suffix.
312 ///
313 /// The returned string shares storage with this string.
314 ///
315 /// # Panics
316 /// Panics if `at` is out of bounds or is not a UTF-8 code point boundary.
317 ///
318 /// # Examples
319 /// ```
320 /// # use bytestring::ByteString;
321 /// let mut text = ByteString::from("hello world");
322 /// let prefix = text.split_to(5);
323 ///
324 /// assert_eq!(text, " world");
325 /// assert_eq!(prefix, "hello");
326 /// ```
327 #[inline]
328 #[must_use = "use advance if the prefix is not needed"]
329 pub fn split_to(&mut self, at: usize) -> Self {
330 assert!(self.is_char_boundary(at), "invalid split boundary");
331
332 Self(self.0.split_to(at))
333 }
334
335 /// Divides one bytestring into two at an index, returning both parts.
336 ///
337 /// # Panics
338 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is past the end of the last
339 /// code point of the bytestring.
340 ///
341 /// # Examples
342 /// ```
343 /// # use bytestring::ByteString;
344 /// let text = ByteString::from("hello world");
345 /// let (prefix, suffix) = text.split_at(5);
346 ///
347 /// assert_eq!(prefix, "hello");
348 /// assert_eq!(suffix, " world");
349 /// assert_eq!(text, "hello world");
350 /// ```
351 #[doc(alias = "split")]
352 #[must_use]
353 pub fn split_at(&self, mid: usize) -> (ByteString, ByteString) {
354 let this: &str = self.as_ref();
355 let _valid_midpoint_check = this.split_at(mid);
356
357 let mut bytes = self.0.clone();
358 let first = bytes.split_to(mid);
359 let last = bytes;
360
361 unsafe {
362 (
363 ByteString::from_bytes_unchecked(first),
364 ByteString::from_bytes_unchecked(last),
365 )
366 }
367 }
368
369 /// Retains the first `len` bytes. Does nothing if `len` exceeds the length.
370 ///
371 /// # Panics
372 /// Panics if `len` is within the string but is not a UTF-8 code point boundary.
373 ///
374 /// # Examples
375 /// ```
376 /// # use bytestring::ByteString;
377 /// let mut text = ByteString::from("hello world");
378 /// text.truncate(5);
379 /// assert_eq!(text, "hello");
380 /// ```
381 #[inline]
382 pub fn truncate(&mut self, len: usize) {
383 assert!(
384 len >= self.len() || self.is_char_boundary(len),
385 "invalid truncate boundary"
386 );
387
388 self.0.truncate(len);
389 }
390
391 /// Removes the first `cnt` bytes without copying the remaining contents.
392 ///
393 /// # Panics
394 /// Panics if `cnt` is out of bounds or is not a UTF-8 code point boundary.
395 ///
396 /// # Examples
397 /// ```
398 /// # use bytestring::ByteString;
399 /// let mut text = ByteString::from("µ: value");
400 /// text.advance(4);
401 /// assert_eq!(text, "value");
402 /// ```
403 #[inline]
404 pub fn advance(&mut self, cnt: usize) {
405 assert!(self.is_char_boundary(cnt), "invalid advance boundary");
406
407 bytes::Buf::advance(&mut self.0, cnt);
408 }
409
410 /// Unwraps this `ByteString` into the underlying `Bytes` object.
411 ///
412 /// # Examples
413 /// ```
414 /// # use bytestring::ByteString;
415 /// let text = ByteString::from("hello");
416 /// assert_eq!(text.into_bytes(), bytes::Bytes::from_static(b"hello"));
417 /// ```
418 #[doc(alias = "into_inner")]
419 #[doc(alias = "unwrap")]
420 #[inline]
421 #[must_use]
422 pub fn into_bytes(self) -> Bytes {
423 self.0
424 }
425}
426
427impl PartialEq<str> for ByteString {
428 #[inline]
429 fn eq(&self, other: &str) -> bool {
430 &self[..] == other
431 }
432}
433
434impl<T: AsRef<str>> PartialEq<T> for ByteString {
435 #[inline]
436 fn eq(&self, other: &T) -> bool {
437 &self[..] == other.as_ref()
438 }
439}
440
441impl AsRef<ByteString> for ByteString {
442 #[inline]
443 fn as_ref(&self) -> &ByteString {
444 self
445 }
446}
447
448impl AsRef<[u8]> for ByteString {
449 #[inline]
450 fn as_ref(&self) -> &[u8] {
451 self.0.as_ref()
452 }
453}
454
455impl AsRef<str> for ByteString {
456 #[inline]
457 fn as_ref(&self) -> &str {
458 self
459 }
460}
461
462impl hash::Hash for ByteString {
463 #[inline]
464 fn hash<H: hash::Hasher>(&self, state: &mut H) {
465 (**self).hash(state);
466 }
467}
468
469impl ops::Deref for ByteString {
470 type Target = str;
471
472 #[inline]
473 fn deref(&self) -> &str {
474 let bytes = self.0.as_ref();
475 // SAFETY: UTF-8 validity is guaranteed during construction.
476 unsafe { str::from_utf8_unchecked(bytes) }
477 }
478}
479
480impl Borrow<str> for ByteString {
481 #[inline]
482 fn borrow(&self) -> &str {
483 self
484 }
485}
486
487impl From<ByteString> for Bytes {
488 fn from(value: ByteString) -> Self {
489 value.into_bytes()
490 }
491}
492
493impl From<String> for ByteString {
494 #[inline]
495 fn from(value: String) -> Self {
496 Self(Bytes::from(value))
497 }
498}
499
500impl From<&str> for ByteString {
501 #[inline]
502 fn from(value: &str) -> Self {
503 Self(Bytes::copy_from_slice(value.as_ref()))
504 }
505}
506
507impl From<Box<str>> for ByteString {
508 #[inline]
509 fn from(value: Box<str>) -> Self {
510 Self(Bytes::from(value.into_boxed_bytes()))
511 }
512}
513
514impl From<ByteString> for String {
515 #[inline]
516 fn from(value: ByteString) -> Self {
517 // SAFETY: UTF-8 validity is guaranteed during construction.
518 unsafe { String::from_utf8_unchecked(value.0.into()) }
519 }
520}
521
522/// Validates that `bytes` is valid UTF-8, returning the exact [`str::Utf8Error`] on failure.
523#[cfg(feature = "simd")]
524fn validate_utf8(bytes: &[u8]) -> Result<(), str::Utf8Error> {
525 // `simdutf8` falls back to `core::str::from_utf8` for slices shorter than 64 bytes (its SIMD
526 // chunk size). Handling short slices here avoids dispatch overhead, avoids validating invalid
527 // short inputs twice, and preserves an ASCII fast path for common short strings.
528 if bytes.len() < 64 {
529 if bytes.is_ascii() {
530 return Ok(());
531 }
532 return str::from_utf8(bytes).map(|_| ());
533 }
534
535 if simdutf8::compat::from_utf8(bytes).is_ok() {
536 return Ok(());
537 }
538
539 validate_utf8_err(bytes)
540}
541
542/// Validates that `bytes` is valid UTF-8, using a chunked ASCII fast path to avoid double-scanning
543/// an ASCII prefix before a late non-ASCII byte while preserving exact [`str::Utf8Error`] values.
544#[cfg(not(feature = "simd"))]
545fn validate_utf8(bytes: &[u8]) -> Result<(), str::Utf8Error> {
546 const CHUNK_SIZE: usize = 64;
547
548 let (chunks, remainder) = bytes.as_chunks::<CHUNK_SIZE>();
549 let mut offset = 0;
550 for chunk in chunks {
551 if !chunk.is_ascii() {
552 let tail = &bytes[offset..];
553 return match str::from_utf8(tail) {
554 Ok(_) => Ok(()),
555 Err(err) if offset == 0 => Err(err),
556 Err(_) => validate_utf8_err(bytes),
557 };
558 }
559 offset += CHUNK_SIZE;
560 }
561
562 if remainder.is_ascii() {
563 return Ok(());
564 }
565
566 match str::from_utf8(remainder) {
567 Ok(_) => Ok(()),
568 Err(err) if offset == 0 => Err(err),
569 Err(_) => validate_utf8_err(bytes),
570 }
571}
572
573#[cold]
574fn validate_utf8_err(bytes: &[u8]) -> Result<(), str::Utf8Error> {
575 str::from_utf8(bytes).map(|_| ())
576}
577
578impl TryFrom<&[u8]> for ByteString {
579 type Error = str::Utf8Error;
580
581 #[inline]
582 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
583 validate_utf8(value)?;
584 Ok(ByteString(Bytes::copy_from_slice(value)))
585 }
586}
587
588impl TryFrom<Vec<u8>> for ByteString {
589 type Error = str::Utf8Error;
590
591 #[inline]
592 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
593 validate_utf8(&value)?;
594 Ok(ByteString(Bytes::from(value)))
595 }
596}
597
598impl TryFrom<Bytes> for ByteString {
599 type Error = str::Utf8Error;
600
601 #[inline]
602 fn try_from(value: Bytes) -> Result<Self, Self::Error> {
603 validate_utf8(&value)?;
604 Ok(ByteString(value))
605 }
606}
607
608impl TryFrom<bytes::BytesMut> for ByteString {
609 type Error = str::Utf8Error;
610
611 #[inline]
612 fn try_from(value: bytes::BytesMut) -> Result<Self, Self::Error> {
613 validate_utf8(&value)?;
614 Ok(ByteString(value.freeze()))
615 }
616}
617
618macro_rules! array_impls {
619 ($($len:expr)+) => {
620 $(
621 impl TryFrom<[u8; $len]> for ByteString {
622 type Error = str::Utf8Error;
623
624 #[inline]
625 fn try_from(value: [u8; $len]) -> Result<Self, Self::Error> {
626 ByteString::try_from(&value[..])
627 }
628 }
629
630 impl TryFrom<&[u8; $len]> for ByteString {
631 type Error = str::Utf8Error;
632
633 #[inline]
634 fn try_from(value: &[u8; $len]) -> Result<Self, Self::Error> {
635 ByteString::try_from(&value[..])
636 }
637 }
638 )+
639 }
640}
641
642array_impls!(0 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);
643
644impl fmt::Debug for ByteString {
645 #[inline]
646 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
647 fmt::Debug::fmt(&**self, fmt)
648 }
649}
650
651impl fmt::Display for ByteString {
652 #[inline]
653 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
654 fmt::Display::fmt(&**self, fmt)
655 }
656}
657
658/// An error from [`ByteString::from_utf8`] that retains the original bytes.
659#[derive(Debug, Clone, PartialEq, Eq)]
660pub struct FromUtf8Error {
661 bytes: Bytes,
662 error: str::Utf8Error,
663}
664
665impl FromUtf8Error {
666 /// Returns the original bytes without copying them.
667 ///
668 /// # Examples
669 /// ```
670 /// # use bytestring::ByteString;
671 /// let bytes = bytes::Bytes::from_static(b"a\xff");
672 /// let err = ByteString::from_utf8(bytes).unwrap_err();
673 /// assert_eq!(err.into_bytes(), bytes::Bytes::from_static(b"a\xff"));
674 /// ```
675 #[inline]
676 #[must_use]
677 pub fn into_bytes(self) -> Bytes {
678 self.bytes
679 }
680
681 /// Returns details of the UTF-8 validation failure.
682 ///
683 /// # Examples
684 /// ```
685 /// # use bytestring::ByteString;
686 /// let bytes = bytes::Bytes::from_static(b"a\xff");
687 /// let err = ByteString::from_utf8(bytes).unwrap_err();
688 ///
689 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
690 /// assert_eq!(err.utf8_error().error_len(), Some(1));
691 /// ```
692 #[inline]
693 #[must_use]
694 pub const fn utf8_error(&self) -> str::Utf8Error {
695 self.error
696 }
697}
698
699impl fmt::Display for FromUtf8Error {
700 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
701 fmt::Display::fmt(&self.error, f)
702 }
703}
704
705impl core::error::Error for FromUtf8Error {}
706
707#[cfg(test)]
708mod tests {
709 use core::panic::{RefUnwindSafe, UnwindSafe};
710
711 use static_assertions::assert_impl_all;
712
713 use super::*;
714
715 assert_impl_all!(ByteString: Send, Sync, Unpin, Sized);
716 assert_impl_all!(ByteString: Clone, Default, Eq, PartialOrd, Ord);
717 assert_impl_all!(ByteString: fmt::Debug, fmt::Display);
718 assert_impl_all!(ByteString: UnwindSafe, RefUnwindSafe);
719}