ntex_bytes/
bytes.rs

1use std::{borrow, cmp, fmt, hash, mem, ops};
2
3use crate::{Buf, BytesMut, buf::IntoIter, debug, storage::INLINE_CAP, storage::Storage};
4
5/// A reference counted contiguous slice of memory.
6///
7/// `Bytes` is an efficient container for storing and operating on contiguous
8/// slices of memory. It is intended for use primarily in networking code, but
9/// could have applications elsewhere as well.
10///
11/// `Bytes` values facilitate zero-copy network programming by allowing multiple
12/// `Bytes` objects to point to the same underlying memory. This is managed by
13/// using a reference count to track when the memory is no longer needed and can
14/// be freed.
15///
16/// ```
17/// use ntex_bytes::Bytes;
18///
19/// let mut mem = Bytes::from(&b"Hello world"[..]);
20/// let a = mem.slice(0..5);
21///
22/// assert_eq!(a, b"Hello");
23///
24/// let b = mem.split_to(6);
25///
26/// assert_eq!(mem, b"world");
27/// assert_eq!(b, b"Hello ");
28/// ```
29///
30/// # Memory layout
31///
32/// The `Bytes` struct itself is fairly small, limited to a pointer to the
33/// memory and 4 `usize` fields used to track information about which segment of
34/// the underlying memory the `Bytes` handle has access to.
35///
36/// The memory layout looks like this:
37///
38/// ```text
39/// +-------+
40/// | Bytes |
41/// +-------+
42///  /      \_____
43/// |              \
44/// v               v
45/// +-----+------------------------------------+
46/// | Arc |         |      Data     |          |
47/// +-----+------------------------------------+
48/// ```
49///
50/// `Bytes` keeps both a pointer to the shared `Arc` containing the full memory
51/// slice and a pointer to the start of the region visible by the handle.
52/// `Bytes` also tracks the length of its view into the memory.
53///
54/// # Sharing
55///
56/// The memory itself is reference counted, and multiple `Bytes` objects may
57/// point to the same region. Each `Bytes` handle point to different sections within
58/// the memory region, and `Bytes` handle may or may not have overlapping views
59/// into the memory.
60///
61///
62/// ```text
63///
64///    Arc ptrs                   +---------+
65///    ________________________ / | Bytes 2 |
66///   /                           +---------+
67///  /          +-----------+     |         |
68/// |_________/ |  Bytes 1  |     |         |
69/// |           +-----------+     |         |
70/// |           |           | ___/ data     | tail
71/// |      data |      tail |/              |
72/// v           v           v               v
73/// +-----+---------------------------------+-----+
74/// | Arc |     |           |               |     |
75/// +-----+---------------------------------+-----+
76/// ```
77///
78/// # Mutating
79///
80/// While `Bytes` handles may potentially represent overlapping views of the
81/// underlying memory slice and may not be mutated, `BytesMut` handles are
82/// guaranteed to be the only handle able to view that slice of memory. As such,
83/// `BytesMut` handles are able to mutate the underlying memory. Note that
84/// holding a unique view to a region of memory does not mean that there are no
85/// other `Bytes` and `BytesMut` handles with disjoint views of the underlying
86/// memory.
87///
88/// # Inline bytes
89///
90/// As an optimization, when the slice referenced by a `Bytes` handle is small
91/// enough [^1]. In this case, a clone is no longer "shallow" and the data will
92/// be copied.  Converting from a `Vec` will never use inlining. `BytesMut` does
93/// not support data inlining and always allocates, but during converion to `Bytes`
94/// data from `BytesMut` could be inlined.
95///
96/// [^1]: Small enough: 31 bytes on 64 bit systems, 15 on 32 bit systems.
97///
98pub struct Bytes {
99    pub(crate) storage: Storage,
100}
101
102/*
103 *
104 * ===== Bytes =====
105 *
106 */
107
108impl Bytes {
109    /// Creates a new empty `Bytes`.
110    ///
111    /// This will not allocate and the returned `Bytes` handle will be empty.
112    ///
113    /// # Examples
114    ///
115    /// ```
116    /// use ntex_bytes::Bytes;
117    ///
118    /// let b = Bytes::new();
119    /// assert_eq!(&b[..], b"");
120    /// ```
121    #[inline]
122    pub const fn new() -> Bytes {
123        Bytes {
124            storage: Storage::empty(),
125        }
126    }
127
128    /// Creates a new `Bytes` from a static slice.
129    ///
130    /// The returned `Bytes` will point directly to the static slice. There is
131    /// no allocating or copying.
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// use ntex_bytes::Bytes;
137    ///
138    /// let b = Bytes::from_static(b"hello");
139    /// assert_eq!(&b[..], b"hello");
140    /// ```
141    #[inline]
142    pub const fn from_static(bytes: &'static [u8]) -> Bytes {
143        Bytes {
144            storage: Storage::from_static(bytes),
145        }
146    }
147
148    /// Returns the number of bytes contained in this `Bytes`.
149    ///
150    /// # Examples
151    ///
152    /// ```
153    /// use ntex_bytes::Bytes;
154    ///
155    /// let b = Bytes::from(&b"hello"[..]);
156    /// assert_eq!(b.len(), 5);
157    /// ```
158    #[inline]
159    pub fn len(&self) -> usize {
160        self.storage.len()
161    }
162
163    /// Returns true if the `Bytes` has a length of 0.
164    ///
165    /// # Examples
166    ///
167    /// ```
168    /// use ntex_bytes::Bytes;
169    ///
170    /// let b = Bytes::new();
171    /// assert!(b.is_empty());
172    /// ```
173    #[inline]
174    pub fn is_empty(&self) -> bool {
175        self.storage.is_empty()
176    }
177
178    /// Return true if the `Bytes` uses inline allocation
179    ///
180    /// # Examples
181    /// ```
182    /// use ntex_bytes::{Bytes, BytesMut};
183    ///
184    /// assert!(Bytes::from(BytesMut::from(&[0, 0, 0, 0][..])).is_inline());
185    /// assert!(Bytes::from(Vec::with_capacity(4)).is_inline());
186    /// assert!(!Bytes::from(&[0; 1024][..]).is_inline());
187    /// ```
188    pub fn is_inline(&self) -> bool {
189        self.storage.is_inline()
190    }
191
192    /// Creates `Bytes` instance from slice, by copying it.
193    pub fn copy_from_slice(data: &[u8]) -> Self {
194        Bytes {
195            storage: Storage::from_slice(data),
196        }
197    }
198
199    /// Returns a slice of self for the provided range.
200    ///
201    /// This will increment the reference count for the underlying memory and
202    /// return a new `Bytes` handle set to the slice.
203    ///
204    /// This operation is `O(1)`.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// use ntex_bytes::Bytes;
210    ///
211    /// let a = Bytes::from(b"hello world");
212    /// let b = a.slice(2..5);
213    ///
214    /// assert_eq!(&b[..], b"llo");
215    /// assert_eq!(&b[..=1], b"ll");
216    /// assert_eq!(&b[1..=1], b"l");
217    /// ```
218    ///
219    /// # Panics
220    ///
221    /// Requires that `begin <= end` and `end <= self.len()`, otherwise slicing
222    /// will panic.
223    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    /// Returns a slice of self for the provided range.
229    ///
230    /// Does nothing if `begin <= end` or `end <= self.len()`
231    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    /// Returns a slice of self that is equivalent to the given `subset`.
267    ///
268    /// When processing a `Bytes` buffer with other tools, one often gets a
269    /// `&[u8]` which is in fact a slice of the `Bytes`, i.e. a subset of it.
270    /// This function turns that `&[u8]` into another `Bytes`, as if one had
271    /// called `self.slice()` with the offsets that correspond to `subset`.
272    ///
273    /// This operation is `O(1)`.
274    ///
275    /// # Examples
276    ///
277    /// ```
278    /// use ntex_bytes::Bytes;
279    ///
280    /// let bytes = Bytes::from(&b"012345678"[..]);
281    /// let as_slice = bytes.as_ref();
282    /// let subset = &as_slice[2..6];
283    /// let subslice = bytes.slice_ref(&subset);
284    /// assert_eq!(subslice, b"2345");
285    /// ```
286    ///
287    /// # Panics
288    ///
289    /// Requires that the given `sub` slice is in fact contained within the
290    /// `Bytes` buffer; otherwise this function will panic.
291    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    /// Returns a slice of self that is equivalent to the given `subset`.
297    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    /// Splits the bytes into two at the given index.
313    ///
314    /// Afterwards `self` contains elements `[0, at)`, and the returned `Bytes`
315    /// contains elements `[at, len)`.
316    ///
317    /// This is an `O(1)` operation that just increases the reference count and
318    /// sets a few indices.
319    ///
320    /// # Examples
321    ///
322    /// ```
323    /// use ntex_bytes::Bytes;
324    ///
325    /// let mut a = Bytes::from(&b"hello world"[..]);
326    /// let b = a.split_off(5);
327    ///
328    /// assert_eq!(a, b"hello");
329    /// assert_eq!(b, b" world");
330    /// ```
331    ///
332    /// # Panics
333    ///
334    /// Panics if `at > self.len()`.
335    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    /// Splits the bytes into two at the given index.
341    ///
342    /// Does nothing if `at > self.len()`
343    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    /// Splits the bytes into two at the given index.
360    ///
361    /// Afterwards `self` contains elements `[at, len)`, and the returned
362    /// `Bytes` contains elements `[0, at)`.
363    ///
364    /// This is an `O(1)` operation that just increases the reference count and
365    /// sets a few indices.
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// use ntex_bytes::Bytes;
371    ///
372    /// let mut a = Bytes::from(&b"hello world"[..]);
373    /// let b = a.split_to(5);
374    ///
375    /// assert_eq!(a, b" world");
376    /// assert_eq!(b, b"hello");
377    /// ```
378    ///
379    /// # Panics
380    ///
381    /// Panics if `at > len`.
382    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    /// Splits the bytes into two at the given index.
388    ///
389    /// Does nothing if `at > len`.
390    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    /// Advance the internal cursor.
407    ///
408    /// Afterwards `self` contains elements `[cnt, len)`.
409    /// This is an `O(1)` operation.
410    ///
411    /// # Examples
412    ///
413    /// ```
414    /// use ntex_bytes::Bytes;
415    ///
416    /// let mut a = Bytes::copy_from_slice(&b"hello world"[..]);
417    /// a.advance_to(5);
418    ///
419    /// assert_eq!(&a[..], b" world");
420    /// ```
421    ///
422    /// # Panics
423    ///
424    /// Panics if `cnt > len`.
425    pub fn advance_to(&mut self, cnt: usize) {
426        unsafe {
427            self.storage.set_start(cnt);
428        }
429    }
430
431    /// Shortens the buffer, keeping the first `len` bytes and dropping the
432    /// rest.
433    ///
434    /// If `len` is greater than the buffer's current length, this has no
435    /// effect.
436    ///
437    /// The [`split_off`] method can emulate `truncate`, but this causes the
438    /// excess bytes to be returned instead of dropped.
439    ///
440    /// # Examples
441    ///
442    /// ```
443    /// use ntex_bytes::Bytes;
444    ///
445    /// let mut buf = Bytes::from(&b"hello world"[..]);
446    /// buf.truncate(5);
447    /// assert_eq!(buf, b"hello"[..]);
448    /// ```
449    ///
450    /// [`split_off`]: #method.split_off
451    #[inline]
452    pub fn truncate(&mut self, len: usize) {
453        self.storage.truncate(len, true);
454    }
455
456    /// Shortens the buffer to `len` bytes and dropping the rest.
457    ///
458    /// This is useful if underlying buffer is larger than cuurrent bytes object.
459    ///
460    /// # Examples
461    ///
462    /// ```
463    /// use ntex_bytes::Bytes;
464    ///
465    /// let mut buf = Bytes::from(&b"hello world"[..]);
466    /// buf.trimdown();
467    /// assert_eq!(buf, b"hello world"[..]);
468    /// ```
469    #[inline]
470    pub fn trimdown(&mut self) {
471        self.storage.trimdown();
472    }
473
474    /// Clears the buffer, removing all data.
475    ///
476    /// # Examples
477    ///
478    /// ```
479    /// use ntex_bytes::Bytes;
480    ///
481    /// let mut buf = Bytes::from(&b"hello world"[..]);
482    /// buf.clear();
483    /// assert!(buf.is_empty());
484    /// ```
485    #[inline]
486    pub fn clear(&mut self) {
487        self.storage = Storage::empty();
488    }
489
490    /// Returns an iterator over the bytes contained by the buffer.
491    ///
492    /// # Examples
493    ///
494    /// ```
495    /// use ntex_bytes::{Buf, Bytes};
496    ///
497    /// let buf = Bytes::from(&b"abc"[..]);
498    /// let mut iter = buf.iter();
499    ///
500    /// assert_eq!(iter.next().map(|b| *b), Some(b'a'));
501    /// assert_eq!(iter.next().map(|b| *b), Some(b'b'));
502    /// assert_eq!(iter.next().map(|b| *b), Some(b'c'));
503    /// assert_eq!(iter.next(), None);
504    /// ```
505    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    /// Convert a `Vec` into a `Bytes`
582    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
694/*
695 *
696 * ===== PartialEq / PartialOrd =====
697 *
698 */
699
700impl 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}