ntex_bytes/
bytesmut.rs

1use std::{borrow, fmt, ops, ptr};
2
3use crate::{buf::IntoIter, buf::UninitSlice, debug, storage::Storage, Buf, BufMut, Bytes};
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) inner: 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            inner: 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            inner: 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            inner: 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            inner: 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.inner.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.inner.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.inner.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            inner: self.inner.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            inner: self.inner.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                inner: self.inner.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.inner.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.inner.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.inner.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.inner.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
523impl Buf for BytesMut {
524    #[inline]
525    fn remaining(&self) -> usize {
526        self.len()
527    }
528
529    #[inline]
530    fn chunk(&self) -> &[u8] {
531        self.inner.as_ref()
532    }
533
534    #[inline]
535    fn advance(&mut self, cnt: usize) {
536        assert!(cnt <= self.inner.len(), "cannot advance past `remaining`");
537        unsafe {
538            self.inner.set_start(cnt);
539        }
540    }
541}
542
543impl BufMut for BytesMut {
544    #[inline]
545    fn remaining_mut(&self) -> usize {
546        self.capacity() - self.len()
547    }
548
549    #[inline]
550    unsafe fn advance_mut(&mut self, cnt: usize) {
551        let new_len = self.len() + cnt;
552
553        // This call will panic if `cnt` is too big
554        self.inner.set_len(new_len);
555    }
556
557    #[inline]
558    fn chunk_mut(&mut self) -> &mut UninitSlice {
559        let len = self.len();
560
561        unsafe {
562            // This will never panic as `len` can never become invalid
563            let ptr = &mut self.inner.as_raw()[len..];
564
565            UninitSlice::from_raw_parts_mut(ptr.as_mut_ptr(), self.capacity() - len)
566        }
567    }
568
569    #[inline]
570    fn put_slice(&mut self, src: &[u8]) {
571        let len = src.len();
572        self.reserve(len);
573
574        unsafe {
575            ptr::copy_nonoverlapping(src.as_ptr(), self.chunk_mut().as_mut_ptr(), len);
576            self.advance_mut(len);
577        }
578    }
579
580    #[inline]
581    fn put_u8(&mut self, n: u8) {
582        self.reserve(1);
583        self.inner.put_u8(n);
584    }
585
586    #[inline]
587    fn put_i8(&mut self, n: i8) {
588        self.reserve(1);
589        self.put_u8(n as u8);
590    }
591}
592
593impl bytes::buf::Buf for BytesMut {
594    #[inline]
595    fn remaining(&self) -> usize {
596        self.len()
597    }
598
599    #[inline]
600    fn chunk(&self) -> &[u8] {
601        self.inner.as_ref()
602    }
603
604    #[inline]
605    fn advance(&mut self, cnt: usize) {
606        Buf::advance(self, cnt)
607    }
608}
609
610unsafe impl bytes::buf::BufMut for BytesMut {
611    #[inline]
612    fn remaining_mut(&self) -> usize {
613        BufMut::remaining_mut(self)
614    }
615
616    #[inline]
617    unsafe fn advance_mut(&mut self, cnt: usize) {
618        BufMut::advance_mut(self, cnt)
619    }
620
621    #[inline]
622    fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
623        let len = self.len();
624        unsafe {
625            // This will never panic as `len` can never become invalid
626            let ptr = &mut self.inner.as_raw()[len..];
627            bytes::buf::UninitSlice::from_raw_parts_mut(
628                ptr.as_mut_ptr(),
629                self.capacity() - len,
630            )
631        }
632    }
633
634    #[inline]
635    fn put_slice(&mut self, src: &[u8]) {
636        BufMut::put_slice(self, src)
637    }
638
639    #[inline]
640    fn put_u8(&mut self, n: u8) {
641        BufMut::put_u8(self, n)
642    }
643
644    #[inline]
645    fn put_i8(&mut self, n: i8) {
646        BufMut::put_i8(self, n)
647    }
648}
649
650impl AsRef<[u8]> for BytesMut {
651    #[inline]
652    fn as_ref(&self) -> &[u8] {
653        self.inner.as_ref()
654    }
655}
656
657impl AsMut<[u8]> for BytesMut {
658    #[inline]
659    fn as_mut(&mut self) -> &mut [u8] {
660        self.inner.as_mut()
661    }
662}
663
664impl ops::Deref for BytesMut {
665    type Target = [u8];
666
667    #[inline]
668    fn deref(&self) -> &[u8] {
669        self.as_ref()
670    }
671}
672
673impl ops::DerefMut for BytesMut {
674    #[inline]
675    fn deref_mut(&mut self) -> &mut [u8] {
676        self.inner.as_mut()
677    }
678}
679
680impl From<Vec<u8>> for BytesMut {
681    #[inline]
682    /// Convert a `Vec` into a `BytesMut`
683    ///
684    /// This constructor may be used to avoid the inlining optimization used by
685    /// `with_capacity`.  A `BytesMut` constructed this way will always store
686    /// its data on the heap.
687    fn from(src: Vec<u8>) -> BytesMut {
688        BytesMut::from_vec(src)
689    }
690}
691
692impl From<String> for BytesMut {
693    #[inline]
694    fn from(src: String) -> BytesMut {
695        BytesMut::from_vec(src.into_bytes())
696    }
697}
698
699impl From<&BytesMut> for BytesMut {
700    #[inline]
701    fn from(src: &BytesMut) -> BytesMut {
702        src.clone()
703    }
704}
705
706impl<'a> From<&'a [u8]> for BytesMut {
707    fn from(src: &'a [u8]) -> BytesMut {
708        if src.is_empty() {
709            BytesMut::new()
710        } else {
711            BytesMut::copy_from_slice(src)
712        }
713    }
714}
715
716impl<const N: usize> From<[u8; N]> for BytesMut {
717    fn from(src: [u8; N]) -> BytesMut {
718        BytesMut::copy_from_slice(src)
719    }
720}
721
722impl<'a, const N: usize> From<&'a [u8; N]> for BytesMut {
723    fn from(src: &'a [u8; N]) -> BytesMut {
724        BytesMut::copy_from_slice(src)
725    }
726}
727
728impl<'a> From<&'a str> for BytesMut {
729    #[inline]
730    fn from(src: &'a str) -> BytesMut {
731        BytesMut::from(src.as_bytes())
732    }
733}
734
735impl From<Bytes> for BytesMut {
736    #[inline]
737    fn from(src: Bytes) -> BytesMut {
738        src.try_mut()
739            .unwrap_or_else(|src| BytesMut::copy_from_slice(&src[..]))
740    }
741}
742
743impl From<&Bytes> for BytesMut {
744    #[inline]
745    fn from(src: &Bytes) -> BytesMut {
746        BytesMut::copy_from_slice(&src[..])
747    }
748}
749
750impl Eq for BytesMut {}
751
752impl PartialEq for BytesMut {
753    #[inline]
754    fn eq(&self, other: &BytesMut) -> bool {
755        self.inner.as_ref() == other.inner.as_ref()
756    }
757}
758
759impl Default for BytesMut {
760    #[inline]
761    fn default() -> BytesMut {
762        BytesMut::new()
763    }
764}
765
766impl borrow::Borrow<[u8]> for BytesMut {
767    #[inline]
768    fn borrow(&self) -> &[u8] {
769        self.as_ref()
770    }
771}
772
773impl borrow::BorrowMut<[u8]> for BytesMut {
774    #[inline]
775    fn borrow_mut(&mut self) -> &mut [u8] {
776        self.as_mut()
777    }
778}
779
780impl fmt::Debug for BytesMut {
781    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
782        fmt::Debug::fmt(&debug::BsDebug(self.inner.as_ref()), fmt)
783    }
784}
785
786impl fmt::Write for BytesMut {
787    #[inline]
788    fn write_str(&mut self, s: &str) -> fmt::Result {
789        if self.remaining_mut() >= s.len() {
790            self.put_slice(s.as_bytes());
791            Ok(())
792        } else {
793            Err(fmt::Error)
794        }
795    }
796
797    #[inline]
798    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
799        fmt::write(self, args)
800    }
801}
802
803impl Clone for BytesMut {
804    #[inline]
805    fn clone(&self) -> BytesMut {
806        BytesMut::from(&self[..])
807    }
808}
809
810impl IntoIterator for BytesMut {
811    type Item = u8;
812    type IntoIter = IntoIter<BytesMut>;
813
814    fn into_iter(self) -> Self::IntoIter {
815        IntoIter::new(self)
816    }
817}
818
819impl<'a> IntoIterator for &'a BytesMut {
820    type Item = &'a u8;
821    type IntoIter = std::slice::Iter<'a, u8>;
822
823    fn into_iter(self) -> Self::IntoIter {
824        self.as_ref().iter()
825    }
826}
827
828impl FromIterator<u8> for BytesMut {
829    fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
830        let iter = into_iter.into_iter();
831        let (min, maybe_max) = iter.size_hint();
832
833        let mut out = BytesMut::with_capacity(maybe_max.unwrap_or(min));
834        for i in iter {
835            out.reserve(1);
836            out.put_u8(i);
837        }
838
839        out
840    }
841}
842
843impl<'a> FromIterator<&'a u8> for BytesMut {
844    fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
845        into_iter.into_iter().copied().collect::<BytesMut>()
846    }
847}
848
849impl Extend<u8> for BytesMut {
850    fn extend<T>(&mut self, iter: T)
851    where
852        T: IntoIterator<Item = u8>,
853    {
854        let iter = iter.into_iter();
855
856        let (lower, _) = iter.size_hint();
857        self.reserve(lower);
858
859        for b in iter {
860            self.put_u8(b);
861        }
862    }
863}
864
865impl<'a> Extend<&'a u8> for BytesMut {
866    fn extend<T>(&mut self, iter: T)
867    where
868        T: IntoIterator<Item = &'a u8>,
869    {
870        self.extend(iter.into_iter().copied())
871    }
872}
873
874/*
875 *
876 * ===== PartialEq / PartialOrd =====
877 *
878 */
879
880impl PartialEq<[u8]> for BytesMut {
881    fn eq(&self, other: &[u8]) -> bool {
882        &**self == other
883    }
884}
885
886impl<const N: usize> PartialEq<[u8; N]> for BytesMut {
887    fn eq(&self, other: &[u8; N]) -> bool {
888        &**self == other
889    }
890}
891
892impl PartialEq<BytesMut> for [u8] {
893    fn eq(&self, other: &BytesMut) -> bool {
894        *other == *self
895    }
896}
897
898impl<const N: usize> PartialEq<BytesMut> for [u8; N] {
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 PartialEq<str> for BytesMut {
911    fn eq(&self, other: &str) -> bool {
912        &**self == other.as_bytes()
913    }
914}
915
916impl PartialEq<BytesMut> for str {
917    fn eq(&self, other: &BytesMut) -> bool {
918        *other == *self
919    }
920}
921
922impl PartialEq<Vec<u8>> for BytesMut {
923    fn eq(&self, other: &Vec<u8>) -> bool {
924        *self == other[..]
925    }
926}
927
928impl PartialEq<BytesMut> for Vec<u8> {
929    fn eq(&self, other: &BytesMut) -> bool {
930        *other == *self
931    }
932}
933
934impl PartialEq<String> for BytesMut {
935    fn eq(&self, other: &String) -> bool {
936        *self == other[..]
937    }
938}
939
940impl PartialEq<BytesMut> for String {
941    fn eq(&self, other: &BytesMut) -> bool {
942        *other == *self
943    }
944}
945
946impl<'a, T: ?Sized> PartialEq<&'a T> for BytesMut
947where
948    BytesMut: PartialEq<T>,
949{
950    fn eq(&self, other: &&'a T) -> bool {
951        *self == **other
952    }
953}
954
955impl PartialEq<BytesMut> for &[u8] {
956    fn eq(&self, other: &BytesMut) -> bool {
957        *other == *self
958    }
959}
960
961impl PartialEq<BytesMut> for &str {
962    fn eq(&self, other: &BytesMut) -> bool {
963        *other == *self
964    }
965}
966
967impl PartialEq<Bytes> for BytesMut {
968    fn eq(&self, other: &Bytes) -> bool {
969        other[..] == self[..]
970    }
971}