bytes_str/
byte_string.rs

1use std::{
2    borrow::{Borrow, BorrowMut, Cow},
3    cmp::Ordering,
4    convert::Infallible,
5    ffi::OsStr,
6    fmt::{self, Debug, Display},
7    hash::{Hash, Hasher},
8    net::{SocketAddr, ToSocketAddrs},
9    ops::{Add, AddAssign, Deref, DerefMut, Index, IndexMut},
10    path::Path,
11    slice::SliceIndex,
12    str::{FromStr, Utf8Error},
13};
14
15use bytes::{Bytes, BytesMut};
16
17/// [String] but backed by a [BytesMut]
18///
19/// # Features
20///
21/// ## `serde`
22///
23/// If the `serde` feature is enabled, the [BytesString] type will be
24/// [serde::Serialize] and [serde::Deserialize].
25///
26/// The [BytesString] type will be serialized just like a [String] type.
27#[derive(Clone, Default, PartialEq, Eq)]
28pub struct BytesString {
29    pub(crate) bytes: BytesMut,
30}
31
32impl BytesString {
33    /// Returns a new, empty BytesString.
34    ///
35    /// # Examples
36    ///
37    /// ```
38    /// use bytes_str::BytesString;
39    ///
40    /// let s = BytesString::new();
41    ///
42    /// assert!(s.is_empty());
43    /// ```
44    pub fn new() -> Self {
45        Self {
46            bytes: BytesMut::new(),
47        }
48    }
49
50    /// Returns a new, empty BytesString with the specified capacity.
51    ///
52    /// The capacity is the size of the internal buffer in bytes.
53    ///
54    /// The actual capacity may be larger than the specified capacity.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// use bytes_str::BytesString;
60    ///
61    /// let s = BytesString::with_capacity(10);
62    ///
63    /// assert!(s.capacity() >= 10);
64    /// ```
65    pub fn with_capacity(capacity: usize) -> Self {
66        Self {
67            bytes: BytesMut::with_capacity(capacity),
68        }
69    }
70
71    /// Returns the length of this String, in bytes.
72    ///
73    /// # Examples
74    ///
75    /// ```
76    /// use bytes_str::BytesString;
77    ///
78    /// let s = BytesString::from("hello");
79    ///
80    /// assert_eq!(s.len(), 5);
81    /// ```
82    pub fn len(&self) -> usize {
83        self.bytes.len()
84    }
85
86    /// Returns the capacity of this String, in bytes.
87    ///
88    /// # Examples
89    ///
90    /// ```
91    /// use bytes_str::BytesString;
92    ///
93    /// let s = BytesString::from("hello");
94    ///
95    /// assert!(s.capacity() >= 5);
96    /// ```
97    pub fn capacity(&self) -> usize {
98        self.bytes.capacity()
99    }
100
101    /// Reserves the minimum capacity for exactly `additional` more bytes to be
102    /// stored without reallocating.
103    ///
104    /// # Panics
105    ///
106    /// Panics if the new capacity overflows usize.
107    ///
108    /// # Examples
109    ///
110    /// ```
111    /// use bytes_str::BytesString;
112    ///
113    /// let mut s = BytesString::from("hello");
114    ///
115    /// s.reserve(10);
116    ///
117    /// assert!(s.capacity() >= 15);
118    /// ```
119    pub fn reserve(&mut self, additional: usize) {
120        self.bytes.reserve(additional);
121    }
122
123    /// Splits the string into two at the given index.
124    ///
125    /// Returns a newly allocated String. `self` contains bytes at indices
126    /// greater than `at`, and the returned string contains bytes at indices
127    /// less than `at`.
128    ///
129    /// # Examples
130    ///
131    /// ```
132    /// use bytes_str::BytesString;
133    ///
134    /// let mut s = BytesString::from("hello");
135    ///
136    /// let other = s.split_off(2);
137    ///
138    /// assert_eq!(s, "he");
139    /// assert_eq!(other, "llo");
140    /// ```
141    pub fn split_off(&mut self, at: usize) -> Self {
142        Self {
143            bytes: self.bytes.split_off(at),
144        }
145    }
146
147    /// Returns a byte slice of this String’s contents.
148    ///
149    /// # Examples
150    ///
151    /// ```
152    /// use bytes_str::BytesString;
153    ///
154    /// let s = BytesString::from("hello");
155    ///
156    /// assert_eq!(s.as_bytes(), b"hello");
157    /// ```
158    pub fn as_bytes(&self) -> &[u8] {
159        self.bytes.as_ref()
160    }
161
162    /// Returns true if the BytesString has a length of 0.
163    ///
164    /// # Examples
165    ///
166    /// ```
167    /// use bytes_str::BytesString;
168    ///
169    /// let s = BytesString::new();
170    ///
171    /// assert!(s.is_empty());
172    /// ```
173    pub fn is_empty(&self) -> bool {
174        self.bytes.is_empty()
175    }
176
177    /// Truncates the BytesString to the specified length.
178    ///
179    /// If new_len is greater than or equal to the string’s current length, this
180    /// has no effect.
181    ///
182    /// Note that this method has no effect on the allocated capacity of the
183    /// string
184    ///
185    /// # Arguments
186    ///
187    /// * `new_len` - The new length of the BytesString
188    ///
189    /// # Panics
190    ///
191    /// Panics if new_len does not lie on a char boundary.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use bytes_str::BytesString;
197    ///
198    /// let mut s = BytesString::from("hello");
199    ///
200    /// s.truncate(3);
201    ///
202    /// assert_eq!(s, "hel");
203    /// ```
204    ///
205    ///
206    /// Shortens this String to the specified length.
207    pub fn truncate(&mut self, new_len: usize) {
208        if new_len <= self.len() {
209            assert!(self.is_char_boundary(new_len));
210            self.bytes.truncate(new_len);
211        }
212    }
213
214    /// Clears the BytesString, removing all bytes.
215    ///
216    /// # Examples
217    ///
218    /// ```
219    /// use bytes_str::BytesString;
220    ///
221    /// let mut s = BytesString::from("hello");
222    ///
223    /// s.clear();
224    ///
225    /// assert!(s.is_empty());
226    /// ```
227    pub fn clear(&mut self) {
228        self.bytes.clear();
229    }
230
231    /// Appends a character to the end of this BytesString.
232    ///
233    /// # Examples
234    ///
235    /// ```
236    /// use bytes_str::BytesString;
237    ///
238    /// let mut s = BytesString::from("hello");
239    ///
240    /// s.push(' ');
241    ///
242    /// assert_eq!(s, "hello ");
243    /// ```
244    pub fn push(&mut self, ch: char) {
245        let mut buf = [0; 4];
246        let bytes = ch.encode_utf8(&mut buf);
247        self.bytes.extend_from_slice(bytes.as_bytes());
248    }
249
250    /// Appends a string slice to the end of this BytesString.
251    ///
252    /// # Examples
253    ///
254    /// ```
255    /// use bytes_str::BytesString;
256    ///
257    /// let mut s = BytesString::from("hello");
258    ///
259    /// s.push_str(" world");
260    ///
261    /// assert_eq!(s, "hello world");
262    /// ```
263    pub fn push_str(&mut self, s: &str) {
264        self.bytes.extend_from_slice(s.as_bytes());
265    }
266
267    /// Returns a string slice containing the entire BytesString.
268    ///
269    /// # Examples
270    ///
271    /// ```
272    /// use bytes_str::BytesString;
273    ///
274    /// let s = BytesString::from("hello");
275    ///
276    /// assert_eq!(s.as_str(), "hello");
277    /// ```
278    pub fn as_str(&self) -> &str {
279        unsafe { std::str::from_utf8_unchecked(&self.bytes) }
280    }
281
282    /// Returns a mutable string slice containing the entire BytesString.
283    ///
284    /// # Examples
285    ///
286    /// ```
287    /// use bytes_str::BytesString;
288    ///
289    /// let mut s = BytesString::from("hello");
290    ///
291    /// s.as_mut_str().make_ascii_uppercase();
292    ///
293    /// assert_eq!(s, "HELLO");
294    /// ```
295    pub fn as_mut_str(&mut self) -> &mut str {
296        unsafe { std::str::from_utf8_unchecked_mut(&mut self.bytes) }
297    }
298
299    /// Converts the BytesString into a [BytesMut].
300    ///
301    /// # Examples
302    ///
303    /// ```
304    /// use bytes_str::BytesString;
305    /// use bytes::BytesMut;
306    ///
307    /// let s = BytesString::from("hello");
308    ///
309    /// let bytes = s.into_bytes();
310    ///
311    /// assert_eq!(bytes, BytesMut::from(&b"hello"[..]));
312    /// ```
313    pub fn into_bytes(self) -> BytesMut {
314        self.bytes
315    }
316
317    /// Converts a [BytesMut] into a [BytesString] without checking if the bytes
318    /// are valid UTF-8.
319    ///
320    /// # Safety
321    ///
322    /// This function is unsafe because it does not check if the bytes are valid
323    /// UTF-8.
324    pub unsafe fn from_bytes_unchecked(bytes: BytesMut) -> Self {
325        Self { bytes }
326    }
327
328    /// Converts a [BytesMut] into a [BytesString] if the bytes are valid UTF-8.
329    ///
330    /// # Errors
331    ///
332    /// Returns a [Utf8Error] if the bytes are not valid UTF-8.
333    ///
334    /// # Examples
335    ///
336    /// ```
337    /// use bytes_str::BytesString;
338    /// use bytes::BytesMut;
339    ///
340    /// let s = BytesString::from_utf8(BytesMut::from(&b"hello"[..]));
341    /// ```
342    pub fn from_utf8(bytes: BytesMut) -> Result<Self, Utf8Error> {
343        std::str::from_utf8(bytes.as_ref())?;
344
345        Ok(Self { bytes })
346    }
347
348    /// Converts a slice of bytes into a [BytesString] if the bytes are valid
349    /// UTF-8.
350    ///
351    /// # Errors
352    ///
353    /// Returns a [Utf8Error] if the bytes are not valid UTF-8.
354    ///
355    /// # Examples
356    ///
357    /// ```
358    /// use bytes_str::BytesString;
359    ///
360    /// let s = BytesString::from_utf8_slice(b"hello");
361    /// ```
362    pub fn from_utf8_slice(bytes: &[u8]) -> Result<Self, Utf8Error> {
363        std::str::from_utf8(bytes)?;
364
365        Ok(Self {
366            bytes: BytesMut::from(bytes),
367        })
368    }
369}
370
371impl Deref for BytesString {
372    type Target = str;
373
374    fn deref(&self) -> &Self::Target {
375        self.as_str()
376    }
377}
378
379impl DerefMut for BytesString {
380    fn deref_mut(&mut self) -> &mut Self::Target {
381        self.as_mut_str()
382    }
383}
384
385impl AsRef<str> for BytesString {
386    fn as_ref(&self) -> &str {
387        self.as_str()
388    }
389}
390
391impl Borrow<str> for BytesString {
392    fn borrow(&self) -> &str {
393        self.as_str()
394    }
395}
396
397impl From<String> for BytesString {
398    fn from(s: String) -> Self {
399        Self {
400            bytes: Bytes::from(s.into_bytes()).into(),
401        }
402    }
403}
404
405impl From<&str> for BytesString {
406    fn from(s: &str) -> Self {
407        Self {
408            bytes: BytesMut::from(s),
409        }
410    }
411}
412
413impl From<BytesString> for BytesMut {
414    fn from(s: BytesString) -> Self {
415        s.bytes
416    }
417}
418
419impl From<BytesString> for Bytes {
420    fn from(s: BytesString) -> Self {
421        s.bytes.into()
422    }
423}
424
425impl From<char> for BytesString {
426    fn from(ch: char) -> Self {
427        let mut bytes = BytesString::with_capacity(ch.len_utf8());
428        bytes.push(ch);
429        bytes
430    }
431}
432
433impl PartialEq<str> for BytesString {
434    fn eq(&self, other: &str) -> bool {
435        self.as_str() == other
436    }
437}
438
439impl PartialEq<&'_ str> for BytesString {
440    fn eq(&self, other: &&str) -> bool {
441        self.as_str() == *other
442    }
443}
444
445impl PartialEq<Cow<'_, str>> for BytesString {
446    fn eq(&self, other: &Cow<'_, str>) -> bool {
447        self.as_str() == *other
448    }
449}
450
451impl PartialEq<BytesString> for str {
452    fn eq(&self, other: &BytesString) -> bool {
453        self == other.as_str()
454    }
455}
456
457impl PartialEq<BytesString> for &'_ str {
458    fn eq(&self, other: &BytesString) -> bool {
459        *self == other.as_str()
460    }
461}
462
463impl PartialEq<BytesString> for Bytes {
464    fn eq(&self, other: &BytesString) -> bool {
465        self == other.as_bytes()
466    }
467}
468
469impl PartialEq<String> for BytesString {
470    fn eq(&self, other: &String) -> bool {
471        self.as_str() == other
472    }
473}
474
475impl PartialEq<BytesString> for String {
476    fn eq(&self, other: &BytesString) -> bool {
477        self == other.as_str()
478    }
479}
480
481impl Add<&str> for BytesString {
482    type Output = Self;
483
484    fn add(mut self, other: &str) -> Self::Output {
485        self += other;
486        self
487    }
488}
489
490impl AddAssign<&str> for BytesString {
491    fn add_assign(&mut self, other: &str) {
492        self.push_str(other);
493    }
494}
495
496impl Add<BytesString> for BytesString {
497    type Output = Self;
498
499    fn add(mut self, other: BytesString) -> Self::Output {
500        self += other;
501        self
502    }
503}
504
505impl AddAssign<BytesString> for BytesString {
506    fn add_assign(&mut self, other: BytesString) {
507        self.bytes.extend(other.bytes);
508    }
509}
510
511impl AsMut<str> for BytesString {
512    fn as_mut(&mut self) -> &mut str {
513        self.as_mut_str()
514    }
515}
516
517impl AsRef<[u8]> for BytesString {
518    fn as_ref(&self) -> &[u8] {
519        self.as_bytes()
520    }
521}
522
523impl AsRef<OsStr> for BytesString {
524    fn as_ref(&self) -> &OsStr {
525        OsStr::new(self.as_str())
526    }
527}
528
529impl AsRef<Path> for BytesString {
530    fn as_ref(&self) -> &Path {
531        Path::new(self.as_str())
532    }
533}
534
535impl BorrowMut<str> for BytesString {
536    fn borrow_mut(&mut self) -> &mut str {
537        self.as_mut_str()
538    }
539}
540
541impl Debug for BytesString {
542    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543        Debug::fmt(self.as_str(), f)
544    }
545}
546
547impl Display for BytesString {
548    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549        Display::fmt(self.as_str(), f)
550    }
551}
552
553impl PartialOrd for BytesString {
554    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
555        Some(self.cmp(other))
556    }
557}
558
559impl Ord for BytesString {
560    fn cmp(&self, other: &Self) -> Ordering {
561        self.as_str().cmp(other.as_str())
562    }
563}
564
565impl<'a> Extend<&'a char> for BytesString {
566    fn extend<T: IntoIterator<Item = &'a char>>(&mut self, iter: T) {
567        self.extend(iter.into_iter().copied());
568    }
569}
570impl Extend<char> for BytesString {
571    fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
572        let mut buf = [0; 4];
573        for ch in iter {
574            let bytes = ch.encode_utf8(&mut buf);
575            self.bytes.extend_from_slice(bytes.as_bytes());
576        }
577    }
578}
579
580impl<'a> Extend<&'a str> for BytesString {
581    fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
582        for s in iter {
583            self.push_str(s);
584        }
585    }
586}
587
588impl Extend<Box<str>> for BytesString {
589    fn extend<T: IntoIterator<Item = Box<str>>>(&mut self, iter: T) {
590        for s in iter {
591            self.push_str(&s);
592        }
593    }
594}
595
596impl<'a> Extend<Cow<'a, str>> for BytesString {
597    fn extend<T: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: T) {
598        for s in iter {
599            self.push_str(&s);
600        }
601    }
602}
603
604impl Extend<String> for BytesString {
605    fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
606        for s in iter {
607            self.push_str(&s);
608        }
609    }
610}
611
612impl<'a> Extend<&'a String> for BytesString {
613    fn extend<T: IntoIterator<Item = &'a String>>(&mut self, iter: T) {
614        for s in iter {
615            self.push_str(s);
616        }
617    }
618}
619
620impl Extend<BytesString> for BytesString {
621    fn extend<T: IntoIterator<Item = BytesString>>(&mut self, iter: T) {
622        for s in iter {
623            self.bytes.extend(s.bytes);
624        }
625    }
626}
627
628impl FromIterator<char> for BytesString {
629    fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
630        let mut bytes = BytesString::new();
631        bytes.extend(iter);
632        bytes
633    }
634}
635
636impl<'a> FromIterator<&'a str> for BytesString {
637    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
638        let mut bytes = BytesString::new();
639        bytes.extend(iter);
640        bytes
641    }
642}
643
644impl FromIterator<Box<str>> for BytesString {
645    fn from_iter<T: IntoIterator<Item = Box<str>>>(iter: T) -> Self {
646        let mut bytes = BytesString::new();
647        bytes.extend(iter);
648        bytes
649    }
650}
651
652impl<'a> FromIterator<Cow<'a, str>> for BytesString {
653    fn from_iter<T: IntoIterator<Item = Cow<'a, str>>>(iter: T) -> Self {
654        let mut bytes = BytesString::new();
655        bytes.extend(iter);
656        bytes
657    }
658}
659
660impl FromIterator<String> for BytesString {
661    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
662        let mut bytes = BytesString::new();
663        bytes.extend(iter);
664        bytes
665    }
666}
667
668impl FromIterator<BytesString> for BytesString {
669    fn from_iter<T: IntoIterator<Item = BytesString>>(iter: T) -> Self {
670        let mut bytes = BytesString::new();
671        bytes.extend(iter);
672        bytes
673    }
674}
675
676impl FromStr for BytesString {
677    type Err = Infallible;
678
679    fn from_str(s: &str) -> Result<Self, Self::Err> {
680        Ok(Self {
681            bytes: BytesMut::from(s),
682        })
683    }
684}
685
686impl<I> Index<I> for BytesString
687where
688    I: SliceIndex<str>,
689{
690    type Output = I::Output;
691
692    fn index(&self, index: I) -> &Self::Output {
693        self.as_str().index(index)
694    }
695}
696
697impl<I> IndexMut<I> for BytesString
698where
699    I: SliceIndex<str>,
700{
701    fn index_mut(&mut self, index: I) -> &mut Self::Output {
702        self.as_mut_str().index_mut(index)
703    }
704}
705
706impl ToSocketAddrs for BytesString {
707    type Iter = std::vec::IntoIter<SocketAddr>;
708
709    fn to_socket_addrs(&self) -> Result<Self::Iter, std::io::Error> {
710        self.as_str().to_socket_addrs()
711    }
712}
713
714/// This produces the same hash as [str]
715impl Hash for BytesString {
716    fn hash<H: Hasher>(&self, state: &mut H) {
717        self.as_str().hash(state);
718    }
719}
720
721#[cfg(feature = "serde")]
722mod serde_impl {
723    use serde::{Deserialize, Deserializer, Serialize, Serializer};
724
725    use super::*;
726
727    impl<'de> Deserialize<'de> for BytesString {
728        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
729        where
730            D: Deserializer<'de>,
731        {
732            let s = String::deserialize(deserializer)?;
733            Ok(Self::from(s))
734        }
735    }
736
737    impl Serialize for BytesString {
738        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
739        where
740            S: Serializer,
741        {
742            serializer.serialize_str(self.as_str())
743        }
744    }
745}