Skip to main content

ntex_bytes/
bvec.rs

1use std::{borrow, fmt, io, ops::DerefMut, ptr};
2
3use crate::{Buf, BufMut, Bytes, buf::UninitSlice, stvec::StorageVec};
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 fewer copies and
10/// allocations. It also always allocates.
11///
12/// For more detail, see [`Bytes`].
13///
14/// # Growth
15///
16/// Safe write operations such as [`BufMut::put_slice`], [`BufMut::put_u8`], and
17/// [`extend_from_slice`](Self::extend_from_slice) reserve additional capacity
18/// when needed. Use [`reserve`](Self::reserve) when the required capacity is
19/// known in advance to avoid repeated allocation.
20///
21/// # Examples
22///
23/// ```
24/// use ntex_bytes::{BytesMut, BufMut};
25///
26/// let mut buf = BytesMut::with_capacity(64);
27///
28/// buf.put_u8(b'h');
29/// buf.put_u8(b'e');
30/// buf.put("llo");
31///
32/// assert_eq!(&buf[..], b"hello");
33///
34/// // Freeze the buffer so that it can be shared
35/// let a = buf.freeze();
36///
37/// // This does not allocate, instead `b` points to the same memory.
38/// let b = a.clone();
39///
40/// assert_eq!(a, b"hello");
41/// assert_eq!(b, b"hello");
42/// ```
43pub struct BytesMut {
44    pub(crate) storage: StorageVec,
45}
46
47impl BytesMut {
48    /// Creates a new `BytesMut` with the specified capacity.
49    ///
50    /// The returned `BytesMut` will be able to hold `capacity` bytes
51    /// without reallocating.
52    ///
53    /// It is important to note that this function does not specify the length
54    /// of the returned `BytesMut`, but only the capacity.
55    ///
56    /// # Panics
57    ///
58    /// Panics if `capacity` exceeds `u32::MAX` minus the buffer
59    /// header size, just under 4 GiB.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use ntex_bytes::{BytesMut, BufMut};
65    ///
66    /// let mut bytes = BytesMut::with_capacity(64);
67    ///
68    /// // `bytes` contains no data, even though there is capacity
69    /// assert_eq!(bytes.len(), 0);
70    ///
71    /// bytes.put(&b"hello world"[..]);
72    ///
73    /// assert_eq!(&bytes[..], b"hello world");
74    /// ```
75    #[inline]
76    #[must_use]
77    pub fn with_capacity(capacity: usize) -> BytesMut {
78        BytesMut {
79            storage: StorageVec::with_capacity(capacity),
80        }
81    }
82
83    /// Creates a `BytesMut` by copying a byte slice.
84    #[inline]
85    #[must_use]
86    pub fn copy_from_slice<T: AsRef<[u8]>>(src: T) -> Self {
87        let slice = src.as_ref();
88        BytesMut {
89            storage: StorageVec::from_slice(slice.len(), slice),
90        }
91    }
92
93    /// Creates a new `BytesMut` with default capacity.
94    ///
95    /// Resulting object has length 0 and unspecified capacity.
96    ///
97    /// # Examples
98    ///
99    /// ```
100    /// use ntex_bytes::{BytesMut, BufMut};
101    ///
102    /// let mut bytes = BytesMut::new();
103    ///
104    /// assert_eq!(0, bytes.len());
105    ///
106    /// bytes.reserve(2);
107    /// bytes.put_slice(b"xy");
108    ///
109    /// assert_eq!(&b"xy"[..], &bytes[..]);
110    /// ```
111    #[inline]
112    #[must_use]
113    pub fn new() -> BytesMut {
114        BytesMut {
115            storage: StorageVec::with_capacity(crate::storage::MIN_CAPACITY),
116        }
117    }
118
119    /// Returns the number of bytes contained in this `BytesMut`.
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use ntex_bytes::BytesMut;
125    ///
126    /// let b = BytesMut::copy_from_slice(&b"hello"[..]);
127    /// assert_eq!(b.len(), 5);
128    /// ```
129    #[inline]
130    pub fn len(&self) -> usize {
131        self.storage.len()
132    }
133
134    /// Returns `true` if the buffer is empty.
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// use ntex_bytes::BytesMut;
140    ///
141    /// let b = BytesMut::with_capacity(64);
142    /// assert!(b.is_empty());
143    /// ```
144    #[inline]
145    pub fn is_empty(&self) -> bool {
146        self.storage.len() == 0
147    }
148
149    /// Returns the number of bytes the `BytesMut` can hold without reallocating.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use ntex_bytes::BytesMut;
155    ///
156    /// let b = BytesMut::with_capacity(64);
157    /// assert_eq!(b.capacity(), 64);
158    /// ```
159    #[inline]
160    pub fn capacity(&self) -> usize {
161        self.storage.capacity()
162    }
163
164    /// Returns `true` if no other handle refers to the underlying buffer.
165    ///
166    /// Values split off with [`split_to`](Self::split_to) or frozen into
167    /// [`Bytes`] share the buffer with `self`. While they exist, clearing
168    /// `self` does not reclaim the capacity in front of it, and the whole
169    /// allocation stays alive as long as any of them does.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use ntex_bytes::BytesMut;
175    ///
176    /// let mut buf = BytesMut::with_capacity(64);
177    /// buf.extend_from_slice(&[0; 32]);
178    /// assert!(buf.is_unique());
179    ///
180    /// let head = buf.split_to(30);
181    /// assert!(!buf.is_unique());
182    ///
183    /// drop(head);
184    /// assert!(buf.is_unique());
185    /// ```
186    #[inline]
187    pub fn is_unique(&self) -> bool {
188        self.storage.is_unique()
189    }
190
191    /// Converts `self` into an immutable `Bytes`.
192    ///
193    /// The conversion is zero cost and is used to indicate that the slice
194    /// referenced by the handle will no longer be mutated. Once the conversion
195    /// is done, the handle can be cloned and shared across threads.
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// use ntex_bytes::{BytesMut, BufMut};
201    /// use std::thread;
202    ///
203    /// let mut b = BytesMut::with_capacity(64);
204    /// b.put("hello world");
205    /// let b1 = b.freeze();
206    /// let b2 = b1.clone();
207    ///
208    /// let th = thread::spawn(move || {
209    ///     assert_eq!(b1, b"hello world");
210    /// });
211    ///
212    /// assert_eq!(b2, b"hello world");
213    /// th.join().unwrap();
214    /// ```
215    #[inline]
216    #[must_use]
217    pub fn freeze(self) -> Bytes {
218        Bytes {
219            storage: self.storage.freeze(),
220        }
221    }
222
223    /// Removes the bytes from the current view, returning them in a
224    /// `Bytes` instance.
225    ///
226    /// Afterwards, `self` will be empty, but will retain any additional
227    /// capacity that it had before the operation. This is identical to
228    /// `self.split_to(self.len())`.
229    ///
230    /// This is an `O(1)` operation that just increases the reference count and
231    /// sets a few indices.
232    ///
233    /// # Examples
234    ///
235    /// ```
236    /// use ntex_bytes::{BytesMut, BufMut};
237    ///
238    /// let mut buf = BytesMut::with_capacity(1024);
239    /// buf.put(&b"hello world"[..]);
240    ///
241    /// let other = buf.take();
242    ///
243    /// assert!(buf.is_empty());
244    /// assert_eq!(1013, buf.capacity());
245    ///
246    /// assert_eq!(other, b"hello world"[..]);
247    /// ```
248    #[inline]
249    #[must_use]
250    pub fn take(&mut self) -> Bytes {
251        Bytes {
252            storage: self.storage.split_to(self.len()),
253        }
254    }
255
256    /// Splits the buffer into two at the given index.
257    ///
258    /// Afterwards `self` contains elements `[at, len)`, and the returned `Bytes`
259    /// contains elements `[0, at)`.
260    ///
261    /// This is an `O(1)` operation that just increases the reference count and
262    /// sets a few indices.
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// use ntex_bytes::BytesMut;
268    ///
269    /// let mut a = BytesMut::copy_from_slice(&b"hello world"[..]);
270    /// let mut b = a.split_to(5);
271    ///
272    /// a[0] = b'!';
273    ///
274    /// assert_eq!(&a[..], b"!world");
275    /// assert_eq!(&b[..], b"hello");
276    /// ```
277    ///
278    /// # Panics
279    ///
280    /// Panics if `at > len`.
281    #[inline]
282    #[must_use]
283    pub fn split_to(&mut self, at: usize) -> Bytes {
284        self.split_to_checked(at)
285            .expect("at value must be <= self.len()`")
286    }
287
288    /// Advance the internal cursor.
289    ///
290    /// Afterwards `self` contains elements `[cnt, len)`.
291    /// This is an `O(1)` operation.
292    ///
293    /// # Examples
294    ///
295    /// ```
296    /// use ntex_bytes::BytesMut;
297    ///
298    /// let mut a = BytesMut::copy_from_slice(&b"hello world"[..]);
299    /// a.advance_to(5);
300    ///
301    /// a[0] = b'!';
302    ///
303    /// assert_eq!(&a[..], b"!world");
304    /// ```
305    ///
306    /// # Panics
307    ///
308    /// Panics if `cnt > len`.
309    #[inline]
310    pub fn advance_to(&mut self, cnt: usize) {
311        unsafe {
312            self.storage.set_start(cnt);
313        }
314    }
315
316    /// Splits the bytes into two at the given index.
317    ///
318    /// Returns `None` if `at > len`.
319    #[inline]
320    #[must_use]
321    pub fn split_to_checked(&mut self, at: usize) -> Option<Bytes> {
322        if at <= self.len() {
323            Some(Bytes {
324                storage: self.storage.split_to(at),
325            })
326        } else {
327            None
328        }
329    }
330
331    /// Shortens the buffer, keeping the first `len` bytes and dropping the
332    /// rest.
333    ///
334    /// If `len` is greater than the buffer's current length, this has no
335    /// effect.
336    ///
337    /// `truncate(0)` on a buffer that is not shared with any other handle
338    /// also reclaims the capacity in front of the current view, see
339    /// [`clear`](Self::clear).
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use ntex_bytes::BytesMut;
345    ///
346    /// let mut buf = BytesMut::copy_from_slice(&b"hello world"[..]);
347    /// buf.truncate(5);
348    /// assert_eq!(buf, b"hello"[..]);
349    /// ```
350    #[inline]
351    pub fn truncate(&mut self, len: usize) {
352        self.storage.truncate(len);
353    }
354
355    /// Clears the buffer, removing all data.
356    ///
357    /// If no other handle refers to the underlying buffer (see
358    /// [`is_unique`](Self::is_unique)), the view is reset to the start of the
359    /// allocation, so the full capacity becomes available again.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// use ntex_bytes::BytesMut;
365    ///
366    /// let mut buf = BytesMut::copy_from_slice(&b"hello world"[..]);
367    /// buf.clear();
368    /// assert!(buf.is_empty());
369    /// ```
370    #[inline]
371    pub fn clear(&mut self) {
372        self.truncate(0);
373    }
374
375    /// Resizes the buffer so that `len` is equal to `new_len`.
376    ///
377    /// If `new_len` is greater than `len`, the buffer is extended by the
378    /// difference with each additional byte set to `value`. If `new_len` is
379    /// less than `len`, the buffer is simply truncated.
380    ///
381    /// # Panics
382    ///
383    /// Panics if `new_len` exceeds `u32::MAX` minus the buffer
384    /// header size, just under 4 GiB.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use ntex_bytes::BytesMut;
390    ///
391    /// let mut buf = BytesMut::new();
392    ///
393    /// buf.resize(3, 0x1);
394    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
395    ///
396    /// buf.resize(2, 0x2);
397    /// assert_eq!(&buf[..], &[0x1, 0x1]);
398    ///
399    /// buf.resize(4, 0x3);
400    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
401    /// ```
402    #[inline]
403    pub fn resize(&mut self, new_len: usize, value: u8) {
404        self.storage.resize(new_len, value);
405    }
406
407    /// Sets the length of the buffer.
408    ///
409    /// This will explicitly set the size of the buffer without actually
410    /// modifying the data, so it is up to the caller to ensure that the data
411    /// has been initialized.
412    ///
413    /// # Examples
414    ///
415    /// ```
416    /// use ntex_bytes::BytesMut;
417    ///
418    /// let mut b = BytesMut::copy_from_slice(&b"hello world"[..]);
419    ///
420    /// unsafe {
421    ///     b.set_len(5);
422    /// }
423    ///
424    /// assert_eq!(&b[..], b"hello");
425    ///
426    /// unsafe {
427    ///     b.set_len(11);
428    /// }
429    ///
430    /// assert_eq!(&b[..], b"hello world");
431    /// ```
432    ///
433    /// # Safety
434    ///
435    /// Caller must ensure that data has been initialized.
436    ///
437    /// # Panics
438    ///
439    /// Panics if `len > self.capacity()`.
440    #[inline]
441    pub unsafe fn set_len(&mut self, len: usize) {
442        self.storage.set_len(len);
443    }
444
445    /// Reserves capacity for at least `additional` more bytes to be inserted
446    /// into the given `BytesMut`.
447    ///
448    /// Before allocating new buffer space, the function will attempt to reclaim
449    /// space in the existing buffer. If the current handle references a small
450    /// view in the original buffer and all other handles have been dropped,
451    /// and the requested capacity is less than or equal to the existing
452    /// buffer's capacity, then the current view will be copied to the front of
453    /// the buffer and the handle will take ownership of the full buffer.
454    ///
455    /// Otherwise a unique buffer that is not a pooled page is reallocated,
456    /// often in place, and a new buffer is allocated in all other cases. The
457    /// new capacity is at least twice the current length, so appending in
458    /// small steps reallocates a logarithmic number of times. Use [`reserve_capacity`](Self::reserve_capacity) to
459    /// allocate an exact capacity.
460    ///
461    /// # Panics
462    ///
463    /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
464    /// header size, just under 4 GiB.
465    ///
466    /// # Examples
467    ///
468    /// In the following example, a new buffer is allocated.
469    ///
470    /// ```
471    /// use ntex_bytes::BytesMut;
472    ///
473    /// let mut buf = BytesMut::copy_from_slice(&b"hello"[..]);
474    /// buf.reserve(64);
475    /// assert!(buf.capacity() >= 69);
476    /// ```
477    ///
478    /// In the following example, the existing buffer is reclaimed.
479    ///
480    /// ```
481    /// use ntex_bytes::{BytesMut, BufMut};
482    ///
483    /// let mut buf = BytesMut::with_capacity(128);
484    /// buf.put(&[0; 64][..]);
485    ///
486    /// let ptr = buf.as_ptr();
487    /// let other = buf.take();
488    ///
489    /// assert!(buf.is_empty());
490    /// assert_eq!(buf.capacity(), 64);
491    ///
492    /// drop(other);
493    /// buf.reserve(128);
494    ///
495    /// assert_eq!(buf.capacity(), 128);
496    /// assert_eq!(buf.as_ptr(), ptr);
497    /// ```
498    #[inline]
499    pub fn reserve(&mut self, additional: usize) {
500        self.storage.reserve(additional);
501    }
502
503    /// Reserves capacity for exactly `additional` more bytes to be inserted
504    /// into the given `BytesMut`.
505    ///
506    /// Behaves like [`reserve`](Self::reserve), it reclaims the existing buffer
507    /// when possible and reallocates a unique buffer that is not a pooled page,
508    /// but a new allocation is sized to hold exactly `additional` more bytes
509    /// instead of growing to at least twice the current length. Unlike
510    /// [`reserve_capacity`](Self::reserve_capacity), the contents are not moved
511    /// when the buffer already has enough remaining capacity.
512    ///
513    /// # Panics
514    ///
515    /// Panics if the new capacity exceeds `u32::MAX` minus the buffer
516    /// header size, just under 4 GiB.
517    ///
518    /// # Examples
519    ///
520    /// ```
521    /// use ntex_bytes::BytesMut;
522    ///
523    /// let mut buf = BytesMut::copy_from_slice(&[0; 1000][..]);
524    /// buf.reserve_exact(24);
525    /// assert_eq!(buf.capacity(), 1024);
526    ///
527    /// // enough remaining capacity keeps the current buffer
528    /// let ptr = buf.as_ptr();
529    /// buf.reserve_exact(24);
530    /// assert_eq!(buf.as_ptr(), ptr);
531    /// ```
532    #[inline]
533    pub fn reserve_exact(&mut self, additional: usize) {
534        self.storage.reserve_exact(additional);
535    }
536
537    /// Moves the contents into a newly allocated buffer with capacity `cap`.
538    ///
539    /// If `cap` is greater than [`len`](Self::len), a new buffer is allocated,
540    /// the current contents are copied into it, and afterwards
541    /// [`capacity`](Self::capacity) is at least `cap`. The new buffer is not
542    /// shared with any [`Bytes`] previously split off this `BytesMut`.
543    ///
544    /// If `cap` is less than or equal to `len`, this method does nothing: the
545    /// contents are neither reallocated nor truncated.
546    ///
547    /// Unlike [`reserve`](Self::reserve), this always allocates when
548    /// `cap > len`, even if the current buffer is already large enough.
549    ///
550    /// # Panics
551    ///
552    /// Panics if `cap` exceeds `u32::MAX` minus the buffer
553    /// header size, just under 4 GiB.
554    ///
555    /// # Examples
556    ///
557    /// ```
558    /// use ntex_bytes::BytesMut;
559    ///
560    /// let mut buf = BytesMut::copy_from_slice(&b"hello"[..]);
561    /// buf.reserve_capacity(128);
562    /// assert!(buf.capacity() >= 128);
563    /// assert_eq!(&buf[..], b"hello");
564    ///
565    /// // `cap <= len` keeps the current buffer
566    /// let ptr = buf.as_ptr();
567    /// buf.reserve_capacity(2);
568    /// assert_eq!(buf.as_ptr(), ptr);
569    /// assert_eq!(&buf[..], b"hello");
570    /// ```
571    #[inline]
572    pub fn reserve_capacity(&mut self, cap: usize) {
573        self.storage.reserve_capacity(cap);
574    }
575
576    /// Appends a byte slice to the buffer.
577    ///
578    /// Additional capacity is reserved automatically when needed.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use ntex_bytes::BytesMut;
584    ///
585    /// let mut buf = BytesMut::with_capacity(0);
586    /// buf.extend_from_slice(b"aaabbb");
587    /// buf.extend_from_slice(b"cccddd");
588    ///
589    /// assert_eq!(b"aaabbbcccddd", &buf[..]);
590    /// ```
591    #[inline]
592    pub fn extend_from_slice(&mut self, extend: &[u8]) {
593        self.put_slice(extend);
594    }
595
596    /// Returns an iterator over the bytes contained by the buffer.
597    ///
598    /// # Examples
599    ///
600    /// ```
601    /// use ntex_bytes::{Buf, BytesMut};
602    ///
603    /// let buf = BytesMut::copy_from_slice(&b"abc"[..]);
604    /// let mut iter = buf.iter();
605    ///
606    /// assert_eq!(iter.next().map(|b| *b), Some(b'a'));
607    /// assert_eq!(iter.next().map(|b| *b), Some(b'b'));
608    /// assert_eq!(iter.next().map(|b| *b), Some(b'c'));
609    /// assert_eq!(iter.next(), None);
610    /// ```
611    #[inline]
612    pub fn iter(&'_ self) -> std::slice::Iter<'_, u8> {
613        self.chunk().iter()
614    }
615}
616
617impl_buf!(BytesMut {});
618
619impl_slice_traits!(BytesMut);
620
621impl_partial_eq!(BytesMut);
622
623impl BufMut for BytesMut {
624    #[inline]
625    fn remaining_mut(&self) -> usize {
626        self.storage.remaining()
627    }
628
629    #[inline]
630    unsafe fn advance_mut(&mut self, cnt: usize) {
631        // This call will panic if `cnt` is too big
632        self.storage.set_len(self.len() + cnt);
633    }
634
635    #[inline]
636    fn chunk_mut(&mut self) -> &mut UninitSlice {
637        self.storage.spare_mut()
638    }
639
640    #[inline]
641    fn put<T: Buf>(&mut self, mut src: T)
642    where
643        Self: Sized,
644    {
645        self.reserve(src.remaining());
646        while src.has_remaining() {
647            let chunk = src.chunk();
648            let len = chunk.len();
649            self.put_slice(chunk);
650            src.advance(len);
651        }
652    }
653
654    #[inline]
655    fn put_slice(&mut self, src: &[u8]) {
656        self.reserve(src.len());
657        self.storage.put_slice_partial(src);
658    }
659
660    #[inline]
661    fn put_u8(&mut self, n: u8) {
662        self.reserve(1);
663        self.storage.put_u8(n);
664    }
665
666    #[inline]
667    fn put_i8(&mut self, n: i8) {
668        self.put_u8(n as u8);
669    }
670}
671
672/// Interop with the `bytes` crate: like `bytes::BytesMut`, the buffer grows on
673/// demand, so `remaining_mut()` reports `usize::MAX - len` and `chunk_mut()`
674/// is never empty. The native [`BufMut`] impl reports spare capacity instead.
675unsafe impl bytes::buf::BufMut for BytesMut {
676    #[inline]
677    fn remaining_mut(&self) -> usize {
678        usize::MAX - self.len()
679    }
680
681    #[inline]
682    unsafe fn advance_mut(&mut self, cnt: usize) {
683        let remaining = BufMut::remaining_mut(self);
684        assert!(
685            cnt <= remaining,
686            "cannot advance past `remaining_mut`: {cnt:?} <= {remaining:?}"
687        );
688        BufMut::advance_mut(self, cnt);
689    }
690
691    #[inline]
692    fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
693        if BufMut::remaining_mut(self) == 0 {
694            self.reserve(64);
695        }
696        unsafe {
697            let ptr = self.storage.as_ptr();
698            bytes::buf::UninitSlice::from_raw_parts_mut(
699                ptr.add(self.len()),
700                BufMut::remaining_mut(self),
701            )
702        }
703    }
704
705    #[inline]
706    fn put<T: bytes::buf::Buf>(&mut self, mut src: T)
707    where
708        Self: Sized,
709    {
710        self.reserve(src.remaining());
711        while src.has_remaining() {
712            let chunk = src.chunk();
713            let len = chunk.len();
714            BufMut::put_slice(self, chunk);
715            src.advance(len);
716        }
717    }
718
719    #[inline]
720    fn put_slice(&mut self, src: &[u8]) {
721        BufMut::put_slice(self, src);
722    }
723
724    #[inline]
725    fn put_bytes(&mut self, val: u8, cnt: usize) {
726        self.reserve(cnt);
727        unsafe {
728            ptr::write_bytes(self.storage.as_ptr().add(self.len()), val, cnt);
729            BufMut::advance_mut(self, cnt);
730        }
731    }
732
733    #[inline]
734    fn put_u8(&mut self, n: u8) {
735        BufMut::put_u8(self, n);
736    }
737
738    #[inline]
739    fn put_i8(&mut self, n: i8) {
740        BufMut::put_i8(self, n);
741    }
742}
743
744impl AsMut<[u8]> for BytesMut {
745    #[inline]
746    fn as_mut(&mut self) -> &mut [u8] {
747        self.storage.as_mut()
748    }
749}
750
751impl DerefMut for BytesMut {
752    #[inline]
753    fn deref_mut(&mut self) -> &mut [u8] {
754        self.storage.as_mut()
755    }
756}
757
758impl Eq for BytesMut {}
759
760impl PartialEq for BytesMut {
761    #[inline]
762    fn eq(&self, other: &BytesMut) -> bool {
763        self.storage.as_ref() == other.storage.as_ref()
764    }
765}
766
767impl borrow::BorrowMut<[u8]> for BytesMut {
768    #[inline]
769    fn borrow_mut(&mut self) -> &mut [u8] {
770        self.as_mut()
771    }
772}
773
774impl PartialEq<Bytes> for BytesMut {
775    fn eq(&self, other: &Bytes) -> bool {
776        other[..] == self[..]
777    }
778}
779
780impl PartialEq<BytesMut> for Bytes {
781    fn eq(&self, other: &BytesMut) -> bool {
782        *other == *self
783    }
784}
785
786impl_read!(BytesMut);
787
788impl io::Write for BytesMut {
789    fn write(&mut self, src: &[u8]) -> Result<usize, io::Error> {
790        self.extend_from_slice(src);
791        Ok(src.len())
792    }
793
794    fn flush(&mut self) -> Result<(), io::Error> {
795        Ok(())
796    }
797}
798
799impl fmt::Write for BytesMut {
800    #[inline]
801    fn write_str(&mut self, s: &str) -> fmt::Result {
802        self.extend_from_slice(s.as_bytes());
803        Ok(())
804    }
805}
806
807impl Clone for BytesMut {
808    #[inline]
809    fn clone(&self) -> BytesMut {
810        BytesMut::from(&self[..])
811    }
812}
813
814impl FromIterator<u8> for BytesMut {
815    fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
816        let iter = into_iter.into_iter();
817        let (min, maybe_max) = iter.size_hint();
818
819        let mut out = BytesMut::with_capacity(maybe_max.unwrap_or(min));
820        out.extend(iter);
821        out
822    }
823}
824
825impl<'a> FromIterator<&'a u8> for BytesMut {
826    fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
827        into_iter.into_iter().copied().collect::<BytesMut>()
828    }
829}
830
831impl Extend<u8> for BytesMut {
832    fn extend<T>(&mut self, iter: T)
833    where
834        T: IntoIterator<Item = u8>,
835    {
836        let iter = iter.into_iter();
837        self.reserve(iter.size_hint().0);
838        for b in iter {
839            self.put_u8(b);
840        }
841    }
842}
843
844impl<'a> Extend<&'a u8> for BytesMut {
845    fn extend<T>(&mut self, iter: T)
846    where
847        T: IntoIterator<Item = &'a u8>,
848    {
849        self.extend(iter.into_iter().copied());
850    }
851}
852
853impl From<BytesMut> for Bytes {
854    #[inline]
855    fn from(b: BytesMut) -> Self {
856        b.freeze()
857    }
858}
859
860impl<'a> From<&'a [u8]> for BytesMut {
861    #[inline]
862    fn from(src: &'a [u8]) -> BytesMut {
863        BytesMut::copy_from_slice(src)
864    }
865}
866
867impl<const N: usize> From<[u8; N]> for BytesMut {
868    #[inline]
869    fn from(src: [u8; N]) -> BytesMut {
870        BytesMut::copy_from_slice(src)
871    }
872}
873
874impl<'a, const N: usize> From<&'a [u8; N]> for BytesMut {
875    #[inline]
876    fn from(src: &'a [u8; N]) -> BytesMut {
877        BytesMut::copy_from_slice(src)
878    }
879}
880
881impl<'a> From<&'a str> for BytesMut {
882    #[inline]
883    fn from(src: &'a str) -> BytesMut {
884        BytesMut::from(src.as_bytes())
885    }
886}
887
888impl From<Bytes> for BytesMut {
889    #[inline]
890    fn from(src: Bytes) -> BytesMut {
891        match src.storage.try_into_vec() {
892            Ok(storage) => BytesMut { storage },
893            Err(storage) => BytesMut::copy_from_slice(storage.as_ref()),
894        }
895    }
896}
897
898impl From<&Bytes> for BytesMut {
899    #[inline]
900    fn from(src: &Bytes) -> BytesMut {
901        BytesMut::copy_from_slice(&src[..])
902    }
903}
904
905#[cfg(test)]
906mod tests {
907    use super::*;
908
909    #[test]
910    fn growth_is_amortized() {
911        let mut buf = BytesMut::with_capacity(0);
912        let mut cap = buf.capacity();
913        let mut reallocs = 0;
914        for _ in 0..10_000 {
915            buf.put_slice(b"abcdefgh");
916            if buf.capacity() != cap {
917                reallocs += 1;
918                cap = buf.capacity();
919            }
920        }
921        assert_eq!(buf.len(), 80_000);
922        assert!(reallocs <= 16, "reallocs: {reallocs}");
923
924        // writes through `io::Write` and `fmt::Write` grow the same way
925        let mut buf = BytesMut::with_capacity(0);
926        for i in 0..1000 {
927            std::fmt::Write::write_fmt(&mut buf, format_args!("{i:08}")).unwrap();
928        }
929        assert_eq!(buf.len(), 8000);
930        assert!(buf.capacity() < 16_000);
931    }
932
933    #[test]
934    fn growth_of_little_data_is_exact() {
935        let mut buf = BytesMut::copy_from_slice(b"hello");
936        buf.reserve(64 * 1024);
937        assert_eq!(buf.capacity(), 5 + 64 * 1024);
938
939        // a buffer shared with split off `Bytes`
940        let mut buf = BytesMut::with_capacity(1024);
941        buf.extend_from_slice(&[1; 1024]);
942        let head = buf.split_to(1000);
943        buf.reserve(4096);
944        assert_eq!(buf.capacity(), 24 + 4096);
945        assert_eq!(&head[..], &[1; 1000][..]);
946    }
947
948    #[test]
949    fn from_unique_bytes_reuses_buffer() {
950        let mut buf = BytesMut::with_capacity(256);
951        buf.extend_from_slice(&[1; 64]);
952        let b = buf.freeze();
953        let ptr = b.as_ptr();
954
955        let mut m = BytesMut::from(b);
956        assert_eq!(m.as_ptr(), ptr);
957        assert_eq!(&m[..], &[1; 64][..]);
958        assert_eq!(m.capacity(), 256);
959
960        // spare capacity past the view is writable
961        m.extend_from_slice(&[2; 192]);
962        assert_eq!(m.as_ptr(), ptr);
963        assert_eq!(&m[64..], &[2; 192][..]);
964    }
965
966    #[test]
967    fn from_unique_bytes_subview() {
968        let mut buf = BytesMut::with_capacity(256);
969        buf.extend_from_slice(&[1; 128]);
970        let mut b = buf.freeze();
971        let head = b.split_to(32);
972        drop(head);
973        b.truncate(64);
974        let ptr = b.as_ptr();
975
976        let mut m = BytesMut::from(b);
977        assert_eq!(m.as_ptr(), ptr);
978        assert_eq!(m.len(), 64);
979        assert_eq!(m.capacity(), 256 - 32);
980
981        // the dropped tail of the view is spare capacity again
982        m.extend_from_slice(&[3; 160]);
983        assert_eq!(m.as_ptr(), ptr);
984        assert_eq!(&m[..64], &[1; 64][..]);
985        assert_eq!(&m[64..], &[3; 160][..]);
986    }
987
988    #[test]
989    fn from_shared_bytes_copies() {
990        let b = BytesMut::copy_from_slice([1; 64]).freeze();
991        let b2 = b.clone();
992
993        let mut m = BytesMut::from(b);
994        assert_ne!(m.as_ptr(), b2.as_ptr());
995        m[0] = 2;
996        assert_eq!(&b2[..], &[1; 64][..]);
997
998        // the buffer is still referenced by a `BytesMut`
999        let mut buf = BytesMut::with_capacity(256);
1000        buf.extend_from_slice(&[1; 64]);
1001        let b = buf.take();
1002        let m = BytesMut::from(b);
1003        assert_ne!(m.as_ptr(), buf.as_ptr());
1004        buf.extend_from_slice(&[2; 64]);
1005        assert_eq!(&m[..], &[1; 64][..]);
1006    }
1007
1008    // Run under miri: without `Acquire`, the header update races with the
1009    // read made by the other thread before it released its handle.
1010    #[test]
1011    fn from_bytes_synchronizes_with_release() {
1012        let b = BytesMut::copy_from_slice([1; 64]).freeze();
1013        let other = b.clone();
1014        let handle = std::thread::spawn(move || {
1015            let val = other[0];
1016            drop(other);
1017            val
1018        });
1019
1020        let ptr = b.as_ptr();
1021        let mut storage = b.storage;
1022        let mut m = loop {
1023            match storage.try_into_vec() {
1024                Ok(storage) => break BytesMut { storage },
1025                Err(st) => {
1026                    storage = st;
1027                    std::thread::yield_now();
1028                }
1029            }
1030        };
1031        assert_eq!(m.as_ptr(), ptr);
1032        m[0] = 2;
1033        assert_eq!(handle.join().unwrap(), 1);
1034    }
1035
1036    #[test]
1037    fn from_inline_and_static_bytes() {
1038        let m = BytesMut::from(Bytes::copy_from_slice(b"inline"));
1039        assert_eq!(&m[..], b"inline");
1040
1041        let m = BytesMut::from(Bytes::from_static(&[1; 64]));
1042        assert_eq!(&m[..], &[1; 64][..]);
1043    }
1044
1045    #[test]
1046    fn bvec_read() {
1047        use std::io::Read;
1048
1049        let mut b = BytesMut::copy_from_slice(b"123");
1050
1051        let mut buf = [0; 10];
1052        assert_eq!(b.read(&mut buf).unwrap(), 3);
1053        assert_eq!(b.len(), 0);
1054        assert_eq!(buf, [49, 50, 51, 0, 0, 0, 0, 0, 0, 0]);
1055    }
1056
1057    #[test]
1058    fn from_bytes_ref() {
1059        let b = Bytes::from_static(b"hello");
1060        let mut m = BytesMut::from(&b);
1061        m.extend_from_slice(b"!");
1062        assert_eq!(m, "hello!");
1063        assert_eq!(b, "hello");
1064    }
1065}