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