ntex_bytes/
bytesmut.rs

1use std::{borrow, fmt, ops, ptr};
2
3use crate::{Buf, BufMut, Bytes, buf::IntoIter, buf::UninitSlice, debug, storage::Storage};
4
5/// A unique reference to a contiguous slice of memory.
6///
7/// `BytesMut` represents a unique view into a potentially shared memory region.
8/// Given the uniqueness guarantee, owners of `BytesMut` handles are able to
9/// mutate the memory. It is similar to a `Vec<u8>` but with less copies and
10/// allocations.
11///
12/// For more detail, see [Bytes](struct.Bytes.html).
13///
14/// # Growth
15///
16/// One key difference from `Vec<u8>` is that most operations **do not
17/// implicitly grow the buffer**. This means that calling `my_bytes.put("hello
18/// world");` could panic if `my_bytes` does not have enough capacity. Before
19/// writing to the buffer, ensure that there is enough remaining capacity by
20/// calling `my_bytes.remaining_mut()`. In general, avoiding calls to `reserve`
21/// is preferable.
22///
23/// The only exception is `extend` which implicitly reserves required capacity.
24///
25/// # Examples
26///
27/// ```
28/// use ntex_bytes::{BytesMut, BufMut};
29///
30/// let mut buf = BytesMut::with_capacity(64);
31///
32/// buf.put_u8(b'h');
33/// buf.put_u8(b'e');
34/// buf.put("llo");
35///
36/// assert_eq!(buf, b"hello");
37///
38/// // Freeze the buffer so that it can be shared
39/// let a = buf.freeze();
40///
41/// // This does not allocate, instead `b` points to the same memory.
42/// let b = a.clone();
43///
44/// assert_eq!(a, b"hello");
45/// assert_eq!(b, b"hello");
46/// ```
47pub struct BytesMut {
48    pub(crate) storage: Storage,
49}
50
51/*
52 *
53 * ===== BytesMut =====
54 *
55 */
56
57impl BytesMut {
58    /// Creates a new `BytesMut` with the specified capacity.
59    ///
60    /// The returned `BytesMut` will be able to hold at least `capacity` bytes
61    /// without reallocating. If `capacity` is under `4 * size_of::<usize>() - 1`,
62    /// then `BytesMut` will not allocate.
63    ///
64    /// It is important to note that this function does not specify the length
65    /// of the returned `BytesMut`, but only the capacity.
66    ///
67    /// # Panics
68    ///
69    /// Panics if `capacity` greater than 60bit for 64bit systems
70    /// and 28bit for 32bit systems
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// use ntex_bytes::{BytesMut, BufMut};
76    ///
77    /// let mut bytes = BytesMut::with_capacity(64);
78    ///
79    /// // `bytes` contains no data, even though there is capacity
80    /// assert_eq!(bytes.len(), 0);
81    ///
82    /// bytes.put(&b"hello world"[..]);
83    ///
84    /// assert_eq!(&bytes[..], b"hello world");
85    /// ```
86    #[inline]
87    pub fn with_capacity(capacity: usize) -> BytesMut {
88        BytesMut {
89            storage: Storage::with_capacity(capacity),
90        }
91    }
92
93    /// Creates a new `BytesMut` from slice, by copying it.
94    pub fn copy_from_slice<T: AsRef<[u8]>>(src: T) -> Self {
95        BytesMut {
96            storage: Storage::from_slice(src.as_ref()),
97        }
98    }
99
100    #[inline]
101    /// Convert a `Vec` into a `BytesMut`
102    pub fn from_vec(src: Vec<u8>) -> BytesMut {
103        BytesMut {
104            storage: Storage::from_vec(src),
105        }
106    }
107
108    /// Creates a new `BytesMut` with default capacity.
109    ///
110    /// Resulting object has length 0 and unspecified capacity.
111    /// This function does not allocate.
112    ///
113    /// # Examples
114    ///
115    /// ```
116    /// use ntex_bytes::{BytesMut, BufMut};
117    ///
118    /// let mut bytes = BytesMut::new();
119    ///
120    /// assert_eq!(0, bytes.len());
121    ///
122    /// bytes.reserve(2);
123    /// bytes.put_slice(b"xy");
124    ///
125    /// assert_eq!(&b"xy"[..], &bytes[..]);
126    /// ```
127    #[inline]
128    pub fn new() -> BytesMut {
129        BytesMut {
130            storage: Storage::empty_inline(),
131        }
132    }
133
134    /// Returns the number of bytes contained in this `BytesMut`.
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// use ntex_bytes::BytesMut;
140    ///
141    /// let b = BytesMut::from(&b"hello"[..]);
142    /// assert_eq!(b.len(), 5);
143    /// ```
144    #[inline]
145    pub fn len(&self) -> usize {
146        self.storage.len()
147    }
148
149    /// Returns true if the `BytesMut` has a length of 0.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use ntex_bytes::BytesMut;
155    ///
156    /// let b = BytesMut::with_capacity(64);
157    /// assert!(b.is_empty());
158    /// ```
159    #[inline]
160    pub fn is_empty(&self) -> bool {
161        self.storage.is_empty()
162    }
163
164    /// Returns the number of bytes the `BytesMut` can hold without reallocating.
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// use ntex_bytes::BytesMut;
170    ///
171    /// let b = BytesMut::with_capacity(64);
172    /// assert_eq!(b.capacity(), 72);
173    /// ```
174    #[inline]
175    pub fn capacity(&self) -> usize {
176        self.storage.capacity()
177    }
178
179    /// Converts `self` into an immutable `Bytes`.
180    ///
181    /// The conversion is zero cost and is used to indicate that the slice
182    /// referenced by the handle will no longer be mutated. Once the conversion
183    /// is done, the handle can be cloned and shared across threads.
184    ///
185    /// # Examples
186    ///
187    /// ```
188    /// use ntex_bytes::{BytesMut, BufMut};
189    /// use std::thread;
190    ///
191    /// let mut b = BytesMut::with_capacity(64);
192    /// b.put("hello world");
193    /// let b1 = b.freeze();
194    /// let b2 = b1.clone();
195    ///
196    /// let th = thread::spawn(move || {
197    ///     assert_eq!(b1, b"hello world");
198    /// });
199    ///
200    /// assert_eq!(b2, b"hello world");
201    /// th.join().unwrap();
202    /// ```
203    #[inline]
204    pub fn freeze(self) -> Bytes {
205        Bytes {
206            storage: self.storage.freeze(),
207        }
208    }
209
210    /// Splits the bytes into two at the given index.
211    ///
212    /// Afterwards `self` contains elements `[0, at)`, and the returned
213    /// `BytesMut` contains elements `[at, capacity)`.
214    ///
215    /// This is an `O(1)` operation that just increases the reference count
216    /// and sets a few indices.
217    ///
218    /// # Examples
219    ///
220    /// ```
221    /// use ntex_bytes::BytesMut;
222    ///
223    /// let mut a = BytesMut::from(&b"hello world"[..]);
224    /// let mut b = a.split_off(5);
225    ///
226    /// a[0] = b'j';
227    /// b[0] = b'!';
228    ///
229    /// assert_eq!(&a[..], b"jello");
230    /// assert_eq!(&b[..], b"!world");
231    /// ```
232    ///
233    /// # Panics
234    ///
235    /// Panics if `at > capacity`.
236    pub fn split_off(&mut self, at: usize) -> BytesMut {
237        BytesMut {
238            storage: self.storage.split_off(at, false),
239        }
240    }
241
242    /// Removes the bytes from the current view, returning them in a new
243    /// `BytesMut` handle.
244    ///
245    /// Afterwards, `self` will be empty, but will retain any additional
246    /// capacity that it had before the operation. This is identical to
247    /// `self.split_to(self.len())`.
248    ///
249    /// This is an `O(1)` operation that just increases the reference count and
250    /// sets a few indices.
251    ///
252    /// # Examples
253    ///
254    /// ```
255    /// use ntex_bytes::{BytesMut, BufMut};
256    ///
257    /// let mut buf = BytesMut::with_capacity(1024);
258    /// buf.put(&b"hello world"[..]);
259    ///
260    /// let other = buf.split();
261    ///
262    /// assert!(buf.is_empty());
263    /// assert_eq!(1021, buf.capacity());
264    ///
265    /// assert_eq!(other, b"hello world"[..]);
266    /// ```
267    pub fn split(&mut self) -> BytesMut {
268        self.split_to(self.len())
269    }
270
271    /// Splits the buffer into two at the given index.
272    ///
273    /// Afterwards `self` contains elements `[at, len)`, and the returned `BytesMut`
274    /// contains elements `[0, at)`.
275    ///
276    /// This is an `O(1)` operation that just increases the reference count and
277    /// sets a few indices.
278    ///
279    /// # Examples
280    ///
281    /// ```
282    /// use ntex_bytes::BytesMut;
283    ///
284    /// let mut a = BytesMut::from(&b"hello world"[..]);
285    /// let mut b = a.split_to(5);
286    ///
287    /// a[0] = b'!';
288    /// b[0] = b'j';
289    ///
290    /// assert_eq!(&a[..], b"!world");
291    /// assert_eq!(&b[..], b"jello");
292    /// ```
293    ///
294    /// # Panics
295    ///
296    /// Panics if `at > len`.
297    pub fn split_to(&mut self, at: usize) -> BytesMut {
298        self.split_to_checked(at)
299            .expect("at value must be <= self.len()`")
300    }
301
302    /// Splits the bytes into two at the given index.
303    ///
304    /// Does nothing if `at > len`.
305    pub fn split_to_checked(&mut self, at: usize) -> Option<BytesMut> {
306        if at <= self.len() {
307            Some(BytesMut {
308                storage: self.storage.split_to(at, false),
309            })
310        } else {
311            None
312        }
313    }
314
315    /// Shortens the buffer, keeping the first `len` bytes and dropping the
316    /// rest.
317    ///
318    /// If `len` is greater than the buffer's current length, this has no
319    /// effect.
320    ///
321    /// The [`split_off`] method can emulate `truncate`, but this causes the
322    /// excess bytes to be returned instead of dropped.
323    ///
324    /// # Examples
325    ///
326    /// ```
327    /// use ntex_bytes::BytesMut;
328    ///
329    /// let mut buf = BytesMut::from(&b"hello world"[..]);
330    /// buf.truncate(5);
331    /// assert_eq!(buf, b"hello"[..]);
332    /// ```
333    ///
334    /// [`split_off`]: #method.split_off
335    pub fn truncate(&mut self, len: usize) {
336        self.storage.truncate(len, false);
337    }
338
339    /// Clears the buffer, removing all data.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use ntex_bytes::BytesMut;
345    ///
346    /// let mut buf = BytesMut::from(&b"hello world"[..]);
347    /// buf.clear();
348    /// assert!(buf.is_empty());
349    /// ```
350    pub fn clear(&mut self) {
351        self.truncate(0);
352    }
353
354    /// Resizes the buffer so that `len` is equal to `new_len`.
355    ///
356    /// If `new_len` is greater than `len`, the buffer is extended by the
357    /// difference with each additional byte set to `value`. If `new_len` is
358    /// less than `len`, the buffer is simply truncated.
359    ///
360    /// # Panics
361    ///
362    /// Panics if `new_len` greater than 60bit for 64bit systems
363    /// and 28bit for 32bit systems
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// use ntex_bytes::BytesMut;
369    ///
370    /// let mut buf = BytesMut::new();
371    ///
372    /// buf.resize(3, 0x1);
373    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
374    ///
375    /// buf.resize(2, 0x2);
376    /// assert_eq!(&buf[..], &[0x1, 0x1]);
377    ///
378    /// buf.resize(4, 0x3);
379    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
380    /// ```
381    #[inline]
382    pub fn resize(&mut self, new_len: usize, value: u8) {
383        self.storage.resize(new_len, value);
384    }
385
386    /// Sets the length of the buffer.
387    ///
388    /// This will explicitly set the size of the buffer without actually
389    /// modifying the data, so it is up to the caller to ensure that the data
390    /// has been initialized.
391    ///
392    /// # Examples
393    ///
394    /// ```
395    /// use ntex_bytes::BytesMut;
396    ///
397    /// let mut b = BytesMut::from(&b"hello world"[..]);
398    ///
399    /// unsafe {
400    ///     b.set_len(5);
401    /// }
402    ///
403    /// assert_eq!(&b[..], b"hello");
404    ///
405    /// unsafe {
406    ///     b.set_len(11);
407    /// }
408    ///
409    /// assert_eq!(&b[..], b"hello world");
410    /// ```
411    ///
412    /// # Panics
413    ///
414    /// This method will panic if `len` is out of bounds for the underlying
415    /// slice or if it comes after the `end` of the configured window.
416    #[inline]
417    #[allow(clippy::missing_safety_doc)]
418    pub unsafe fn set_len(&mut self, len: usize) {
419        self.storage.set_len(len)
420    }
421
422    /// Reserves capacity for at least `additional` more bytes to be inserted
423    /// into the given `BytesMut`.
424    ///
425    /// More than `additional` bytes may be reserved in order to avoid frequent
426    /// reallocations. A call to `reserve` may result in an allocation.
427    ///
428    /// Before allocating new buffer space, the function will attempt to reclaim
429    /// space in the existing buffer. If the current handle references a small
430    /// view in the original buffer and all other handles have been dropped,
431    /// and the requested capacity is less than or equal to the existing
432    /// buffer's capacity, then the current view will be copied to the front of
433    /// the buffer and the handle will take ownership of the full buffer.
434    ///
435    /// # Panics
436    ///
437    /// Panics if new capacity is greater than 60bit for 64bit systems
438    /// and 28bit for 32bit systems
439    ///
440    /// # Examples
441    ///
442    /// In the following example, a new buffer is allocated.
443    ///
444    /// ```
445    /// use ntex_bytes::BytesMut;
446    ///
447    /// let mut buf = BytesMut::from(&b"hello"[..]);
448    /// buf.reserve(64);
449    /// assert!(buf.capacity() >= 69);
450    /// ```
451    ///
452    /// In the following example, the existing buffer is reclaimed.
453    ///
454    /// ```
455    /// use ntex_bytes::{BytesMut, BufMut};
456    ///
457    /// let mut buf = BytesMut::with_capacity(128);
458    /// buf.put(&[0; 64][..]);
459    ///
460    /// let ptr = buf.as_ptr();
461    /// let other = buf.split();
462    ///
463    /// assert!(buf.is_empty());
464    /// assert_eq!(buf.capacity(), 80);
465    ///
466    /// drop(other);
467    /// buf.reserve(128);
468    ///
469    /// assert_eq!(buf.capacity(), 144);
470    /// assert_eq!(buf.as_ptr(), ptr);
471    /// ```
472    ///
473    /// # Panics
474    ///
475    /// Panics if the new capacity overflows `usize`.
476    #[inline]
477    pub fn reserve(&mut self, additional: usize) {
478        self.storage.reserve(additional);
479    }
480
481    /// Appends given bytes to this object.
482    ///
483    /// If this `BytesMut` object has not enough capacity, it is resized first.
484    /// So unlike `put_slice` operation, `extend_from_slice` does not panic.
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use ntex_bytes::BytesMut;
490    ///
491    /// let mut buf = BytesMut::with_capacity(0);
492    /// buf.extend_from_slice(b"aaabbb");
493    /// buf.extend_from_slice(b"cccddd");
494    ///
495    /// assert_eq!(b"aaabbbcccddd", &buf[..]);
496    /// ```
497    #[inline]
498    pub fn extend_from_slice(&mut self, extend: &[u8]) {
499        self.put_slice(extend);
500    }
501
502    /// Returns an iterator over the bytes contained by the buffer.
503    ///
504    /// # Examples
505    ///
506    /// ```
507    /// use ntex_bytes::{Buf, BytesMut};
508    ///
509    /// let buf = BytesMut::from(&b"abc"[..]);
510    /// let mut iter = buf.iter();
511    ///
512    /// assert_eq!(iter.next().map(|b| *b), Some(b'a'));
513    /// assert_eq!(iter.next().map(|b| *b), Some(b'b'));
514    /// assert_eq!(iter.next().map(|b| *b), Some(b'c'));
515    /// assert_eq!(iter.next(), None);
516    /// ```
517    #[inline]
518    pub fn iter(&'_ self) -> std::slice::Iter<'_, u8> {
519        self.chunk().iter()
520    }
521
522    #[inline]
523    #[doc(hidden)]
524    pub fn info(&self) -> crate::info::Info {
525        self.storage.info()
526    }
527}
528
529impl Buf for BytesMut {
530    #[inline]
531    fn remaining(&self) -> usize {
532        self.len()
533    }
534
535    #[inline]
536    fn chunk(&self) -> &[u8] {
537        self.storage.as_ref()
538    }
539
540    #[inline]
541    fn advance(&mut self, cnt: usize) {
542        assert!(cnt <= self.storage.len(), "cannot advance past `remaining`");
543        unsafe {
544            self.storage.set_start(cnt);
545        }
546    }
547}
548
549impl BufMut for BytesMut {
550    #[inline]
551    fn remaining_mut(&self) -> usize {
552        self.capacity() - self.len()
553    }
554
555    #[inline]
556    unsafe fn advance_mut(&mut self, cnt: usize) {
557        let new_len = self.len() + cnt;
558
559        // This call will panic if `cnt` is too big
560        self.storage.set_len(new_len);
561    }
562
563    #[inline]
564    fn chunk_mut(&mut self) -> &mut UninitSlice {
565        let len = self.len();
566
567        unsafe {
568            // This will never panic as `len` can never become invalid
569            let ptr = &mut self.storage.as_raw()[len..];
570
571            UninitSlice::from_raw_parts_mut(ptr.as_mut_ptr(), self.capacity() - len)
572        }
573    }
574
575    #[inline]
576    fn put_slice(&mut self, src: &[u8]) {
577        let len = src.len();
578        self.reserve(len);
579
580        unsafe {
581            ptr::copy_nonoverlapping(src.as_ptr(), self.chunk_mut().as_mut_ptr(), len);
582            self.advance_mut(len);
583        }
584    }
585
586    #[inline]
587    fn put_u8(&mut self, n: u8) {
588        self.reserve(1);
589        self.storage.put_u8(n);
590    }
591
592    #[inline]
593    fn put_i8(&mut self, n: i8) {
594        self.reserve(1);
595        self.put_u8(n as u8);
596    }
597}
598
599impl bytes::buf::Buf for BytesMut {
600    #[inline]
601    fn remaining(&self) -> usize {
602        self.len()
603    }
604
605    #[inline]
606    fn chunk(&self) -> &[u8] {
607        self.storage.as_ref()
608    }
609
610    #[inline]
611    fn advance(&mut self, cnt: usize) {
612        Buf::advance(self, cnt)
613    }
614}
615
616unsafe impl bytes::buf::BufMut for BytesMut {
617    #[inline]
618    fn remaining_mut(&self) -> usize {
619        BufMut::remaining_mut(self)
620    }
621
622    #[inline]
623    unsafe fn advance_mut(&mut self, cnt: usize) {
624        BufMut::advance_mut(self, cnt)
625    }
626
627    #[inline]
628    fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
629        let len = self.len();
630        unsafe {
631            // This will never panic as `len` can never become invalid
632            let ptr = &mut self.storage.as_raw()[len..];
633            bytes::buf::UninitSlice::from_raw_parts_mut(
634                ptr.as_mut_ptr(),
635                self.capacity() - len,
636            )
637        }
638    }
639
640    #[inline]
641    fn put_slice(&mut self, src: &[u8]) {
642        BufMut::put_slice(self, src)
643    }
644
645    #[inline]
646    fn put_u8(&mut self, n: u8) {
647        BufMut::put_u8(self, n)
648    }
649
650    #[inline]
651    fn put_i8(&mut self, n: i8) {
652        BufMut::put_i8(self, n)
653    }
654}
655
656impl AsRef<[u8]> for BytesMut {
657    #[inline]
658    fn as_ref(&self) -> &[u8] {
659        self.storage.as_ref()
660    }
661}
662
663impl AsMut<[u8]> for BytesMut {
664    #[inline]
665    fn as_mut(&mut self) -> &mut [u8] {
666        self.storage.as_mut()
667    }
668}
669
670impl ops::Deref for BytesMut {
671    type Target = [u8];
672
673    #[inline]
674    fn deref(&self) -> &[u8] {
675        self.as_ref()
676    }
677}
678
679impl ops::DerefMut for BytesMut {
680    #[inline]
681    fn deref_mut(&mut self) -> &mut [u8] {
682        self.storage.as_mut()
683    }
684}
685
686impl From<Vec<u8>> for BytesMut {
687    #[inline]
688    /// Convert a `Vec` into a `BytesMut`
689    ///
690    /// This constructor may be used to avoid the inlining optimization used by
691    /// `with_capacity`.  A `BytesMut` constructed this way will always store
692    /// its data on the heap.
693    fn from(src: Vec<u8>) -> BytesMut {
694        BytesMut::from_vec(src)
695    }
696}
697
698impl From<String> for BytesMut {
699    #[inline]
700    fn from(src: String) -> BytesMut {
701        BytesMut::from_vec(src.into_bytes())
702    }
703}
704
705impl From<&BytesMut> for BytesMut {
706    #[inline]
707    fn from(src: &BytesMut) -> BytesMut {
708        src.clone()
709    }
710}
711
712impl<'a> From<&'a [u8]> for BytesMut {
713    fn from(src: &'a [u8]) -> BytesMut {
714        if src.is_empty() {
715            BytesMut::new()
716        } else {
717            BytesMut::copy_from_slice(src)
718        }
719    }
720}
721
722impl<const N: usize> From<[u8; N]> for BytesMut {
723    fn from(src: [u8; N]) -> BytesMut {
724        BytesMut::copy_from_slice(src)
725    }
726}
727
728impl<'a, const N: usize> From<&'a [u8; N]> for BytesMut {
729    fn from(src: &'a [u8; N]) -> BytesMut {
730        BytesMut::copy_from_slice(src)
731    }
732}
733
734impl<'a> From<&'a str> for BytesMut {
735    #[inline]
736    fn from(src: &'a str) -> BytesMut {
737        BytesMut::from(src.as_bytes())
738    }
739}
740
741impl From<Bytes> for BytesMut {
742    #[inline]
743    fn from(src: Bytes) -> BytesMut {
744        src.try_mut()
745            .unwrap_or_else(|src| BytesMut::copy_from_slice(&src[..]))
746    }
747}
748
749impl From<&Bytes> for BytesMut {
750    #[inline]
751    fn from(src: &Bytes) -> BytesMut {
752        BytesMut::copy_from_slice(&src[..])
753    }
754}
755
756impl Eq for BytesMut {}
757
758impl PartialEq for BytesMut {
759    #[inline]
760    fn eq(&self, other: &BytesMut) -> bool {
761        self.storage.as_ref() == other.storage.as_ref()
762    }
763}
764
765impl Default for BytesMut {
766    #[inline]
767    fn default() -> BytesMut {
768        BytesMut::new()
769    }
770}
771
772impl borrow::Borrow<[u8]> for BytesMut {
773    #[inline]
774    fn borrow(&self) -> &[u8] {
775        self.as_ref()
776    }
777}
778
779impl borrow::BorrowMut<[u8]> for BytesMut {
780    #[inline]
781    fn borrow_mut(&mut self) -> &mut [u8] {
782        self.as_mut()
783    }
784}
785
786impl fmt::Debug for BytesMut {
787    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
788        fmt::Debug::fmt(&debug::BsDebug(self.storage.as_ref()), fmt)
789    }
790}
791
792impl fmt::Write for BytesMut {
793    #[inline]
794    fn write_str(&mut self, s: &str) -> fmt::Result {
795        if self.remaining_mut() >= s.len() {
796            self.put_slice(s.as_bytes());
797            Ok(())
798        } else {
799            Err(fmt::Error)
800        }
801    }
802
803    #[inline]
804    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
805        fmt::write(self, args)
806    }
807}
808
809impl Clone for BytesMut {
810    #[inline]
811    fn clone(&self) -> BytesMut {
812        BytesMut::from(&self[..])
813    }
814}
815
816impl IntoIterator for BytesMut {
817    type Item = u8;
818    type IntoIter = IntoIter<BytesMut>;
819
820    fn into_iter(self) -> Self::IntoIter {
821        IntoIter::new(self)
822    }
823}
824
825impl<'a> IntoIterator for &'a BytesMut {
826    type Item = &'a u8;
827    type IntoIter = std::slice::Iter<'a, u8>;
828
829    fn into_iter(self) -> Self::IntoIter {
830        self.as_ref().iter()
831    }
832}
833
834impl FromIterator<u8> for BytesMut {
835    fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
836        let iter = into_iter.into_iter();
837        let (min, maybe_max) = iter.size_hint();
838
839        let mut out = BytesMut::with_capacity(maybe_max.unwrap_or(min));
840        for i in iter {
841            out.reserve(1);
842            out.put_u8(i);
843        }
844
845        out
846    }
847}
848
849impl<'a> FromIterator<&'a u8> for BytesMut {
850    fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
851        into_iter.into_iter().copied().collect::<BytesMut>()
852    }
853}
854
855impl Extend<u8> for BytesMut {
856    fn extend<T>(&mut self, iter: T)
857    where
858        T: IntoIterator<Item = u8>,
859    {
860        let iter = iter.into_iter();
861
862        let (lower, _) = iter.size_hint();
863        self.reserve(lower);
864
865        for b in iter {
866            self.put_u8(b);
867        }
868    }
869}
870
871impl<'a> Extend<&'a u8> for BytesMut {
872    fn extend<T>(&mut self, iter: T)
873    where
874        T: IntoIterator<Item = &'a u8>,
875    {
876        self.extend(iter.into_iter().copied())
877    }
878}
879
880/*
881 *
882 * ===== PartialEq / PartialOrd =====
883 *
884 */
885
886impl PartialEq<[u8]> for BytesMut {
887    fn eq(&self, other: &[u8]) -> bool {
888        &**self == other
889    }
890}
891
892impl<const N: usize> PartialEq<[u8; N]> for BytesMut {
893    fn eq(&self, other: &[u8; N]) -> bool {
894        &**self == other
895    }
896}
897
898impl PartialEq<BytesMut> for [u8] {
899    fn eq(&self, other: &BytesMut) -> bool {
900        *other == *self
901    }
902}
903
904impl<const N: usize> PartialEq<BytesMut> for [u8; N] {
905    fn eq(&self, other: &BytesMut) -> bool {
906        *other == *self
907    }
908}
909
910impl<const N: usize> PartialEq<BytesMut> for &[u8; N] {
911    fn eq(&self, other: &BytesMut) -> bool {
912        *other == *self
913    }
914}
915
916impl PartialEq<str> for BytesMut {
917    fn eq(&self, other: &str) -> bool {
918        &**self == other.as_bytes()
919    }
920}
921
922impl PartialEq<BytesMut> for str {
923    fn eq(&self, other: &BytesMut) -> bool {
924        *other == *self
925    }
926}
927
928impl PartialEq<Vec<u8>> for BytesMut {
929    fn eq(&self, other: &Vec<u8>) -> bool {
930        *self == other[..]
931    }
932}
933
934impl PartialEq<BytesMut> for Vec<u8> {
935    fn eq(&self, other: &BytesMut) -> bool {
936        *other == *self
937    }
938}
939
940impl PartialEq<String> for BytesMut {
941    fn eq(&self, other: &String) -> bool {
942        *self == other[..]
943    }
944}
945
946impl PartialEq<BytesMut> for String {
947    fn eq(&self, other: &BytesMut) -> bool {
948        *other == *self
949    }
950}
951
952impl<'a, T: ?Sized> PartialEq<&'a T> for BytesMut
953where
954    BytesMut: PartialEq<T>,
955{
956    fn eq(&self, other: &&'a T) -> bool {
957        *self == **other
958    }
959}
960
961impl PartialEq<BytesMut> for &[u8] {
962    fn eq(&self, other: &BytesMut) -> bool {
963        *other == *self
964    }
965}
966
967impl PartialEq<BytesMut> for &str {
968    fn eq(&self, other: &BytesMut) -> bool {
969        *other == *self
970    }
971}
972
973impl PartialEq<Bytes> for BytesMut {
974    fn eq(&self, other: &Bytes) -> bool {
975        other[..] == self[..]
976    }
977}