1use std::{borrow, cmp, fmt, hash, mem, ops};
2
3use crate::{Buf, BytesMut, buf::IntoIter, debug, storage::INLINE_CAP, storage::Storage};
4
5pub struct Bytes {
99 pub(crate) storage: Storage,
100}
101
102impl Bytes {
109 #[inline]
122 pub const fn new() -> Bytes {
123 Bytes {
124 storage: Storage::empty(),
125 }
126 }
127
128 #[inline]
142 pub const fn from_static(bytes: &'static [u8]) -> Bytes {
143 Bytes {
144 storage: Storage::from_static(bytes),
145 }
146 }
147
148 #[inline]
159 pub fn len(&self) -> usize {
160 self.storage.len()
161 }
162
163 #[inline]
174 pub fn is_empty(&self) -> bool {
175 self.storage.is_empty()
176 }
177
178 pub fn is_inline(&self) -> bool {
189 self.storage.is_inline()
190 }
191
192 pub fn copy_from_slice(data: &[u8]) -> Self {
194 Bytes {
195 storage: Storage::from_slice(data),
196 }
197 }
198
199 pub fn slice(&self, range: impl ops::RangeBounds<usize>) -> Bytes {
224 self.slice_checked(range)
225 .expect("Requires that `begin <= end` and `end <= self.len()`")
226 }
227
228 pub fn slice_checked(&self, range: impl ops::RangeBounds<usize>) -> Option<Bytes> {
232 use std::ops::Bound;
233
234 let len = self.len();
235
236 let begin = match range.start_bound() {
237 Bound::Included(&n) => n,
238 Bound::Excluded(&n) => n + 1,
239 Bound::Unbounded => 0,
240 };
241
242 let end = match range.end_bound() {
243 Bound::Included(&n) => n + 1,
244 Bound::Excluded(&n) => n,
245 Bound::Unbounded => len,
246 };
247
248 if begin <= end && end <= len {
249 if end - begin <= INLINE_CAP {
250 Some(Bytes {
251 storage: Storage::from_slice(&self[begin..end]),
252 })
253 } else {
254 let mut ret = self.clone();
255 unsafe {
256 ret.storage.set_end(end);
257 ret.storage.set_start(begin);
258 }
259 Some(ret)
260 }
261 } else {
262 None
263 }
264 }
265
266 pub fn slice_ref(&self, subset: &[u8]) -> Bytes {
292 self.slice_ref_checked(subset)
293 .expect("Given `sub` slice is not contained within the `Bytes` buffer")
294 }
295
296 pub fn slice_ref_checked(&self, subset: &[u8]) -> Option<Bytes> {
298 let bytes_p = self.as_ptr() as usize;
299 let bytes_len = self.len();
300
301 let sub_p = subset.as_ptr() as usize;
302 let sub_len = subset.len();
303
304 if sub_p >= bytes_p && sub_p + sub_len <= bytes_p + bytes_len {
305 let sub_offset = sub_p - bytes_p;
306 Some(self.slice(sub_offset..(sub_offset + sub_len)))
307 } else {
308 None
309 }
310 }
311
312 pub fn split_off(&mut self, at: usize) -> Bytes {
336 self.split_off_checked(at)
337 .expect("at value must be <= self.len()`")
338 }
339
340 pub fn split_off_checked(&mut self, at: usize) -> Option<Bytes> {
344 if at <= self.len() {
345 if at == self.len() {
346 Some(Bytes::new())
347 } else if at == 0 {
348 Some(mem::take(self))
349 } else {
350 Some(Bytes {
351 storage: self.storage.split_off(at, true),
352 })
353 }
354 } else {
355 None
356 }
357 }
358
359 pub fn split_to(&mut self, at: usize) -> Bytes {
383 self.split_to_checked(at)
384 .expect("at value must be <= self.len()`")
385 }
386
387 pub fn split_to_checked(&mut self, at: usize) -> Option<Bytes> {
391 if at <= self.len() {
392 if at == self.len() {
393 Some(mem::take(self))
394 } else if at == 0 {
395 Some(Bytes::new())
396 } else {
397 Some(Bytes {
398 storage: self.storage.split_to(at),
399 })
400 }
401 } else {
402 None
403 }
404 }
405
406 pub fn advance_to(&mut self, cnt: usize) {
426 unsafe {
427 self.storage.set_start(cnt);
428 }
429 }
430
431 #[inline]
452 pub fn truncate(&mut self, len: usize) {
453 self.storage.truncate(len, true);
454 }
455
456 #[inline]
470 pub fn trimdown(&mut self) {
471 self.storage.trimdown();
472 }
473
474 #[inline]
486 pub fn clear(&mut self) {
487 self.storage = Storage::empty();
488 }
489
490 pub fn iter(&'_ self) -> std::slice::Iter<'_, u8> {
506 self.chunk().iter()
507 }
508
509 #[inline]
510 #[doc(hidden)]
511 pub fn info(&self) -> crate::info::Info {
512 self.storage.info()
513 }
514}
515
516impl Buf for Bytes {
517 #[inline]
518 fn remaining(&self) -> usize {
519 self.len()
520 }
521
522 #[inline]
523 fn chunk(&self) -> &[u8] {
524 self.storage.as_ref()
525 }
526
527 #[inline]
528 fn advance(&mut self, cnt: usize) {
529 self.advance_to(cnt)
530 }
531}
532
533impl bytes::buf::Buf for Bytes {
534 #[inline]
535 fn remaining(&self) -> usize {
536 self.len()
537 }
538
539 #[inline]
540 fn chunk(&self) -> &[u8] {
541 self.storage.as_ref()
542 }
543
544 #[inline]
545 fn advance(&mut self, cnt: usize) {
546 self.advance_to(cnt)
547 }
548}
549
550impl Clone for Bytes {
551 fn clone(&self) -> Bytes {
552 Bytes {
553 storage: self.storage.clone(),
554 }
555 }
556}
557
558impl AsRef<[u8]> for Bytes {
559 #[inline]
560 fn as_ref(&self) -> &[u8] {
561 self.storage.as_ref()
562 }
563}
564
565impl ops::Deref for Bytes {
566 type Target = [u8];
567
568 #[inline]
569 fn deref(&self) -> &[u8] {
570 self.storage.as_ref()
571 }
572}
573
574impl From<&Bytes> for Bytes {
575 fn from(src: &Bytes) -> Bytes {
576 src.clone()
577 }
578}
579
580impl From<Vec<u8>> for Bytes {
581 fn from(src: Vec<u8>) -> Bytes {
583 Bytes {
584 storage: Storage::from_slice(&src),
585 }
586 }
587}
588
589impl From<String> for Bytes {
590 fn from(src: String) -> Bytes {
591 Bytes {
592 storage: Storage::from_slice(src.as_bytes()),
593 }
594 }
595}
596
597impl From<&'static [u8]> for Bytes {
598 fn from(src: &'static [u8]) -> Bytes {
599 Bytes::from_static(src)
600 }
601}
602
603impl From<&'static str> for Bytes {
604 fn from(src: &'static str) -> Bytes {
605 Bytes::from_static(src.as_bytes())
606 }
607}
608
609impl<'a, const N: usize> From<&'a [u8; N]> for Bytes {
610 fn from(src: &'a [u8; N]) -> Bytes {
611 Bytes::copy_from_slice(src)
612 }
613}
614
615impl FromIterator<u8> for Bytes {
616 fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
617 BytesMut::from_iter(into_iter).freeze()
618 }
619}
620
621impl<'a> FromIterator<&'a u8> for Bytes {
622 fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
623 BytesMut::from_iter(into_iter).freeze()
624 }
625}
626
627impl Eq for Bytes {}
628
629impl PartialEq for Bytes {
630 fn eq(&self, other: &Bytes) -> bool {
631 self.storage.as_ref() == other.storage.as_ref()
632 }
633}
634
635impl PartialOrd for Bytes {
636 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
637 Some(self.cmp(other))
638 }
639}
640
641impl Ord for Bytes {
642 fn cmp(&self, other: &Bytes) -> cmp::Ordering {
643 self.storage.as_ref().cmp(other.storage.as_ref())
644 }
645}
646
647impl Default for Bytes {
648 #[inline]
649 fn default() -> Bytes {
650 Bytes::new()
651 }
652}
653
654impl fmt::Debug for Bytes {
655 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
656 fmt::Debug::fmt(&debug::BsDebug(self.storage.as_ref()), fmt)
657 }
658}
659
660impl hash::Hash for Bytes {
661 fn hash<H>(&self, state: &mut H)
662 where
663 H: hash::Hasher,
664 {
665 let s: &[u8] = self.as_ref();
666 s.hash(state);
667 }
668}
669
670impl borrow::Borrow<[u8]> for Bytes {
671 fn borrow(&self) -> &[u8] {
672 self.as_ref()
673 }
674}
675
676impl IntoIterator for Bytes {
677 type Item = u8;
678 type IntoIter = IntoIter<Bytes>;
679
680 fn into_iter(self) -> Self::IntoIter {
681 IntoIter::new(self)
682 }
683}
684
685impl<'a> IntoIterator for &'a Bytes {
686 type Item = &'a u8;
687 type IntoIter = std::slice::Iter<'a, u8>;
688
689 fn into_iter(self) -> Self::IntoIter {
690 self.as_ref().iter()
691 }
692}
693
694impl PartialEq<[u8]> for Bytes {
701 fn eq(&self, other: &[u8]) -> bool {
702 self.storage.as_ref() == other
703 }
704}
705
706impl<const N: usize> PartialEq<[u8; N]> for Bytes {
707 fn eq(&self, other: &[u8; N]) -> bool {
708 self.storage.as_ref() == other.as_ref()
709 }
710}
711
712impl PartialOrd<[u8]> for Bytes {
713 fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
714 self.storage.as_ref().partial_cmp(other)
715 }
716}
717
718impl<const N: usize> PartialOrd<[u8; N]> for Bytes {
719 fn partial_cmp(&self, other: &[u8; N]) -> Option<cmp::Ordering> {
720 self.storage.as_ref().partial_cmp(other.as_ref())
721 }
722}
723
724impl PartialEq<Bytes> for [u8] {
725 fn eq(&self, other: &Bytes) -> bool {
726 *other == *self
727 }
728}
729
730impl<const N: usize> PartialEq<Bytes> for [u8; N] {
731 fn eq(&self, other: &Bytes) -> bool {
732 *other == *self
733 }
734}
735
736impl<const N: usize> PartialEq<Bytes> for &[u8; N] {
737 fn eq(&self, other: &Bytes) -> bool {
738 *other == *self
739 }
740}
741
742impl PartialOrd<Bytes> for [u8] {
743 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
744 other.partial_cmp(self)
745 }
746}
747
748impl<const N: usize> PartialOrd<Bytes> for [u8; N] {
749 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
750 other.partial_cmp(self)
751 }
752}
753
754impl PartialEq<str> for Bytes {
755 fn eq(&self, other: &str) -> bool {
756 self.storage.as_ref() == other.as_bytes()
757 }
758}
759
760impl PartialOrd<str> for Bytes {
761 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
762 self.storage.as_ref().partial_cmp(other.as_bytes())
763 }
764}
765
766impl PartialEq<Bytes> for str {
767 fn eq(&self, other: &Bytes) -> bool {
768 *other == *self
769 }
770}
771
772impl PartialOrd<Bytes> for str {
773 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
774 other.partial_cmp(self)
775 }
776}
777
778impl PartialEq<Vec<u8>> for Bytes {
779 fn eq(&self, other: &Vec<u8>) -> bool {
780 *self == other[..]
781 }
782}
783
784impl PartialOrd<Vec<u8>> for Bytes {
785 fn partial_cmp(&self, other: &Vec<u8>) -> Option<cmp::Ordering> {
786 self.storage.as_ref().partial_cmp(&other[..])
787 }
788}
789
790impl PartialEq<Bytes> for Vec<u8> {
791 fn eq(&self, other: &Bytes) -> bool {
792 *other == *self
793 }
794}
795
796impl PartialOrd<Bytes> for Vec<u8> {
797 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
798 other.partial_cmp(self)
799 }
800}
801
802impl PartialEq<String> for Bytes {
803 fn eq(&self, other: &String) -> bool {
804 *self == other[..]
805 }
806}
807
808impl PartialOrd<String> for Bytes {
809 fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
810 self.storage.as_ref().partial_cmp(other.as_bytes())
811 }
812}
813
814impl PartialEq<Bytes> for String {
815 fn eq(&self, other: &Bytes) -> bool {
816 *other == *self
817 }
818}
819
820impl PartialOrd<Bytes> for String {
821 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
822 other.partial_cmp(self)
823 }
824}
825
826impl PartialEq<Bytes> for &[u8] {
827 fn eq(&self, other: &Bytes) -> bool {
828 *other == *self
829 }
830}
831
832impl PartialOrd<Bytes> for &[u8] {
833 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
834 other.partial_cmp(self)
835 }
836}
837
838impl PartialEq<Bytes> for &str {
839 fn eq(&self, other: &Bytes) -> bool {
840 *other == *self
841 }
842}
843
844impl PartialOrd<Bytes> for &str {
845 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
846 other.partial_cmp(self)
847 }
848}
849
850impl<'a, T: ?Sized> PartialEq<&'a T> for Bytes
851where
852 Bytes: PartialEq<T>,
853{
854 fn eq(&self, other: &&'a T) -> bool {
855 *self == **other
856 }
857}
858
859impl<'a, T: ?Sized> PartialOrd<&'a T> for Bytes
860where
861 Bytes: PartialOrd<T>,
862{
863 fn partial_cmp(&self, other: &&'a T) -> Option<cmp::Ordering> {
864 self.partial_cmp(&**other)
865 }
866}
867
868#[cfg(test)]
869mod tests {
870 use std::collections::HashMap;
871
872 use super::*;
873 use crate::BufMut;
874
875 const LONG: &[u8] = b"mary had a1 little la2mb, little lamb, little lamb, little lamb, little lamb, little lamb \
876 mary had a little lamb, little lamb, little lamb, little lamb, little lamb, little lamb \
877 mary had a little lamb, little lamb, little lamb, little lamb, little lamb, little lamb \0";
878
879 #[test]
880 #[allow(
881 clippy::op_ref,
882 clippy::len_zero,
883 clippy::nonminimal_bool,
884 clippy::unnecessary_fallible_conversions
885 )]
886 fn bytes() {
887 let mut b = Bytes::from(LONG.to_vec());
888 b.advance_to(10);
889 assert_eq!(&b, &LONG[10..]);
890 b.advance_to(10);
891 assert_eq!(&b[..], &LONG[20..]);
892 assert_eq!(&b, &LONG[20..]);
893 b.clear();
894 assert!(b.is_inline());
895 assert!(b.is_empty());
896 assert!(b.len() == 0);
897
898 let mut b = Bytes::from(LONG);
899 b.advance_to(10);
900 assert_eq!(&b, &LONG[10..]);
901 b.advance_to(10);
902 assert_eq!(&b[..], &LONG[20..]);
903 assert_eq!(&b, &LONG[20..]);
904 b.clear();
905 assert!(b.is_empty());
906 assert!(b.len() == 0);
907
908 let mut b = Bytes::from(LONG);
909 b.split_off(10);
910 assert_eq!(&b, &LONG[..10]);
911 b.advance_to(5);
912 assert_eq!(&b, &LONG[5..10]);
913
914 let mut b = Bytes::copy_from_slice(&LONG[..15]);
915 assert!(b.is_inline());
916 b.split_off(10);
917 assert_eq!(&b, &LONG[..10]);
918 b.advance_to(1);
919 assert_eq!(&b, &LONG[1..10]);
920
921 let b = Bytes::from(b"123");
922 assert!(&b"12"[..] > &b);
923 assert!("123" == &b);
924 assert!("12" > &b);
925
926 let b = Bytes::from(&Bytes::from(LONG));
927 assert_eq!(b, LONG);
928
929 let b = Bytes::from(BytesMut::from(LONG));
930 assert_eq!(b, LONG);
931
932 let mut b: Bytes = BytesMut::try_from(b).unwrap().freeze();
933 assert_eq!(b, LONG);
934 assert!(!(b > b));
935 assert_eq!(<Bytes as Buf>::remaining(&b), LONG.len());
936 assert_eq!(<Bytes as Buf>::chunk(&b), LONG);
937 <Bytes as Buf>::advance(&mut b, 10);
938 assert_eq!(Buf::chunk(&b), &LONG[10..]);
939 <Bytes as Buf>::advance(&mut b, 10);
940 assert_eq!(Buf::chunk(&b), &LONG[20..]);
941
942 let mut h: HashMap<Bytes, usize> = HashMap::default();
943 h.insert(b.clone(), 1);
944 assert_eq!(h.get(&b), Some(&1));
945
946 let mut b = BytesMut::try_from(LONG).unwrap();
947 assert_eq!(b, LONG);
948 assert_eq!(<BytesMut as Buf>::remaining(&b), LONG.len());
949 assert_eq!(<BytesMut as BufMut>::remaining_mut(&b), 0);
950 assert_eq!(<BytesMut as Buf>::chunk(&b), LONG);
951 <BytesMut as Buf>::advance(&mut b, 10);
952 assert_eq!(<BytesMut as Buf>::chunk(&b), &LONG[10..]);
953
954 let mut b = BytesMut::with_capacity(12);
955 <BytesMut as BufMut>::put_i8(&mut b, 1);
956 assert_eq!(b, b"\x01".as_ref());
957 <BytesMut as BufMut>::put_u8(&mut b, 2);
958 assert_eq!(b, b"\x01\x02".as_ref());
959 <BytesMut as BufMut>::put_slice(&mut b, b"12345");
960 assert_eq!(b, b"\x01\x0212345".as_ref());
961 <BytesMut as BufMut>::chunk_mut(&mut b).write_byte(0, b'1');
962 unsafe { <BytesMut as BufMut>::advance_mut(&mut b, 1) };
963 assert_eq!(b, b"\x01\x02123451".as_ref());
964
965 let mut iter = Bytes::from(LONG.to_vec()).into_iter();
966 assert_eq!(iter.next(), Some(LONG[0]));
967 assert_eq!(iter.next(), Some(LONG[1]));
968 assert_eq!(iter.next(), Some(LONG[2]));
969 assert_eq!(iter.next(), Some(LONG[3]));
970 }
971}