bytes-str 0.2.1

A string type that is backed by bytes crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
use std::{
    borrow::{Borrow, BorrowMut, Cow},
    cmp::Ordering,
    convert::Infallible,
    ffi::OsStr,
    fmt::{self, Debug, Display},
    hash::{Hash, Hasher},
    net::{SocketAddr, ToSocketAddrs},
    ops::{Add, AddAssign, Deref, DerefMut, Index, IndexMut},
    path::Path,
    slice::SliceIndex,
    str::{FromStr, Utf8Error},
};

use bytes::{Bytes, BytesMut};

/// [String] but backed by a [BytesMut]
///
/// # Features
///
/// ## `serde`
///
/// If the `serde` feature is enabled, the [BytesString] type will be
/// [serde::Serialize] and [serde::Deserialize].
///
/// The [BytesString] type will be serialized just like a [String] type.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct BytesString {
    pub(crate) bytes: BytesMut,
}

impl BytesString {
    /// Returns a new, empty BytesString.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::new();
    ///
    /// assert!(s.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            bytes: BytesMut::new(),
        }
    }

    /// Returns a new, empty BytesString with the specified capacity.
    ///
    /// The capacity is the size of the internal buffer in bytes.
    ///
    /// The actual capacity may be larger than the specified capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::with_capacity(10);
    ///
    /// assert!(s.capacity() >= 10);
    /// ```
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            bytes: BytesMut::with_capacity(capacity),
        }
    }

    /// Returns the length of this String, in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::from("hello");
    ///
    /// assert_eq!(s.len(), 5);
    /// ```
    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    /// Returns the capacity of this String, in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::from("hello");
    ///
    /// assert!(s.capacity() >= 5);
    /// ```
    pub fn capacity(&self) -> usize {
        self.bytes.capacity()
    }

    /// Reserves the minimum capacity for exactly `additional` more bytes to be
    /// stored without reallocating.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows usize.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let mut s = BytesString::from("hello");
    ///
    /// s.reserve(10);
    ///
    /// assert!(s.capacity() >= 15);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        self.bytes.reserve(additional);
    }

    /// Splits the string into two at the given index.
    ///
    /// Returns a newly allocated String. `self` contains bytes at indices
    /// greater than `at`, and the returned string contains bytes at indices
    /// less than `at`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let mut s = BytesString::from("hello");
    ///
    /// let other = s.split_off(2);
    ///
    /// assert_eq!(s, "he");
    /// assert_eq!(other, "llo");
    /// ```
    pub fn split_off(&mut self, at: usize) -> Self {
        Self {
            bytes: self.bytes.split_off(at),
        }
    }

    /// Returns a byte slice of this String’s contents.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::from("hello");
    ///
    /// assert_eq!(s.as_bytes(), b"hello");
    /// ```
    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_ref()
    }

    /// Returns true if the BytesString has a length of 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::new();
    ///
    /// assert!(s.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// Truncates the BytesString to the specified length.
    ///
    /// If new_len is greater than or equal to the string’s current length, this
    /// has no effect.
    ///
    /// Note that this method has no effect on the allocated capacity of the
    /// string
    ///
    /// # Arguments
    ///
    /// * `new_len` - The new length of the BytesString
    ///
    /// # Panics
    ///
    /// Panics if new_len does not lie on a char boundary.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let mut s = BytesString::from("hello");
    ///
    /// s.truncate(3);
    ///
    /// assert_eq!(s, "hel");
    /// ```
    ///
    ///
    /// Shortens this String to the specified length.
    pub fn truncate(&mut self, new_len: usize) {
        if new_len <= self.len() {
            assert!(self.is_char_boundary(new_len));
            self.bytes.truncate(new_len);
        }
    }

    /// Clears the BytesString, removing all bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let mut s = BytesString::from("hello");
    ///
    /// s.clear();
    ///
    /// assert!(s.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.bytes.clear();
    }

    /// Appends a character to the end of this BytesString.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let mut s = BytesString::from("hello");
    ///
    /// s.push(' ');
    ///
    /// assert_eq!(s, "hello ");
    /// ```
    pub fn push(&mut self, ch: char) {
        let mut buf = [0; 4];
        let bytes = ch.encode_utf8(&mut buf);
        self.bytes.extend_from_slice(bytes.as_bytes());
    }

    /// Appends a string slice to the end of this BytesString.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let mut s = BytesString::from("hello");
    ///
    /// s.push_str(" world");
    ///
    /// assert_eq!(s, "hello world");
    /// ```
    pub fn push_str(&mut self, s: &str) {
        self.bytes.extend_from_slice(s.as_bytes());
    }

    /// Returns a string slice containing the entire BytesString.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::from("hello");
    ///
    /// assert_eq!(s.as_str(), "hello");
    /// ```
    pub fn as_str(&self) -> &str {
        unsafe { std::str::from_utf8_unchecked(&self.bytes) }
    }

    /// Returns a mutable string slice containing the entire BytesString.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let mut s = BytesString::from("hello");
    ///
    /// s.as_mut_str().make_ascii_uppercase();
    ///
    /// assert_eq!(s, "HELLO");
    /// ```
    pub fn as_mut_str(&mut self) -> &mut str {
        unsafe { std::str::from_utf8_unchecked_mut(&mut self.bytes) }
    }

    /// Converts the BytesString into a [BytesMut].
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    /// use bytes::BytesMut;
    ///
    /// let s = BytesString::from("hello");
    ///
    /// let bytes = s.into_bytes();
    ///
    /// assert_eq!(bytes, BytesMut::from(&b"hello"[..]));
    /// ```
    pub fn into_bytes(self) -> BytesMut {
        self.bytes
    }

    /// Converts a [BytesMut] into a [BytesString] without checking if the bytes
    /// are valid UTF-8.
    ///
    /// # Safety
    ///
    /// This function is unsafe because it does not check if the bytes are valid
    /// UTF-8.
    pub unsafe fn from_bytes_unchecked(bytes: BytesMut) -> Self {
        Self { bytes }
    }

    /// Converts a [BytesMut] into a [BytesString] if the bytes are valid UTF-8.
    ///
    /// # Errors
    ///
    /// Returns a [Utf8Error] if the bytes are not valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    /// use bytes::BytesMut;
    ///
    /// let s = BytesString::from_utf8(BytesMut::from(&b"hello"[..]));
    /// ```
    pub fn from_utf8(bytes: BytesMut) -> Result<Self, Utf8Error> {
        std::str::from_utf8(bytes.as_ref())?;

        Ok(Self { bytes })
    }

    /// Converts a slice of bytes into a [BytesString] if the bytes are valid
    /// UTF-8.
    ///
    /// # Errors
    ///
    /// Returns a [Utf8Error] if the bytes are not valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes_str::BytesString;
    ///
    /// let s = BytesString::from_utf8_slice(b"hello");
    /// ```
    pub fn from_utf8_slice(bytes: &[u8]) -> Result<Self, Utf8Error> {
        std::str::from_utf8(bytes)?;

        Ok(Self {
            bytes: BytesMut::from(bytes),
        })
    }
}

