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#[derive(Clone, Default, PartialEq, Eq)]
28pub struct BytesString {
29 pub(crate) bytes: BytesMut,
30}
31
32impl BytesString {
33 pub fn new() -> Self {
45 Self {
46 bytes: BytesMut::new(),
47 }
48 }
49
50 pub fn with_capacity(capacity: usize) -> Self {
66 Self {
67 bytes: BytesMut::with_capacity(capacity),
68 }
69 }
70
71 pub fn len(&self) -> usize {
83 self.bytes.len()
84 }
85
86 pub fn capacity(&self) -> usize {
98 self.bytes.capacity()
99 }
100
101 pub fn reserve(&mut self, additional: usize) {
120 self.bytes.reserve(additional);
121 }
122
123 pub fn split_off(&mut self, at: usize) -> Self {
142 Self {
143 bytes: self.bytes.split_off(at),
144 }
145 }
146
147 pub fn as_bytes(&self) -> &[u8] {
159 self.bytes.as_ref()
160 }
161
162 pub fn is_empty(&self) -> bool {
174 self.bytes.is_empty()
175 }
176
177 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 pub fn clear(&mut self) {
228 self.bytes.clear();
229 }
230
231 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 pub fn push_str(&mut self, s: &str) {
264 self.bytes.extend_from_slice(s.as_bytes());
265 }
266
267 pub fn as_str(&self) -> &str {
279 unsafe { std::str::from_utf8_unchecked(&self.bytes) }
280 }
281
282 pub fn as_mut_str(&mut self) -> &mut str {
296 unsafe { std::str::from_utf8_unchecked_mut(&mut self.bytes) }
297 }
298
299 pub fn into_bytes(self) -> BytesMut {
314 self.bytes
315 }
316
317 pub unsafe fn from_bytes_unchecked(bytes: BytesMut) -> Self {
325 Self { bytes }
326 }
327
328 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 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
714impl 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}