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}
570
571impl Extend<char> for BytesString {
572    fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
573        let mut buf = [0; 4];
574        for ch in iter {
575            let bytes = ch.encode_utf8(&mut buf);
576            self.bytes.extend_from_slice(bytes.as_bytes());
577        }
578    }
579}
580
581impl<'a> Extend<&'a str> for BytesString {
582    fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
583        for s in iter {
584            self.push_str(s);
585        }
586    }
587}
588
589impl<'a, 'b> Extend<&'a &'b str> for BytesString {
590    fn extend<T: IntoIterator<Item = &'a &'b str>>(&mut self, iter: T) {
591        for s in iter {
592            self.push_str(s);
593        }
594    }
595}
596
597impl Extend<Box<str>> for BytesString {
598    fn extend<T: IntoIterator<Item = Box<str>>>(&mut self, iter: T) {
599        for s in iter {
600            self.push_str(&s);
601        }
602    }
603}
604
605impl<'a> Extend<Cow<'a, str>> for BytesString {
606    fn extend<T: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: T) {
607        for s in iter {
608            self.push_str(&s);
609        }
610    }
611}
612
613impl Extend<String> for BytesString {
614    fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
615        for s in iter {
616            self.push_str(&s);
617        }
618    }
619}
620
621impl<'a> Extend<&'a String> for BytesString {
622    fn extend<T: IntoIterator<Item = &'a String>>(&mut self, iter: T) {
623        for s in iter {
624            self.push_str(s);
625        }
626    }
627}
628
629impl Extend<BytesString> for BytesString {
630    fn extend<T: IntoIterator<Item = BytesString>>(&mut self, iter: T) {
631        for s in iter {
632            self.bytes.extend(s.bytes);
633        }
634    }
635}
636
637impl FromIterator<char> for BytesString {
638    fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
639        let mut bytes = BytesString::new();
640        bytes.extend(iter);
641        bytes
642    }
643}
644
645impl<'a> FromIterator<&'a str> for BytesString {
646    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
647        let mut bytes = BytesString::new();
648        bytes.extend(iter);
649        bytes
650    }
651}
652
653impl FromIterator<Box<str>> for BytesString {
654    fn from_iter<T: IntoIterator<Item = Box<str>>>(iter: T) -> Self {
655        let mut bytes = BytesString::new();
656        bytes.extend(iter);
657        bytes
658    }
659}
660
661impl<'a> FromIterator<Cow<'a, str>> for BytesString {
662    fn from_iter<T: IntoIterator<Item = Cow<'a, str>>>(iter: T) -> Self {
663        let mut bytes = BytesString::new();
664        bytes.extend(iter);
665        bytes
666    }
667}
668
669impl FromIterator<String> for BytesString {
670    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
671        let mut bytes = BytesString::new();
672        bytes.extend(iter);
673        bytes
674    }
675}
676
677impl FromIterator<BytesString> for BytesString {
678    fn from_iter<T: IntoIterator<Item = BytesString>>(iter: T) -> Self {
679        let mut bytes = BytesString::new();
680        bytes.extend(iter);
681        bytes
682    }
683}
684
685impl FromStr for BytesString {
686    type Err = Infallible;
687
688    fn from_str(s: &str) -> Result<Self, Self::Err> {
689        Ok(Self {
690            bytes: BytesMut::from(s),
691        })
692    }
693}
694
695impl<I> Index<I> for BytesString
696where
697    I: SliceIndex<str>,
698{
699    type Output = I::Output;
700
701    fn index(&self, index: I) -> &Self::Output {
702        self.as_str().index(index)
703    }
704}
705
706impl<I> IndexMut<I> for BytesString
707where
708    I: SliceIndex<str>,
709{
710    fn index_mut(&mut self, index: I) -> &mut Self::Output {
711        self.as_mut_str().index_mut(index)
712    }
713}
714
715impl ToSocketAddrs for BytesString {
716    type Iter = std::vec::IntoIter<SocketAddr>;
717
718    fn to_socket_addrs(&self) -> Result<Self::Iter, std::io::Error> {
719        self.as_str().to_socket_addrs()
720    }
721}
722
723/// This produces the same hash as [str]
724impl Hash for BytesString {
725    fn hash<H: Hasher>(&self, state: &mut H) {
726        self.as_str().hash(state);
727    }
728}
729
730#[cfg(feature = "serde")]
731mod serde_impl {
732    use serde::{Deserialize, Deserializer, Serialize, Serializer};
733
734    use super::*;
735
736    impl<'de> Deserialize<'de> for BytesString {
737        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
738        where
739            D: Deserializer<'de>,
740        {
741            let s = String::deserialize(deserializer)?;
742            Ok(Self::from(s))
743        }
744    }
745
746    impl Serialize for BytesString {
747        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
748        where
749            S: Serializer,
750        {
751            serializer.serialize_str(self.as_str())
752        }
753    }
754}
755
756#[cfg(test)]
757mod tests {
758    use std::{
759        collections::{hash_map::DefaultHasher, HashMap},
760        hash::{Hash, Hasher},
761    };
762
763    use super::*;
764
765    #[test]
766    fn test_new() {
767        let s = BytesString::new();
768        assert!(s.is_empty());
769        assert_eq!(s.len(), 0);
770        assert_eq!(s.as_str(), "");
771    }
772
773    #[test]
774    fn test_with_capacity() {
775        let s = BytesString::with_capacity(10);
776        assert!(s.capacity() >= 10);
777        assert!(s.is_empty());
778        assert_eq!(s.len(), 0);
779    }
780
781    #[test]
782    fn test_from_str() {
783        let s = BytesString::from("hello");
784        assert_eq!(s.as_str(), "hello");
785        assert_eq!(s.len(), 5);
786        assert!(!s.is_empty());
787    }
788
789    #[test]
790    fn test_from_string() {
791        let original = String::from("hello world");
792        let s = BytesString::from(original);
793        assert_eq!(s.as_str(), "hello world");
794        assert_eq!(s.len(), 11);
795    }
796
797    #[test]
798    fn test_from_char() {
799        let s = BytesString::from('H');
800        assert_eq!(s.as_str(), "H");
801        assert_eq!(s.len(), 1);
802
803        // Test unicode character
804        let s = BytesString::from('한');
805        assert_eq!(s.as_str(), "한");
806        assert_eq!(s.len(), 3); // UTF-8 encoding
807    }
808
809    #[test]
810    fn test_push() {
811        let mut s = BytesString::from("hello");
812        s.push(' ');
813        s.push('w');
814        assert_eq!(s.as_str(), "hello w");
815
816        // Test unicode
817        s.push('한');
818        assert_eq!(s.as_str(), "hello w한");
819    }
820
821    #[test]
822    fn test_push_str() {
823        let mut s = BytesString::from("hello");
824        s.push_str(" world");
825        assert_eq!(s.as_str(), "hello world");
826
827        s.push_str("!");
828        assert_eq!(s.as_str(), "hello world!");
829
830        // Test unicode
831        s.push_str(" 한국어");
832        assert_eq!(s.as_str(), "hello world! 한국어");
833    }
834
835    #[test]
836    fn test_clear() {
837        let mut s = BytesString::from("hello");
838        assert!(!s.is_empty());
839        s.clear();
840        assert!(s.is_empty());
841        assert_eq!(s.len(), 0);
842        assert_eq!(s.as_str(), "");
843    }
844
845    #[test]
846    fn test_truncate() {
847        let mut s = BytesString::from("hello world");
848        s.truncate(5);
849        assert_eq!(s.as_str(), "hello");
850
851        // Test truncating to larger than current length
852        s.truncate(20);
853        assert_eq!(s.as_str(), "hello");
854
855        // Test unicode boundaries
856        let mut s = BytesString::from("한국어");
857        s.truncate(6); // Should truncate to "한국"
858        assert_eq!(s.as_str(), "한국");
859    }
860
861    #[test]
862    #[should_panic]
863    fn test_truncate_panic_on_char_boundary() {
864        let mut s = BytesString::from("한국어");
865        s.truncate(1); // Should panic as it's not on a char boundary
866    }
867
868    #[test]
869    fn test_split_off() {
870        let mut s = BytesString::from("hello world");
871        let other = s.split_off(6);
872        assert_eq!(s.as_str(), "hello ");
873        assert_eq!(other.as_str(), "world");
874
875        // Test at beginning
876        let mut s = BytesString::from("hello");
877        let other = s.split_off(0);
878        assert_eq!(s.as_str(), "");
879        assert_eq!(other.as_str(), "hello");
880
881        // Test at end
882        let mut s = BytesString::from("hello");
883        let other = s.split_off(5);
884        assert_eq!(s.as_str(), "hello");
885        assert_eq!(other.as_str(), "");
886    }
887
888    #[test]
889    fn test_as_bytes() {
890        let s = BytesString::from("hello");
891        assert_eq!(s.as_bytes(), b"hello");
892
893        let s = BytesString::from("한국어");
894        assert_eq!(s.as_bytes(), "한국어".as_bytes());
895    }
896
897    #[test]
898    fn test_as_mut_str() {
899        let mut s = BytesString::from("hello");
900        s.as_mut_str().make_ascii_uppercase();
901        assert_eq!(s.as_str(), "HELLO");
902    }
903
904    #[test]
905    fn test_into_bytes() {
906        let s = BytesString::from("hello");
907        let bytes = s.into_bytes();
908        assert_eq!(bytes.as_ref(), b"hello");
909    }
910
911    #[test]
912    fn test_from_utf8() {
913        let bytes = BytesMut::from(&b"hello"[..]);
914        let s = BytesString::from_utf8(bytes).unwrap();
915        assert_eq!(s.as_str(), "hello");
916
917        // Test invalid UTF-8
918        let invalid_bytes = BytesMut::from(&[0xff, 0xfe][..]);
919        assert!(BytesString::from_utf8(invalid_bytes).is_err());
920    }
921
922    #[test]
923    fn test_from_utf8_slice() {
924        let s = BytesString::from_utf8_slice(b"hello").unwrap();
925        assert_eq!(s.as_str(), "hello");
926
927        // Test invalid UTF-8
928        assert!(BytesString::from_utf8_slice(&[0xff, 0xfe]).is_err());
929    }
930
931    #[test]
932    fn test_from_bytes_unchecked() {
933        let bytes = BytesMut::from(&b"hello"[..]);
934        let s = unsafe { BytesString::from_bytes_unchecked(bytes) };
935        assert_eq!(s.as_str(), "hello");
936    }
937
938    #[test]
939    fn test_reserve() {
940        let mut s = BytesString::from("hello");
941        let initial_capacity = s.capacity();
942        s.reserve(100);
943        assert!(s.capacity() >= initial_capacity + 100);
944        assert_eq!(s.as_str(), "hello"); // Content unchanged
945    }
946
947    #[test]
948    fn test_deref() {
949        let s = BytesString::from("hello world");
950        assert_eq!(s.len(), 11);
951        assert!(s.contains("world"));
952        assert!(s.starts_with("hello"));
953        assert!(s.ends_with("world"));
954    }
955
956    #[test]
957    fn test_partial_eq() {
958        let s = BytesString::from("hello");
959
960        // Test with &str
961        assert_eq!(s, "hello");
962        assert_ne!(s, "world");
963
964        // Test with String
965        assert_eq!(s, String::from("hello"));
966        assert_ne!(s, String::from("world"));
967
968        // Test with Cow
969        assert_eq!(s, Cow::Borrowed("hello"));
970        assert_eq!(s, Cow::Owned(String::from("hello")));
971
972        // Test with Bytes
973        assert_eq!(Bytes::from("hello"), s);
974        assert_ne!(Bytes::from("world"), s);
975
976        // Test symmetry
977        assert_eq!("hello", s);
978        assert_eq!(String::from("hello"), s);
979    }
980
981    #[test]
982    fn test_ordering() {
983        let s1 = BytesString::from("apple");
984        let s2 = BytesString::from("banana");
985        let s3 = BytesString::from("apple");
986
987        assert!(s1 < s2);
988        assert!(s2 > s1);
989        assert_eq!(s1, s3);
990        assert!(s1 <= s3);
991        assert!(s1 >= s3);
992    }
993
994    #[test]
995    fn test_hash() {
996        let s1 = BytesString::from("hello");
997        let s2 = BytesString::from("hello");
998        let s3 = BytesString::from("world");
999
1000        let mut hasher1 = DefaultHasher::new();
1001        let mut hasher2 = DefaultHasher::new();
1002        let mut hasher3 = DefaultHasher::new();
1003
1004        s1.hash(&mut hasher1);
1005        s2.hash(&mut hasher2);
1006        s3.hash(&mut hasher3);
1007
1008        assert_eq!(hasher1.finish(), hasher2.finish());
1009        assert_ne!(hasher1.finish(), hasher3.finish());
1010
1011        // Test hash consistency with str
1012        let mut str_hasher = DefaultHasher::new();
1013        "hello".hash(&mut str_hasher);
1014        assert_eq!(hasher1.finish(), str_hasher.finish());
1015    }
1016
1017    #[test]
1018    fn test_add() {
1019        let s1 = BytesString::from("hello");
1020        let s2 = s1 + " world";
1021        assert_eq!(s2.as_str(), "hello world");
1022
1023        let s3 = BytesString::from("foo");
1024        let s4 = BytesString::from("bar");
1025        let s5 = s3 + s4;
1026        assert_eq!(s5.as_str(), "foobar");
1027    }
1028
1029    #[test]
1030    fn test_add_assign() {
1031        let mut s = BytesString::from("hello");
1032        s += " world";
1033        assert_eq!(s.as_str(), "hello world");
1034
1035        let mut s1 = BytesString::from("foo");
1036        let s2 = BytesString::from("bar");
1037        s1 += s2;
1038        assert_eq!(s1.as_str(), "foobar");
1039    }
1040
1041    #[test]
1042    fn test_extend_char() {
1043        let mut s = BytesString::from("hello");
1044        s.extend(['!', ' ', '🎉'].iter());
1045        assert_eq!(s.as_str(), "hello! 🎉");
1046
1047        let mut s = BytesString::new();
1048        s.extend(['a', 'b', 'c']);
1049        assert_eq!(s.as_str(), "abc");
1050    }
1051
1052    #[test]
1053    fn test_extend_str() {
1054        let mut s = BytesString::from("hello");
1055        s.extend([" ", "world", "!"].iter());
1056        assert_eq!(s.as_str(), "hello world!");
1057
1058        let strings = vec![String::from("foo"), String::from("bar")];
1059        let mut s = BytesString::new();
1060        s.extend(&strings);
1061        assert_eq!(s.as_str(), "foobar");
1062    }
1063
1064    #[test]
1065    fn test_extend_bytes_string() {
1066        let mut s = BytesString::from("hello");
1067        let parts = vec![BytesString::from(" "), BytesString::from("world")];
1068        s.extend(parts);
1069        assert_eq!(s.as_str(), "hello world");
1070    }
1071
1072    #[test]
1073    fn test_from_iterator() {
1074        let s: BytesString = ['h', 'e', 'l', 'l', 'o'].into_iter().collect();
1075        assert_eq!(s.as_str(), "hello");
1076
1077        let s: BytesString = ["hello", " ", "world"].into_iter().collect();
1078        assert_eq!(s.as_str(), "hello world");
1079
1080        let strings = vec![String::from("foo"), String::from("bar")];
1081        let s: BytesString = strings.into_iter().collect();
1082        assert_eq!(s.as_str(), "foobar");
1083    }
1084
1085    #[test]
1086    fn test_from_str_trait() {
1087        let s: BytesString = "hello world".parse().unwrap();
1088        assert_eq!(s.as_str(), "hello world");
1089    }
1090
1091    #[test]
1092    fn test_index() {
1093        let s = BytesString::from("hello world");
1094        assert_eq!(&s[0..5], "hello");
1095        assert_eq!(&s[6..], "world");
1096        assert_eq!(&s[..5], "hello");
1097        assert_eq!(&s[6..11], "world");
1098    }
1099
1100    #[test]
1101    fn test_index_mut() {
1102        let mut s = BytesString::from("hello world");
1103        s[0..5].make_ascii_uppercase();
1104        assert_eq!(s.as_str(), "HELLO world");
1105    }
1106
1107    #[test]
1108    fn test_as_ref_implementations() {
1109        let s = BytesString::from("hello/world");
1110
1111        // AsRef<str>
1112        let str_ref: &str = s.as_ref();
1113        assert_eq!(str_ref, "hello/world");
1114
1115        // AsRef<[u8]>
1116        let bytes_ref: &[u8] = s.as_ref();
1117        assert_eq!(bytes_ref, b"hello/world");
1118
1119        // AsRef<OsStr>
1120        let os_str_ref: &OsStr = s.as_ref();
1121        assert_eq!(os_str_ref, OsStr::new("hello/world"));
1122
1123        // AsRef<Path>
1124        let path_ref: &Path = s.as_ref();
1125        assert_eq!(path_ref, Path::new("hello/world"));
1126    }
1127
1128    #[test]
1129    fn test_borrow() {
1130        let s = BytesString::from("hello");
1131        let borrowed: &str = s.borrow();
1132        assert_eq!(borrowed, "hello");
1133
1134        let mut s = BytesString::from("hello");
1135        let borrowed_mut: &mut str = s.borrow_mut();
1136        borrowed_mut.make_ascii_uppercase();
1137        assert_eq!(s.as_str(), "HELLO");
1138    }
1139
1140    #[test]
1141    fn test_debug() {
1142        let s = BytesString::from("hello");
1143        assert_eq!(format!("{:?}", s), "\"hello\"");
1144    }
1145
1146    #[test]
1147    fn test_display() {
1148        let s = BytesString::from("hello world");
1149        assert_eq!(format!("{}", s), "hello world");
1150    }
1151
1152    #[test]
1153    fn test_conversions() {
1154        let s = BytesString::from("hello");
1155
1156        // Into BytesMut
1157        let bytes_mut: BytesMut = s.clone().into();
1158        assert_eq!(bytes_mut.as_ref(), b"hello");
1159
1160        // Into Bytes
1161        let bytes: Bytes = s.into();
1162        assert_eq!(bytes.as_ref(), b"hello");
1163    }
1164
1165    #[test]
1166    fn test_to_socket_addrs() {
1167        let s = BytesString::from("127.0.0.1:8080");
1168        let addrs: Vec<_> = s.to_socket_addrs().unwrap().collect();
1169        assert!(!addrs.is_empty());
1170
1171        let s = BytesString::from("localhost:8080");
1172        let result = s.to_socket_addrs();
1173        // This might fail depending on system configuration, so we just check it
1174        // compiles
1175        let _ = result;
1176    }
1177
1178    #[test]
1179    fn test_unicode_handling() {
1180        let s = BytesString::from("Hello 🌍 한국어 🎉");
1181        assert_eq!(s.as_str(), "Hello 🌍 한국어 🎉");
1182        assert!(s.len() > 13); // More than ASCII length due to UTF-8 encoding
1183
1184        let mut s = BytesString::new();
1185        s.push('🌍');
1186        s.push_str(" 한국어");
1187        assert_eq!(s.as_str(), "🌍 한국어");
1188    }
1189
1190    #[test]
1191    fn test_empty_operations() {
1192        let mut s = BytesString::new();
1193        assert!(s.is_empty());
1194
1195        s.push_str("");
1196        assert!(s.is_empty());
1197
1198        s.clear();
1199        assert!(s.is_empty());
1200
1201        let other = s.split_off(0);
1202        assert!(s.is_empty());
1203        assert!(other.is_empty());
1204    }
1205
1206    #[test]
1207    fn test_large_string() {
1208        let large_str = "a".repeat(10000);
1209        let s = BytesString::from(large_str.as_str());
1210        assert_eq!(s.len(), 10000);
1211        assert_eq!(s.as_str(), large_str);
1212
1213        let mut s = BytesString::with_capacity(10000);
1214        for _ in 0..10000 {
1215            s.push('a');
1216        }
1217        assert_eq!(s.len(), 10000);
1218        assert_eq!(s.as_str(), large_str);
1219    }
1220
1221    #[test]
1222    fn test_clone() {
1223        let s1 = BytesString::from("hello world");
1224        let s2 = s1.clone();
1225        assert_eq!(s1, s2);
1226        assert_eq!(s1.as_str(), s2.as_str());
1227    }
1228
1229    #[test]
1230    fn test_default() {
1231        let s: BytesString = Default::default();
1232        assert!(s.is_empty());
1233        assert_eq!(s.as_str(), "");
1234    }
1235
1236    #[test]
1237    fn test_hash_map_usage() {
1238        let mut map = HashMap::new();
1239        let key = BytesString::from("key");
1240        map.insert(key, "value");
1241
1242        let lookup_key = BytesString::from("key");
1243        assert_eq!(map.get(&lookup_key), Some(&"value"));
1244
1245        // Test that string can be used to lookup BytesString key
1246        assert_eq!(map.get("key"), Some(&"value"));
1247    }
1248}