impl Deref for BytesString {
    type Target = str;

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

impl DerefMut for BytesString {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_str()
    }
}

impl AsRef<str> for BytesString {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for BytesString {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl From<String> for BytesString {
    fn from(s: String) -> Self {
        Self {
            bytes: Bytes::from(s.into_bytes()).into(),
        }
    }
}

impl From<&str> for BytesString {
    fn from(s: &str) -> Self {
        Self {
            bytes: BytesMut::from(s),
        }
    }
}

impl From<BytesString> for BytesMut {
    fn from(s: BytesString) -> Self {
        s.bytes
    }
}

impl From<BytesString> for Bytes {
    fn from(s: BytesString) -> Self {
        s.bytes.into()
    }
}

impl From<char> for BytesString {
    fn from(ch: char) -> Self {
        let mut bytes = BytesString::with_capacity(ch.len_utf8());
        bytes.push(ch);
        bytes
    }
}

impl PartialEq<str> for BytesString {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&'_ str> for BytesString {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<Cow<'_, str>> for BytesString {
    fn eq(&self, other: &Cow<'_, str>) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<BytesString> for str {
    fn eq(&self, other: &BytesString) -> bool {
        self == other.as_str()
    }
}

impl PartialEq<BytesString> for &'_ str {
    fn eq(&self, other: &BytesString) -> bool {
        *self == other.as_str()
    }
}

impl PartialEq<BytesString> for Bytes {
    fn eq(&self, other: &BytesString) -> bool {
        self == other.as_bytes()
    }
}

impl PartialEq<String> for BytesString {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<BytesString> for String {
    fn eq(&self, other: &BytesString) -> bool {
        self == other.as_str()
    }
}

impl Add<&str> for BytesString {
    type Output = Self;

    fn add(mut self, other: &str) -> Self::Output {
        self += other;
        self
    }
}

impl AddAssign<&str> for BytesString {
    fn add_assign(&mut self, other: &str) {
        self.push_str(other);
    }
}

impl Add<BytesString> for BytesString {
    type Output = Self;

    fn add(mut self, other: BytesString) -> Self::Output {
        self += other;
        self
    }
}

impl AddAssign<BytesString> for BytesString {
    fn add_assign(&mut self, other: BytesString) {
        self.bytes.extend(other.bytes);
    }
}

impl AsMut<str> for BytesString {
    fn as_mut(&mut self) -> &mut str {
        self.as_mut_str()
    }
}

impl AsRef<[u8]> for BytesString {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsRef<OsStr> for BytesString {
    fn as_ref(&self) -> &OsStr {
        OsStr::new(self.as_str())
    }
}

impl AsRef<Path> for BytesString {
    fn as_ref(&self) -> &Path {
        Path::new(self.as_str())
    }
}

impl BorrowMut<str> for BytesString {
    fn borrow_mut(&mut self) -> &mut str {
        self.as_mut_str()
    }
}

impl Debug for BytesString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(self.as_str(), f)
    }
}

impl Display for BytesString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(self.as_str(), f)
    }
}

impl PartialOrd for BytesString {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for BytesString {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_str().cmp(other.as_str())
    }
}

impl<'a> Extend<&'a char> for BytesString {
    fn extend<T: IntoIterator<Item = &'a char>>(&mut self, iter: T) {
        self.extend(iter.into_iter().copied());
    }
}
impl Extend<char> for BytesString {
    fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
        let mut buf = [0; 4];
        for ch in iter {
            let bytes = ch.encode_utf8(&mut buf);
            self.bytes.extend_from_slice(bytes.as_bytes());
        }
    }
}

impl<'a> Extend<&'a str> for BytesString {
    fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
        for s in iter {
            self.push_str(s);
        }
    }
}

impl Extend<Box<str>> for BytesString {
    fn extend<T: IntoIterator<Item = Box<str>>>(&mut self, iter: T) {
        for s in iter {
            self.push_str(&s);
        }
    }
}

impl<'a> Extend<Cow<'a, str>> for BytesString {
    fn extend<T: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: T) {
        for s in iter {
            self.push_str(&s);
        }
    }
}

impl Extend<String> for BytesString {
    fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
        for s in iter {
            self.push_str(&s);
        }
    }
}

impl<'a> Extend<&'a String> for BytesString {
    fn extend<T: IntoIterator<Item = &'a String>>(&mut self, iter: T) {
        for s in iter {
            self.push_str(s);
        }
    }
}

impl Extend<BytesString> for BytesString {
    fn extend<T: IntoIterator<Item = BytesString>>(&mut self, iter: T) {
        for s in iter {
            self.bytes.extend(s.bytes);
        }
    }
}

impl FromIterator<char> for BytesString {
    fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
        let mut bytes = BytesString::new();
        bytes.extend(iter);
        bytes
    }
}

impl<'a> FromIterator<&'a str> for BytesString {
    fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
        let mut bytes = BytesString::new();
        bytes.extend(iter);
        bytes
    }
}

impl FromIterator<Box<str>> for BytesString {
    fn from_iter<T: IntoIterator<Item = Box<str>>>(iter: T) -> Self {
        let mut bytes = BytesString::new();
        bytes.extend(iter);
        bytes
    }
}

impl<'a> FromIterator<Cow<'a, str>> for BytesString {
    fn from_iter<T: IntoIterator<Item = Cow<'a, str>>>(iter: T) -> Self {
        let mut bytes = BytesString::new();
        bytes.extend(iter);
        bytes
    }
}

impl FromIterator<String> for BytesString {
    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
        let mut bytes = BytesString::new();
        bytes.extend(iter);
        bytes
    }
}

impl FromIterator<BytesString> for BytesString {
    fn from_iter<T: IntoIterator<Item = BytesString>>(iter: T) -> Self {
        let mut bytes = BytesString::new();
        bytes.extend(iter);
        bytes
    }
}

impl FromStr for BytesString {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self {
            bytes: BytesMut::from(s),
        })
    }
}

impl<I> Index<I> for BytesString
where
    I: SliceIndex<str>,
{
    type Output = I::Output;

    fn index(&self, index: I) -> &Self::Output {
        self.as_str().index(index)
    }
}

impl<I> IndexMut<I> for BytesString
where
    I: SliceIndex<str>,
{
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        self.as_mut_str().index_mut(index)
    }
}

impl ToSocketAddrs for BytesString {
    type Iter = std::vec::IntoIter<SocketAddr>;

    fn to_socket_addrs(&self) -> Result<Self::Iter, std::io::Error> {
        self.as_str().to_socket_addrs()
    }
}

/// This produces the same hash as [str]
impl Hash for BytesString {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    use super::*;

    impl<'de> Deserialize<'de> for BytesString {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let s = String::deserialize(deserializer)?;
            Ok(Self::from(s))
        }
    }

    impl Serialize for BytesString {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_str(self.as_str())
        }
    }
}