Skip to main content

bytes/
bytes_mut.rs

1use core::mem::{self, ManuallyDrop, MaybeUninit};
2use core::ops::{Deref, DerefMut};
3use core::ptr::{self, NonNull};
4use core::{cmp, fmt, hash, slice};
5
6use alloc::{
7    borrow::{Borrow, BorrowMut},
8    boxed::Box,
9    string::String,
10    vec,
11    vec::Vec,
12};
13
14use crate::buf::{IntoIter, UninitSlice};
15use crate::bytes::Vtable;
16#[allow(unused)]
17use crate::loom::sync::atomic::AtomicMut;
18use crate::loom::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
19use crate::{Buf, BufMut, Bytes, TryGetError};
20
21/// A unique reference to a contiguous slice of memory.
22///
23/// `BytesMut` represents a unique view into a potentially shared memory region.
24/// Given the uniqueness guarantee, owners of `BytesMut` handles are able to
25/// mutate the memory.
26///
27/// `BytesMut` can be thought of as containing a `buf: Arc<Vec<u8>>`, an offset
28/// into `buf`, a slice length, and a guarantee that no other `BytesMut` for the
29/// same `buf` overlaps with its slice. That guarantee means that a write lock
30/// is not required.
31///
32/// # Growth
33///
34/// `BytesMut`'s `BufMut` implementation will implicitly grow its buffer as
35/// necessary. However, explicitly reserving the required space up-front before
36/// a series of inserts will be more efficient.
37///
38/// # Examples
39///
40/// ```
41/// use bytes::{BytesMut, BufMut};
42///
43/// let mut buf = BytesMut::with_capacity(64);
44///
45/// buf.put_u8(b'h');
46/// buf.put_u8(b'e');
47/// buf.put(&b"llo"[..]);
48///
49/// assert_eq!(&buf[..], b"hello");
50///
51/// // Freeze the buffer so that it can be shared
52/// let a = buf.freeze();
53///
54/// // This does not allocate, instead `b` points to the same memory.
55/// let b = a.clone();
56///
57/// assert_eq!(&a[..], b"hello");
58/// assert_eq!(&b[..], b"hello");
59/// ```
60pub struct BytesMut {
61    ptr: NonNull<u8>,
62    len: usize,
63    cap: usize,
64    data: *mut Shared,
65}
66
67// Thread-safe reference-counted container for the shared storage. This mostly
68// the same as `core::sync::Arc` but without the weak counter. The ref counting
69// fns are based on the ones found in `std`.
70//
71// The main reason to use `Shared` instead of `core::sync::Arc` is that it ends
72// up making the overall code simpler and easier to reason about. This is due to
73// some of the logic around setting `Inner::arc` and other ways the `arc` field
74// is used. Using `Arc` ended up requiring a number of funky transmutes and
75// other shenanigans to make it work.
76struct Shared {
77    vec: Vec<u8>,
78    original_capacity_repr: usize,
79    ref_count: AtomicUsize,
80}
81
82impl Shared {
83    fn init_to_raw(b: Box<MaybeUninit<Self>>, v: Self) -> *mut Self {
84        let shared = Box::into_raw(b).cast::<Self>();
85        // SAFETY: The Box has the right layout.
86        unsafe { shared.write(v) };
87        shared
88    }
89}
90
91// Assert that the alignment of `Shared` is divisible by 2.
92// This is a necessary invariant since we depend on allocating `Shared` a
93// shared object to implicitly carry the `KIND_ARC` flag in its pointer.
94// This flag is set when the LSB is 0.
95const _: () = {
96    assert!(
97        mem::align_of::<Shared>() % 2 == 0,
98        "Shared alignment must be divisible by 2 for pointer tagging"
99    );
100};
101
102// Buffer storage strategy flags.
103const KIND_ARC: usize = 0b0;
104const KIND_VEC: usize = 0b1;
105const KIND_MASK: usize = 0b1;
106
107// The max original capacity value. Any `Bytes` allocated with a greater initial
108// capacity will default to this.
109const MAX_ORIGINAL_CAPACITY_WIDTH: usize = 17;
110// The original capacity algorithm will not take effect unless the originally
111// allocated capacity was at least 1kb in size.
112const MIN_ORIGINAL_CAPACITY_WIDTH: usize = 10;
113// The original capacity is stored in powers of 2 starting at 1kb to a max of
114// 64kb. Representing it as such requires only 3 bits of storage.
115const ORIGINAL_CAPACITY_MASK: usize = 0b11100;
116const ORIGINAL_CAPACITY_OFFSET: usize = 2;
117
118const VEC_POS_OFFSET: usize = 5;
119// When the storage is in the `Vec` representation, the pointer can be advanced
120// at most this value. This is due to the amount of storage available to track
121// the offset is usize - number of KIND bits and number of ORIGINAL_CAPACITY
122// bits.
123const MAX_VEC_POS: usize = usize::MAX >> VEC_POS_OFFSET;
124const NOT_VEC_POS_MASK: usize = 0b11111;
125
126#[cfg(target_pointer_width = "64")]
127const PTR_WIDTH: usize = 64;
128#[cfg(target_pointer_width = "32")]
129const PTR_WIDTH: usize = 32;
130
131/*
132 *
133 * ===== BytesMut =====
134 *
135 */
136
137impl BytesMut {
138    /// Creates a new `BytesMut` with the specified capacity.
139    ///
140    /// The returned `BytesMut` will be able to hold at least `capacity` bytes
141    /// without reallocating.
142    ///
143    /// It is important to note that this function does not specify the length
144    /// of the returned `BytesMut`, but only the capacity.
145    ///
146    /// # Examples
147    ///
148    /// ```
149    /// use bytes::{BytesMut, BufMut};
150    ///
151    /// let mut bytes = BytesMut::with_capacity(64);
152    ///
153    /// // `bytes` contains no data, even though there is capacity
154    /// assert_eq!(bytes.len(), 0);
155    ///
156    /// bytes.put(&b"hello world"[..]);
157    ///
158    /// assert_eq!(&bytes[..], b"hello world");
159    /// ```
160    #[inline]
161    pub fn with_capacity(capacity: usize) -> BytesMut {
162        BytesMut::from_vec(Vec::with_capacity(capacity))
163    }
164
165    /// Creates a new `BytesMut` with default capacity.
166    ///
167    /// Resulting object has length 0 and unspecified capacity.
168    /// This function does not allocate.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// use bytes::{BytesMut, BufMut};
174    ///
175    /// let mut bytes = BytesMut::new();
176    ///
177    /// assert_eq!(0, bytes.len());
178    ///
179    /// bytes.reserve(2);
180    /// bytes.put_slice(b"xy");
181    ///
182    /// assert_eq!(&b"xy"[..], &bytes[..]);
183    /// ```
184    #[inline]
185    pub fn new() -> BytesMut {
186        BytesMut::with_capacity(0)
187    }
188
189    /// Returns the number of bytes contained in this `BytesMut`.
190    ///
191    /// # Examples
192    ///
193    /// ```
194    /// use bytes::BytesMut;
195    ///
196    /// let b = BytesMut::from(&b"hello"[..]);
197    /// assert_eq!(b.len(), 5);
198    /// ```
199    #[inline]
200    pub fn len(&self) -> usize {
201        self.len
202    }
203
204    /// Returns true if the `BytesMut` has a length of 0.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// use bytes::BytesMut;
210    ///
211    /// let b = BytesMut::with_capacity(64);
212    /// assert!(b.is_empty());
213    /// ```
214    #[inline]
215    pub fn is_empty(&self) -> bool {
216        self.len == 0
217    }
218
219    /// Returns the number of bytes the `BytesMut` can hold without reallocating.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use bytes::BytesMut;
225    ///
226    /// let b = BytesMut::with_capacity(64);
227    /// assert_eq!(b.capacity(), 64);
228    /// ```
229    #[inline]
230    pub fn capacity(&self) -> usize {
231        self.cap
232    }
233
234    /// Converts `self` into an immutable `Bytes`.
235    ///
236    /// The conversion is zero cost and is used to indicate that the slice
237    /// referenced by the handle will no longer be mutated. Once the conversion
238    /// is done, the handle can be cloned and shared across threads.
239    ///
240    /// # Examples
241    ///
242    /// ```ignore-wasm
243    /// use bytes::{BytesMut, BufMut};
244    /// use std::thread;
245    ///
246    /// let mut b = BytesMut::with_capacity(64);
247    /// b.put(&b"hello world"[..]);
248    /// let b1 = b.freeze();
249    /// let b2 = b1.clone();
250    ///
251    /// let th = thread::spawn(move || {
252    ///     assert_eq!(&b1[..], b"hello world");
253    /// });
254    ///
255    /// assert_eq!(&b2[..], b"hello world");
256    /// th.join().unwrap();
257    /// ```
258    #[inline]
259    pub fn freeze(self) -> Bytes {
260        let bytes = ManuallyDrop::new(self);
261        if bytes.kind() == KIND_VEC {
262            // Just re-use `Bytes` internal Vec vtable
263            unsafe {
264                let off = bytes.get_vec_pos();
265                let vec = rebuild_vec(bytes.ptr.as_ptr(), bytes.len, bytes.cap, off);
266                let mut b: Bytes = vec.into();
267                b.advance(off);
268                b
269            }
270        } else {
271            debug_assert_eq!(bytes.kind(), KIND_ARC);
272
273            let ptr = bytes.ptr.as_ptr();
274            let len = bytes.len;
275            let data = AtomicPtr::new(bytes.data.cast());
276            unsafe { Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE) }
277        }
278    }
279
280    /// Creates a new `BytesMut` containing `len` zeros.
281    ///
282    /// The resulting object has a length of `len` and a capacity greater
283    /// than or equal to `len`. The entire length of the object will be filled
284    /// with zeros.
285    ///
286    /// On some platforms or allocators this function may be faster than
287    /// a manual implementation.
288    ///
289    /// # Examples
290    ///
291    /// ```
292    /// use bytes::BytesMut;
293    ///
294    /// let zeros = BytesMut::zeroed(42);
295    ///
296    /// assert!(zeros.capacity() >= 42);
297    /// assert_eq!(zeros.len(), 42);
298    /// zeros.into_iter().for_each(|x| assert_eq!(x, 0));
299    /// ```
300    pub fn zeroed(len: usize) -> BytesMut {
301        BytesMut::from_vec(vec![0; len])
302    }
303
304    /// Splits the bytes into two at the given index.
305    ///
306    /// Afterwards `self` contains elements `[0, at)`, and the returned
307    /// `BytesMut` contains elements `[at, capacity)`. It's guaranteed that the
308    /// memory does not move, that is, the address of `self` does not change,
309    /// and the address of the returned slice is `at` bytes after that.
310    ///
311    /// This is an `O(1)` operation that just increases the reference count
312    /// and sets a few indices.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use bytes::BytesMut;
318    ///
319    /// let mut a = BytesMut::from(&b"hello world"[..]);
320    /// let mut b = a.split_off(5);
321    ///
322    /// a[0] = b'j';
323    /// b[0] = b'!';
324    ///
325    /// assert_eq!(&a[..], b"jello");
326    /// assert_eq!(&b[..], b"!world");
327    /// ```
328    ///
329    /// # Panics
330    ///
331    /// Panics if `at > capacity`.
332    #[must_use = "consider BytesMut::truncate if you don't need the other half"]
333    pub fn split_off(&mut self, at: usize) -> BytesMut {
334        assert!(
335            at <= self.capacity(),
336            "split_off out of bounds: {:?} <= {:?}",
337            at,
338            self.capacity(),
339        );
340        unsafe {
341            // SAFETY: `shallow_clone` increments the reference count (or
342            // promotes to shared) and returns a bitwise copy of the handle.
343            // The caller immediately adjusts both handles so they represent
344            // disjoint regions.
345            let mut other = self.shallow_clone();
346            // SAFETY: We've checked that `at` <= `self.capacity()` above.
347            other.advance_unchecked(at);
348            self.cap = at;
349            self.len = cmp::min(self.len, at);
350            other
351        }
352    }
353
354    /// Removes the bytes from the current view, returning them in a new
355    /// `BytesMut` handle.
356    ///
357    /// Afterwards, `self` will be empty, but will retain any additional
358    /// capacity that it had before the operation. This is identical to
359    /// `self.split_to(self.len())`.
360    ///
361    /// This is an `O(1)` operation that just increases the reference count and
362    /// sets a few indices.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use bytes::{BytesMut, BufMut};
368    ///
369    /// let mut buf = BytesMut::with_capacity(1024);
370    /// buf.put(&b"hello world"[..]);
371    ///
372    /// let other = buf.split();
373    ///
374    /// assert!(buf.is_empty());
375    /// assert_eq!(1013, buf.capacity());
376    ///
377    /// assert_eq!(other, b"hello world"[..]);
378    /// ```
379    #[must_use = "consider BytesMut::clear if you don't need the other half"]
380    pub fn split(&mut self) -> BytesMut {
381        let len = self.len();
382        self.split_to(len)
383    }
384
385    /// Splits the buffer into two at the given index.
386    ///
387    /// Afterwards `self` contains elements `[at, len)`, and the returned `BytesMut`
388    /// contains elements `[0, at)`.
389    ///
390    /// This is an `O(1)` operation that just increases the reference count and
391    /// sets a few indices.
392    ///
393    /// # Examples
394    ///
395    /// ```
396    /// use bytes::BytesMut;
397    ///
398    /// let mut a = BytesMut::from(&b"hello world"[..]);
399    /// let mut b = a.split_to(5);
400    ///
401    /// a[0] = b'!';
402    /// b[0] = b'j';
403    ///
404    /// assert_eq!(&a[..], b"!world");
405    /// assert_eq!(&b[..], b"jello");
406    /// ```
407    ///
408    /// # Panics
409    ///
410    /// Panics if `at > len`.
411    #[must_use = "consider BytesMut::advance if you don't need the other half"]
412    pub fn split_to(&mut self, at: usize) -> BytesMut {
413        assert!(
414            at <= self.len(),
415            "split_to out of bounds: {:?} <= {:?}",
416            at,
417            self.len(),
418        );
419
420        unsafe {
421            // SAFETY: `shallow_clone` increments the reference count (or
422            // promotes to shared) and returns a bitwise copy of the handle.
423            // The caller immediately adjusts both handles so they represent
424            // disjoint regions.
425            let mut other = self.shallow_clone();
426            // SAFETY: We've checked that `at` <= `self.len()` and we know that `self.len()` <=
427            // `self.capacity()`.
428            self.advance_unchecked(at);
429            other.cap = at;
430            other.len = at;
431            other
432        }
433    }
434
435    /// Shortens the buffer, keeping the first `len` bytes and dropping the
436    /// rest.
437    ///
438    /// If `len` is greater than the buffer's current length, this has no
439    /// effect.
440    ///
441    /// Existing underlying capacity is preserved.
442    ///
443    /// The [split_off](`Self::split_off()`) method can emulate `truncate`, but this causes the
444    /// excess bytes to be returned instead of dropped.
445    ///
446    /// # Examples
447    ///
448    /// ```
449    /// use bytes::BytesMut;
450    ///
451    /// let mut buf = BytesMut::from(&b"hello world"[..]);
452    /// buf.truncate(5);
453    /// assert_eq!(buf, b"hello"[..]);
454    /// ```
455    pub fn truncate(&mut self, len: usize) {
456        if len <= self.len() {
457            // SAFETY: Shrinking the buffer cannot expose uninitialized bytes.
458            unsafe { self.set_len(len) };
459        }
460    }
461
462    /// Clears the buffer, removing all data. Existing capacity is preserved.
463    ///
464    /// # Examples
465    ///
466    /// ```
467    /// use bytes::BytesMut;
468    ///
469    /// let mut buf = BytesMut::from(&b"hello world"[..]);
470    /// buf.clear();
471    /// assert!(buf.is_empty());
472    /// ```
473    pub fn clear(&mut self) {
474        // SAFETY: Setting the length to zero cannot expose uninitialized bytes.
475        unsafe { self.set_len(0) };
476    }
477
478    /// Resizes the buffer so that `len` is equal to `new_len`.
479    ///
480    /// If `new_len` is greater than `len`, the buffer is extended by the
481    /// difference with each additional byte set to `value`. If `new_len` is
482    /// less than `len`, the buffer is simply truncated.
483    ///
484    /// # Examples
485    ///
486    /// ```
487    /// use bytes::BytesMut;
488    ///
489    /// let mut buf = BytesMut::new();
490    ///
491    /// buf.resize(3, 0x1);
492    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
493    ///
494    /// buf.resize(2, 0x2);
495    /// assert_eq!(&buf[..], &[0x1, 0x1]);
496    ///
497    /// buf.resize(4, 0x3);
498    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
499    /// ```
500    pub fn resize(&mut self, new_len: usize, value: u8) {
501        let additional = if let Some(additional) = new_len.checked_sub(self.len()) {
502            additional
503        } else {
504            self.truncate(new_len);
505            return;
506        };
507
508        if additional == 0 {
509            return;
510        }
511
512        self.reserve(additional);
513        let dst = self.spare_capacity_mut().as_mut_ptr();
514        // SAFETY: `spare_capacity_mut` returns a valid, properly aligned pointer and we've
515        // reserved enough space to write `additional` bytes.
516        unsafe { ptr::write_bytes(dst, value, additional) };
517
518        // SAFETY: There are at least `new_len` initialized bytes in the buffer so no
519        // uninitialized bytes are being exposed.
520        unsafe { self.set_len(new_len) };
521    }
522
523    /// Sets the length of the buffer.
524    ///
525    /// This will explicitly set the size of the buffer without actually
526    /// modifying the data, so it is up to the caller to ensure that the data
527    /// has been initialized.
528    ///
529    /// # Examples
530    ///
531    /// ```
532    /// use bytes::BytesMut;
533    ///
534    /// let mut b = BytesMut::from(&b"hello world"[..]);
535    ///
536    /// unsafe {
537    ///     b.set_len(5);
538    /// }
539    ///
540    /// assert_eq!(&b[..], b"hello");
541    ///
542    /// unsafe {
543    ///     b.set_len(11);
544    /// }
545    ///
546    /// assert_eq!(&b[..], b"hello world");
547    /// ```
548    #[inline]
549    pub unsafe fn set_len(&mut self, len: usize) {
550        debug_assert!(len <= self.cap, "set_len out of bounds");
551        self.len = len;
552    }
553
554    /// Reserves capacity for at least `additional` more bytes to be inserted
555    /// into the given `BytesMut`.
556    ///
557    /// More than `additional` bytes may be reserved in order to avoid frequent
558    /// reallocations. A call to `reserve` may result in an allocation.
559    ///
560    /// Before allocating new buffer space, the function will attempt to reclaim
561    /// space in the existing buffer. If the current handle references a view
562    /// into a larger original buffer, and all other handles referencing part
563    /// of the same original buffer have been dropped, then the current view
564    /// can be copied/shifted to the front of the buffer and the handle can take
565    /// ownership of the full buffer, provided that the full buffer is large
566    /// enough to fit the requested additional capacity.
567    ///
568    /// This optimization will only happen if shifting the data from the current
569    /// view to the front of the buffer is not too expensive in terms of the
570    /// (amortized) time required. The precise condition is subject to change;
571    /// as of now, the length of the data being shifted needs to be at least as
572    /// large as the distance that it's shifted by. If the current view is empty
573    /// and the original buffer is large enough to fit the requested additional
574    /// capacity, then reallocations will never happen.
575    ///
576    /// This method does not preserve data stored in the unused capacity.
577    ///
578    /// # Examples
579    ///
580    /// In the following example, a new buffer is allocated.
581    ///
582    /// ```
583    /// use bytes::BytesMut;
584    ///
585    /// let mut buf = BytesMut::from(&b"hello"[..]);
586    /// buf.reserve(64);
587    /// assert!(buf.capacity() >= 69);
588    /// ```
589    ///
590    /// In the following example, the existing buffer is reclaimed.
591    ///
592    /// ```
593    /// use bytes::{BytesMut, BufMut};
594    ///
595    /// let mut buf = BytesMut::with_capacity(128);
596    /// buf.put(&[0; 64][..]);
597    ///
598    /// let ptr = buf.as_ptr();
599    /// let other = buf.split();
600    ///
601    /// assert!(buf.is_empty());
602    /// assert_eq!(buf.capacity(), 64);
603    ///
604    /// drop(other);
605    /// buf.reserve(128);
606    ///
607    /// assert_eq!(buf.capacity(), 128);
608    /// assert_eq!(buf.as_ptr(), ptr);
609    /// ```
610    ///
611    /// # Panics
612    ///
613    /// Panics if the new capacity overflows `usize`.
614    #[inline]
615    pub fn reserve(&mut self, additional: usize) {
616        let len = self.len();
617        let rem = self.capacity() - len;
618
619        if additional <= rem {
620            // The handle can already store at least `additional` more bytes, so
621            // there is no further work needed to be done.
622            return;
623        }
624
625        // will always succeed
626        let _ = self.reserve_inner(additional, true);
627    }
628
629    // In separate function to allow the short-circuits in `reserve` and `try_reclaim` to
630    // be inline-able. Significantly helps performance. Returns false if it did not succeed.
631    fn reserve_inner(&mut self, additional: usize, allocate: bool) -> bool {
632        let len = self.len();
633        let kind = self.kind();
634
635        if kind == KIND_VEC {
636            // If there's enough free space before the start of the buffer, then
637            // just copy the data backwards and reuse the already-allocated
638            // space.
639            //
640            // Otherwise, since backed by a vector, use `Vec::reserve`
641            //
642            // We need to make sure that this optimization does not kill the
643            // amortized runtimes of BytesMut's operations.
644            unsafe {
645                let off = self.get_vec_pos();
646
647                // Only reuse space if we can satisfy the requested additional space.
648                //
649                // Also check if the value of `off` suggests that enough bytes
650                // have been read to account for the overhead of shifting all
651                // the data (in an amortized analysis).
652                // Hence the condition `off >= self.len()`.
653                //
654                // This condition also already implies that the buffer is going
655                // to be (at least) half-empty in the end; so we do not break
656                // the (amortized) runtime with future resizes of the underlying
657                // `Vec`.
658                //
659                // [For more details check issue #524, and PR #525.]
660                if self.capacity() - self.len() + off >= additional && off >= self.len() {
661                    // There's enough space, and it's not too much overhead:
662                    // reuse the space!
663                    //
664                    // Just move the pointer back to the start after copying
665                    // data back.
666                    let base_ptr = self.ptr.as_ptr().sub(off);
667                    // Since `off >= self.len()`, the two regions don't overlap.
668                    ptr::copy_nonoverlapping(self.ptr.as_ptr(), base_ptr, self.len);
669                    self.ptr = vptr(base_ptr);
670                    self.set_vec_pos(0);
671
672                    // Length stays constant, but since we moved backwards we
673                    // can gain capacity back.
674                    self.cap += off;
675                } else {
676                    if !allocate {
677                        return false;
678                    }
679                    // Not enough space, or reusing might be too much overhead:
680                    // allocate more space!
681                    let mut v =
682                        ManuallyDrop::new(rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off));
683                    v.reserve(additional);
684
685                    // Update the info
686                    self.ptr = vptr(v.as_mut_ptr().add(off));
687                    self.cap = v.capacity() - off;
688                    debug_assert_eq!(self.len, v.len() - off);
689                }
690
691                return true;
692            }
693        }
694
695        debug_assert_eq!(kind, KIND_ARC);
696        let shared: *mut Shared = self.data;
697
698        // Reserving involves abandoning the currently shared buffer and
699        // allocating a new vector with the requested capacity.
700        //
701        // Compute the new capacity
702        let mut new_cap = match len.checked_add(additional) {
703            Some(new_cap) => new_cap,
704            None if !allocate => return false,
705            None => panic!("overflow"),
706        };
707
708        unsafe {
709            // First, try to reclaim the buffer. This is possible if the current
710            // handle is the only outstanding handle pointing to the buffer.
711            if (*shared).is_unique() {
712                // This is the only handle to the buffer. It can be reclaimed.
713                // However, before doing the work of copying data, check to make
714                // sure that the vector has enough capacity.
715                let v = &mut (*shared).vec;
716
717                let v_capacity = v.capacity();
718                let ptr = v.as_mut_ptr();
719
720                let offset = self.ptr.as_ptr().offset_from(ptr) as usize;
721
722                let new_cap_plus_offset = match new_cap.checked_add(offset) {
723                    Some(new_cap_plus_offset) => new_cap_plus_offset,
724                    None if !allocate => return false,
725                    None => panic!("overflow"),
726                };
727
728                // Compare the condition in the `kind == KIND_VEC` case above
729                // for more details.
730                if v_capacity >= new_cap_plus_offset {
731                    self.cap = new_cap;
732                    // no copy is necessary
733                } else if v_capacity >= new_cap && offset >= len {
734                    // The capacity is sufficient, and copying is not too much
735                    // overhead: reclaim the buffer!
736
737                    // `offset >= len` means: no overlap
738                    ptr::copy_nonoverlapping(self.ptr.as_ptr(), ptr, len);
739
740                    self.ptr = vptr(ptr);
741                    self.cap = v.capacity();
742                } else {
743                    if !allocate {
744                        return false;
745                    }
746
747                    // new_cap is calculated in terms of `BytesMut`, not the underlying
748                    // `Vec`, so it does not take the offset into account.
749                    //
750                    // Thus we have to manually add it here.
751                    new_cap = new_cap_plus_offset;
752
753                    // The vector capacity is not sufficient. The reserve request is
754                    // asking for more than the initial buffer capacity. Allocate more
755                    // than requested if `new_cap` is not much bigger than the current
756                    // capacity.
757                    //
758                    // There are some situations, using `reserve_exact` that the
759                    // buffer capacity could be below `original_capacity`, so do a
760                    // check.
761                    let double = v.capacity().checked_shl(1).unwrap_or(new_cap);
762
763                    new_cap = cmp::max(double, new_cap);
764
765                    // No space - allocate more
766                    //
767                    // The length field of `Shared::vec` is not used by the `BytesMut`;
768                    // instead we use the `len` field in the `BytesMut` itself. However,
769                    // when calling `reserve`, it doesn't guarantee that data stored in
770                    // the unused capacity of the vector is copied over to the new
771                    // allocation, so we need to ensure that we don't have any data we
772                    // care about in the unused capacity before calling `reserve`.
773                    debug_assert!(offset + len <= v.capacity());
774                    v.set_len(offset + len);
775                    v.reserve(new_cap - v.len());
776
777                    // Update the info
778                    self.ptr = vptr(v.as_mut_ptr().add(offset));
779                    self.cap = v.capacity() - offset;
780                }
781
782                return true;
783            }
784        }
785        if !allocate {
786            return false;
787        }
788
789        let original_capacity_repr = unsafe { (*shared).original_capacity_repr };
790        let original_capacity = original_capacity_from_repr(original_capacity_repr);
791
792        new_cap = cmp::max(new_cap, original_capacity);
793
794        // Create a new vector to store the data
795        let mut v = ManuallyDrop::new(Vec::with_capacity(new_cap));
796
797        // Copy the bytes
798        v.extend_from_slice(self.as_ref());
799
800        // Release the shared handle. This must be done *after* the bytes are
801        // copied.
802        unsafe { release_shared(shared) };
803
804        // Update self
805        let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
806        self.data = invalid_ptr(data);
807        self.ptr = vptr(v.as_mut_ptr());
808        self.cap = v.capacity();
809        debug_assert_eq!(self.len, v.len());
810        true
811    }
812
813    /// Attempts to cheaply reclaim already allocated capacity for at least `additional` more
814    /// bytes to be inserted into the given `BytesMut` and returns `true` if it succeeded.
815    ///
816    /// `try_reclaim` behaves exactly like `reserve`, except that it never allocates new storage
817    /// and returns a `bool` indicating whether it was successful in doing so:
818    ///
819    /// `try_reclaim` returns false under these conditions:
820    ///  - The spare capacity left is less than `additional` bytes AND
821    ///  - The existing allocation cannot be reclaimed cheaply or it was less than
822    ///    `additional` bytes in size
823    ///
824    /// Reclaiming the allocation cheaply is possible if the `BytesMut` has no outstanding
825    /// references through other `BytesMut`s or `Bytes` which point to the same underlying
826    /// storage.
827    ///
828    /// This method does not preserve data stored in the unused capacity.
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// use bytes::BytesMut;
834    ///
835    /// let mut buf = BytesMut::with_capacity(64);
836    /// assert_eq!(true, buf.try_reclaim(64));
837    /// assert_eq!(64, buf.capacity());
838    ///
839    /// buf.extend_from_slice(b"abcd");
840    /// let mut split = buf.split();
841    /// assert_eq!(60, buf.capacity());
842    /// assert_eq!(4, split.capacity());
843    /// assert_eq!(false, split.try_reclaim(64));
844    /// assert_eq!(false, buf.try_reclaim(64));
845    /// // The split buffer is filled with "abcd"
846    /// assert_eq!(false, split.try_reclaim(4));
847    /// // buf is empty and has capacity for 60 bytes
848    /// assert_eq!(true, buf.try_reclaim(60));
849    ///
850    /// drop(buf);
851    /// assert_eq!(false, split.try_reclaim(64));
852    ///
853    /// split.clear();
854    /// assert_eq!(4, split.capacity());
855    /// assert_eq!(true, split.try_reclaim(64));
856    /// assert_eq!(64, split.capacity());
857    /// ```
858    // I tried splitting out try_reclaim_inner after the short circuits, but it was inlined
859    // regardless with Rust 1.78.0 so probably not worth it
860    #[inline]
861    #[must_use = "consider BytesMut::reserve if you need an infallible reservation"]
862    pub fn try_reclaim(&mut self, additional: usize) -> bool {
863        let len = self.len();
864        let rem = self.capacity() - len;
865
866        if additional <= rem {
867            // The handle can already store at least `additional` more bytes, so
868            // there is no further work needed to be done.
869            return true;
870        }
871
872        self.reserve_inner(additional, false)
873    }
874
875    /// Appends given bytes to this `BytesMut`.
876    ///
877    /// If this `BytesMut` object does not have enough capacity, it is resized
878    /// first.
879    ///
880    /// # Examples
881    ///
882    /// ```
883    /// use bytes::BytesMut;
884    ///
885    /// let mut buf = BytesMut::with_capacity(0);
886    /// buf.extend_from_slice(b"aaabbb");
887    /// buf.extend_from_slice(b"cccddd");
888    ///
889    /// assert_eq!(b"aaabbbcccddd", &buf[..]);
890    /// ```
891    #[inline]
892    pub fn extend_from_slice(&mut self, extend: &[u8]) {
893        let cnt = extend.len();
894        self.reserve(cnt);
895
896        unsafe {
897            let dst = self.spare_capacity_mut();
898            // Reserved above
899            debug_assert!(dst.len() >= cnt);
900
901            ptr::copy_nonoverlapping(extend.as_ptr(), dst.as_mut_ptr().cast(), cnt);
902        }
903
904        unsafe {
905            // Reserved above
906            self.set_len(self.len() + cnt);
907        }
908    }
909
910    /// Clones the elements in the given `range` within this `BytesMut` and
911    /// appends them to the end.
912    ///
913    /// # Panics
914    ///
915    /// Panics if `range` is out of bounds for this `BytesMut`.
916    ///
917    /// # Examples
918    ///
919    /// ```
920    /// use bytes::BytesMut;
921    ///
922    /// let mut buf = BytesMut::with_capacity(0);
923    /// buf.extend_from_slice(b"aaabbb_");
924    /// buf.extend_from_within(3..6);
925    ///
926    /// assert_eq!(b"aaabbb_bbb", &buf[..]);
927    /// ```
928    pub fn extend_from_within(&mut self, range: impl core::ops::RangeBounds<usize>) {
929        let (begin, end) = crate::range(range, self.len());
930
931        let cnt = end - begin;
932        self.reserve(cnt);
933
934        // SAFETY: range is already checked
935        let src = unsafe { self.as_ptr().add(begin) };
936        let dst = self.spare_capacity_mut();
937
938        // SAFETY: range doesn't overlap with spare capacity
939        unsafe { ptr::copy_nonoverlapping(src, dst.as_mut_ptr().cast(), cnt) }
940
941        // SAFETY: capacity is already reserved and filled with data
942        unsafe { self.advance_mut(cnt) }
943    }
944
945    /// Absorbs a `BytesMut` that was previously split off if they are
946    /// contiguous, otherwise appends its bytes to this `BytesMut`.
947    ///
948    /// If the two `BytesMut` objects were previously contiguous and not mutated
949    /// in a way that causes re-allocation i.e., if `other` was created by
950    /// calling `split_off` on this `BytesMut`, then this is an `O(1)` operation
951    /// that just decreases a reference count and sets a few indices.
952    /// Otherwise this method degenerates to
953    /// `self.extend_from_slice(other.as_ref())`.
954    ///
955    /// # Examples
956    ///
957    /// ```
958    /// use bytes::BytesMut;
959    ///
960    /// let mut buf = BytesMut::with_capacity(64);
961    /// buf.extend_from_slice(b"aaabbbcccddd");
962    ///
963    /// let split = buf.split_off(6);
964    /// assert_eq!(b"aaabbb", &buf[..]);
965    /// assert_eq!(b"cccddd", &split[..]);
966    ///
967    /// buf.unsplit(split);
968    /// assert_eq!(b"aaabbbcccddd", &buf[..]);
969    /// ```
970    pub fn unsplit(&mut self, other: BytesMut) {
971        if self.is_empty() {
972            *self = other;
973            return;
974        }
975
976        if let Err(other) = self.try_unsplit(other) {
977            self.extend_from_slice(other.as_ref());
978        }
979    }
980
981    // private
982
983    // For now, use a `Vec` to manage the memory for us, but we may want to
984    // change that in the future to some alternate allocator strategy.
985    //
986    // Thus, we don't expose an easy way to construct from a `Vec` since an
987    // internal change could make a simple pattern (`BytesMut::from(vec)`)
988    // suddenly a lot more expensive.
989    #[inline]
990    pub(crate) fn from_vec(vec: Vec<u8>) -> BytesMut {
991        let mut vec = ManuallyDrop::new(vec);
992        let ptr = vptr(vec.as_mut_ptr());
993        let len = vec.len();
994        let cap = vec.capacity();
995
996        let original_capacity_repr = original_capacity_to_repr(cap);
997        let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
998
999        BytesMut {
1000            ptr,
1001            len,
1002            cap,
1003            data: invalid_ptr(data),
1004        }
1005    }
1006
1007    #[inline]
1008    fn as_slice(&self) -> &[u8] {
1009        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
1010    }
1011
1012    #[inline]
1013    fn as_slice_mut(&mut self) -> &mut [u8] {
1014        unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
1015    }
1016
1017    /// Advance the buffer without bounds checking.
1018    ///
1019    /// # SAFETY
1020    ///
1021    /// The caller must ensure that `count` <= `self.cap`.
1022    pub(crate) unsafe fn advance_unchecked(&mut self, count: usize) {
1023        // Setting the start to 0 is a no-op, so return early if this is the
1024        // case.
1025        if count == 0 {
1026            return;
1027        }
1028
1029        debug_assert!(count <= self.cap, "internal: set_start out of bounds");
1030
1031        let kind = self.kind();
1032
1033        if kind == KIND_VEC {
1034            // Setting the start when in vec representation is a little more
1035            // complicated. First, we have to track how far ahead the
1036            // "start" of the byte buffer from the beginning of the vec. We
1037            // also have to ensure that we don't exceed the maximum shift.
1038            let pos = self.get_vec_pos() + count;
1039
1040            if pos <= MAX_VEC_POS {
1041                self.set_vec_pos(pos);
1042            } else {
1043                // The repr must be upgraded to ARC. This will never happen
1044                // on 64 bit systems and will only happen on 32 bit systems
1045                // when shifting past 134,217,727 bytes. As such, we don't
1046                // worry too much about performance here.
1047                self.promote_to_shared(/*ref_count = */ 1);
1048            }
1049        }
1050
1051        // Updating the start of the view is setting `ptr` to point to the
1052        // new start and updating the `len` field to reflect the new length
1053        // of the view.
1054        self.ptr = vptr(self.ptr.as_ptr().add(count));
1055        self.len = self.len.saturating_sub(count);
1056        self.cap -= count;
1057    }
1058
1059    /// Absorbs a `BytesMut` that was previously split off.
1060    ///
1061    /// If the two `BytesMut` objects were previously contiguous, i.e., if
1062    /// `other` was created by calling `split_off` on this `BytesMut`, then
1063    /// this is an `O(1)` operation that just decreases a reference
1064    /// count and sets a few indices. Otherwise this method returns an error
1065    /// containing the original `other`.
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// use bytes::BytesMut;
1071    ///
1072    /// let mut buf = BytesMut::with_capacity(64);
1073    /// buf.extend_from_slice(b"aaabbbcccddd");
1074    ///
1075    /// let mut split_1 = buf.split_off(3);
1076    /// let split_2 = split_1.split_off(3);
1077    /// assert_eq!(b"aaa", &buf[..]);
1078    /// assert_eq!(b"bbb", &split_1[..]);
1079    /// assert_eq!(b"cccddd", &split_2[..]);
1080    ///
1081    /// let split_2 = buf.try_unsplit(split_2).unwrap_err();
1082    ///
1083    /// buf.try_unsplit(split_1).unwrap();
1084    /// buf.try_unsplit(split_2).unwrap();
1085    /// assert_eq!(b"aaabbbcccddd", &buf[..]);
1086    /// ```
1087    pub fn try_unsplit(&mut self, other: BytesMut) -> Result<(), BytesMut> {
1088        if other.capacity() == 0 {
1089            return Ok(());
1090        }
1091
1092        let ptr = unsafe { self.ptr.as_ptr().add(self.len) };
1093        if ptr == other.ptr.as_ptr()
1094            && self.kind() == KIND_ARC
1095            && other.kind() == KIND_ARC
1096            && self.data == other.data
1097        {
1098            // Contiguous blocks, just combine directly
1099            self.len += other.len;
1100            self.cap += other.cap;
1101            Ok(())
1102        } else {
1103            Err(other)
1104        }
1105    }
1106
1107    #[inline]
1108    fn kind(&self) -> usize {
1109        self.data as usize & KIND_MASK
1110    }
1111
1112    unsafe fn promote_to_shared(&mut self, ref_cnt: usize) {
1113        debug_assert_eq!(self.kind(), KIND_VEC);
1114        debug_assert!(ref_cnt == 1 || ref_cnt == 2);
1115
1116        let original_capacity_repr =
1117            (self.data as usize & ORIGINAL_CAPACITY_MASK) >> ORIGINAL_CAPACITY_OFFSET;
1118
1119        // The vec offset cannot be concurrently mutated, so there
1120        // should be no danger reading it.
1121        let off = (self.data as usize) >> VEC_POS_OFFSET;
1122
1123        // First, allocate a new `Shared` instance containing the
1124        // `Vec` fields. It's important to note that `ptr`, `len`,
1125        // and `cap` cannot be mutated without having `&mut self`.
1126        // This means that these fields will not be concurrently
1127        // updated and since the buffer hasn't been promoted to an
1128        // `Arc`, those three fields still are the components of the
1129        // vector.
1130        //
1131        // Explicitly allocate before invoking rebuild_vec() so that
1132        // the vector is not dropped if Box::new() panics.
1133        let shared = Box::new(MaybeUninit::<Shared>::uninit());
1134        let shared = Shared::init_to_raw(
1135            shared,
1136            Shared {
1137                vec: rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off),
1138                original_capacity_repr,
1139                ref_count: AtomicUsize::new(ref_cnt),
1140            },
1141        );
1142
1143        // The pointer should be aligned, so this assert should
1144        // always succeed.
1145        debug_assert_eq!(shared as usize & KIND_MASK, KIND_ARC);
1146
1147        self.data = shared;
1148    }
1149
1150    /// Makes an exact shallow clone of `self`.
1151    ///
1152    /// The kind of `self` doesn't matter, but this is unsafe
1153    /// because the clone will have the same offsets. You must
1154    /// be sure the returned value to the user doesn't allow
1155    /// two views into the same range.
1156    #[inline]
1157    unsafe fn shallow_clone(&mut self) -> BytesMut {
1158        if self.kind() == KIND_ARC {
1159            increment_shared(self.data);
1160            ptr::read(self)
1161        } else {
1162            self.promote_to_shared(/*ref_count = */ 2);
1163            ptr::read(self)
1164        }
1165    }
1166
1167    #[inline]
1168    unsafe fn get_vec_pos(&self) -> usize {
1169        debug_assert_eq!(self.kind(), KIND_VEC);
1170
1171        self.data as usize >> VEC_POS_OFFSET
1172    }
1173
1174    #[inline]
1175    unsafe fn set_vec_pos(&mut self, pos: usize) {
1176        debug_assert_eq!(self.kind(), KIND_VEC);
1177        debug_assert!(pos <= MAX_VEC_POS);
1178
1179        self.data = invalid_ptr((pos << VEC_POS_OFFSET) | (self.data as usize & NOT_VEC_POS_MASK));
1180    }
1181
1182    /// Returns the remaining spare capacity of the buffer as a slice of `MaybeUninit<u8>`.
1183    ///
1184    /// The returned slice can be used to fill the buffer with data (e.g. by
1185    /// reading from a file) before marking the data as initialized using the
1186    /// [`set_len`] method.
1187    ///
1188    /// [`set_len`]: BytesMut::set_len
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```
1193    /// use bytes::BytesMut;
1194    ///
1195    /// // Allocate buffer big enough for 10 bytes.
1196    /// let mut buf = BytesMut::with_capacity(10);
1197    ///
1198    /// // Fill in the first 3 elements.
1199    /// let uninit = buf.spare_capacity_mut();
1200    /// uninit[0].write(0);
1201    /// uninit[1].write(1);
1202    /// uninit[2].write(2);
1203    ///
1204    /// // Mark the first 3 bytes of the buffer as being initialized.
1205    /// unsafe {
1206    ///     buf.set_len(3);
1207    /// }
1208    ///
1209    /// assert_eq!(&buf[..], &[0, 1, 2]);
1210    /// ```
1211    #[inline]
1212    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
1213        unsafe {
1214            let ptr = self.ptr.as_ptr().add(self.len);
1215            let len = self.cap - self.len;
1216
1217            slice::from_raw_parts_mut(ptr.cast(), len)
1218        }
1219    }
1220
1221    /// Appends bytes from `iter` into the spare capacity, without growing.
1222    ///
1223    /// Goes through `Vec::extend`, which carries std's `TrustedLen`
1224    /// specialization (slice-like iterators become a memcpy).
1225    ///
1226    /// # SAFETY
1227    ///
1228    /// The caller must ensure that `self.kind()` is `KIND_VEC`.
1229    #[inline(always)]
1230    unsafe fn extend_vec<I: Iterator<Item = u8>>(&mut self, iter: I) -> bool {
1231        debug_assert_eq!(self.kind(), KIND_VEC);
1232
1233        let off = self.get_vec_pos();
1234        let spare = self.cap - self.len;
1235        let mut vec = ManuallyDrop::new(rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off));
1236        vec.extend(iter.take(spare));
1237        self.len = vec.len() - off;
1238        debug_assert_eq!(vec.capacity(), self.cap + off);
1239        self.len == self.cap
1240    }
1241}
1242
1243impl Drop for BytesMut {
1244    fn drop(&mut self) {
1245        let kind = self.kind();
1246
1247        if kind == KIND_VEC {
1248            unsafe {
1249                let off = self.get_vec_pos();
1250
1251                // Vector storage, free the vector
1252                let _ = rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off);
1253            }
1254        } else if kind == KIND_ARC {
1255            unsafe { release_shared(self.data) };
1256        }
1257    }
1258}
1259
1260impl Buf for BytesMut {
1261    #[inline]
1262    fn remaining(&self) -> usize {
1263        self.len()
1264    }
1265
1266    #[inline]
1267    fn chunk(&self) -> &[u8] {
1268        self.as_slice()
1269    }
1270
1271    #[inline]
1272    fn advance(&mut self, cnt: usize) {
1273        assert!(
1274            cnt <= self.remaining(),
1275            "cannot advance past `remaining`: {:?} <= {:?}",
1276            cnt,
1277            self.remaining(),
1278        );
1279        unsafe {
1280            // SAFETY: We've checked that `cnt` <= `self.remaining()` and we know that
1281            // `self.remaining()` <= `self.cap`.
1282            self.advance_unchecked(cnt);
1283        }
1284    }
1285
1286    fn copy_to_bytes(&mut self, len: usize) -> Bytes {
1287        self.split_to(len).freeze()
1288    }
1289}
1290
1291unsafe impl BufMut for BytesMut {
1292    #[inline]
1293    fn remaining_mut(&self) -> usize {
1294        // Max allocation size is isize::MAX.
1295        isize::MAX as usize - self.len()
1296    }
1297
1298    #[inline]
1299    unsafe fn advance_mut(&mut self, cnt: usize) {
1300        let remaining = self.cap - self.len();
1301        if cnt > remaining {
1302            super::panic_advance(&TryGetError {
1303                requested: cnt,
1304                available: remaining,
1305            });
1306        }
1307        // Addition won't overflow since it is at most `self.cap`.
1308        self.len = self.len() + cnt;
1309    }
1310
1311    #[inline]
1312    fn chunk_mut(&mut self) -> &mut UninitSlice {
1313        if self.capacity() == self.len() {
1314            self.reserve(64);
1315        }
1316        self.spare_capacity_mut().into()
1317    }
1318
1319    // Specialize these methods so they can skip checking `remaining_mut`
1320    // and `advance_mut`.
1321
1322    #[inline]
1323    fn put<T: Buf>(&mut self, mut src: T)
1324    where
1325        Self: Sized,
1326    {
1327        if !src.has_remaining() {
1328            // prevent calling `copy_to_bytes`->`put`->`copy_to_bytes` infintely when src is empty
1329            return;
1330        } else if self.capacity() == 0 {
1331            #[cold]
1332            fn put_reuse_allocation<U: Buf>(dst: &mut BytesMut, mut src: U) {
1333                // When capacity is zero, try reusing allocation of `src`.
1334                let src_copy = src.copy_to_bytes(src.remaining());
1335                drop(src);
1336                match src_copy.try_into_mut() {
1337                    Ok(bytes_mut) => *dst = bytes_mut,
1338                    Err(bytes) => dst.extend_from_slice(&bytes),
1339                }
1340            }
1341
1342            put_reuse_allocation(self, src);
1343        } else {
1344            // In case the src isn't contiguous, reserve upfront.
1345            if src.chunk().len() < src.remaining() {
1346                self.reserve(src.remaining());
1347            }
1348
1349            while src.has_remaining() {
1350                let s = src.chunk();
1351                let l = s.len();
1352                self.extend_from_slice(s);
1353                src.advance(l);
1354            }
1355        }
1356    }
1357
1358    #[inline]
1359    fn put_slice(&mut self, src: &[u8]) {
1360        self.extend_from_slice(src);
1361    }
1362
1363    #[inline]
1364    fn put_u8(&mut self, n: u8) {
1365        // Same shape as `Vec::push`, avoiding the default's 1-byte `put_slice`.
1366        self.reserve(1);
1367        let len = self.len();
1368        // SAFETY: `reserve(1)` guarantees `len < capacity`, so `ptr + len` is
1369        // in bounds; the byte is initialized before `len` is bumped over it.
1370        unsafe {
1371            self.ptr.as_ptr().add(len).write(n);
1372            self.set_len(len + 1);
1373        }
1374    }
1375
1376    #[inline]
1377    fn put_i8(&mut self, n: i8) {
1378        self.put_u8(n as u8);
1379    }
1380
1381    #[inline]
1382    fn put_bytes(&mut self, val: u8, cnt: usize) {
1383        self.reserve(cnt);
1384        unsafe {
1385            let dst = self.spare_capacity_mut();
1386            // Reserved above
1387            debug_assert!(dst.len() >= cnt);
1388
1389            ptr::write_bytes(dst.as_mut_ptr(), val, cnt);
1390
1391            // Reserved above
1392            self.set_len(self.len() + cnt);
1393        }
1394    }
1395}
1396
1397impl AsRef<[u8]> for BytesMut {
1398    #[inline]
1399    fn as_ref(&self) -> &[u8] {
1400        self.as_slice()
1401    }
1402}
1403
1404impl Deref for BytesMut {
1405    type Target = [u8];
1406
1407    #[inline]
1408    fn deref(&self) -> &[u8] {
1409        self.as_ref()
1410    }
1411}
1412
1413impl AsMut<[u8]> for BytesMut {
1414    #[inline]
1415    fn as_mut(&mut self) -> &mut [u8] {
1416        self.as_slice_mut()
1417    }
1418}
1419
1420impl DerefMut for BytesMut {
1421    #[inline]
1422    fn deref_mut(&mut self) -> &mut [u8] {
1423        self.as_mut()
1424    }
1425}
1426
1427impl<'a> From<&'a [u8]> for BytesMut {
1428    fn from(src: &'a [u8]) -> BytesMut {
1429        BytesMut::from_vec(src.to_vec())
1430    }
1431}
1432
1433impl<'a> From<&'a str> for BytesMut {
1434    fn from(src: &'a str) -> BytesMut {
1435        BytesMut::from(src.as_bytes())
1436    }
1437}
1438
1439impl From<BytesMut> for Bytes {
1440    fn from(src: BytesMut) -> Bytes {
1441        src.freeze()
1442    }
1443}
1444
1445impl PartialEq for BytesMut {
1446    fn eq(&self, other: &BytesMut) -> bool {
1447        self.as_slice() == other.as_slice()
1448    }
1449}
1450
1451impl PartialOrd for BytesMut {
1452    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1453        Some(self.cmp(other))
1454    }
1455}
1456
1457impl Ord for BytesMut {
1458    fn cmp(&self, other: &BytesMut) -> cmp::Ordering {
1459        self.as_slice().cmp(other.as_slice())
1460    }
1461}
1462
1463impl Eq for BytesMut {}
1464
1465impl Default for BytesMut {
1466    #[inline]
1467    fn default() -> BytesMut {
1468        BytesMut::new()
1469    }
1470}
1471
1472impl hash::Hash for BytesMut {
1473    fn hash<H>(&self, state: &mut H)
1474    where
1475        H: hash::Hasher,
1476    {
1477        let s: &[u8] = self.as_ref();
1478        s.hash(state);
1479    }
1480}
1481
1482impl Borrow<[u8]> for BytesMut {
1483    fn borrow(&self) -> &[u8] {
1484        self.as_ref()
1485    }
1486}
1487
1488impl BorrowMut<[u8]> for BytesMut {
1489    fn borrow_mut(&mut self) -> &mut [u8] {
1490        self.as_mut()
1491    }
1492}
1493
1494impl fmt::Write for BytesMut {
1495    #[inline]
1496    fn write_str(&mut self, s: &str) -> fmt::Result {
1497        if self.remaining_mut() >= s.len() {
1498            self.put_slice(s.as_bytes());
1499            Ok(())
1500        } else {
1501            Err(fmt::Error)
1502        }
1503    }
1504
1505    #[inline]
1506    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
1507        fmt::write(self, args)
1508    }
1509}
1510
1511impl Clone for BytesMut {
1512    fn clone(&self) -> BytesMut {
1513        BytesMut::from(&self[..])
1514    }
1515}
1516
1517impl IntoIterator for BytesMut {
1518    type Item = u8;
1519    type IntoIter = IntoIter<BytesMut>;
1520
1521    fn into_iter(self) -> Self::IntoIter {
1522        IntoIter::new(self)
1523    }
1524}
1525
1526impl<'a> IntoIterator for &'a BytesMut {
1527    type Item = &'a u8;
1528    type IntoIter = core::slice::Iter<'a, u8>;
1529
1530    fn into_iter(self) -> Self::IntoIter {
1531        self.as_ref().iter()
1532    }
1533}
1534
1535impl Extend<u8> for BytesMut {
1536    fn extend<T>(&mut self, iter: T)
1537    where
1538        T: IntoIterator<Item = u8>,
1539    {
1540        let mut iter = iter.into_iter();
1541
1542        let (lower, _) = iter.size_hint();
1543        self.reserve(lower);
1544
1545        // Stop if the iterator ran dry; it may not be fused.
1546        if self.kind() == KIND_VEC {
1547            let may_have_more = unsafe { self.extend_vec(&mut iter) };
1548            if !may_have_more {
1549                return;
1550            }
1551        }
1552
1553        for b in iter {
1554            self.put_u8(b);
1555        }
1556    }
1557}
1558
1559impl<'a> Extend<&'a u8> for BytesMut {
1560    fn extend<T>(&mut self, iter: T)
1561    where
1562        T: IntoIterator<Item = &'a u8>,
1563    {
1564        self.extend(iter.into_iter().copied())
1565    }
1566}
1567
1568impl Extend<Bytes> for BytesMut {
1569    fn extend<T>(&mut self, iter: T)
1570    where
1571        T: IntoIterator<Item = Bytes>,
1572    {
1573        for bytes in iter {
1574            self.extend_from_slice(&bytes)
1575        }
1576    }
1577}
1578
1579impl FromIterator<u8> for BytesMut {
1580    fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
1581        BytesMut::from_vec(Vec::from_iter(into_iter))
1582    }
1583}
1584
1585impl<'a> FromIterator<&'a u8> for BytesMut {
1586    fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
1587        BytesMut::from_iter(into_iter.into_iter().copied())
1588    }
1589}
1590
1591/*
1592 *
1593 * ===== Inner =====
1594 *
1595 */
1596
1597unsafe fn increment_shared(ptr: *mut Shared) {
1598    let old_size = (*ptr).ref_count.fetch_add(1, Ordering::Relaxed);
1599
1600    if old_size > isize::MAX as usize {
1601        crate::abort();
1602    }
1603}
1604
1605unsafe fn release_shared(ptr: *mut Shared) {
1606    // `Shared` storage... follow the drop steps from Arc.
1607    if (*ptr).ref_count.fetch_sub(1, Ordering::Release) != 1 {
1608        return;
1609    }
1610
1611    // This fence is needed to prevent reordering of use of the data and
1612    // deletion of the data.  Because it is marked `Release`, the decreasing
1613    // of the reference count synchronizes with this `Acquire` fence. This
1614    // means that use of the data happens before decreasing the reference
1615    // count, which happens before this fence, which happens before the
1616    // deletion of the data.
1617    //
1618    // As explained in the [Boost documentation][1],
1619    //
1620    // > It is important to enforce any possible access to the object in one
1621    // > thread (through an existing reference) to *happen before* deleting
1622    // > the object in a different thread. This is achieved by a "release"
1623    // > operation after dropping a reference (any access to the object
1624    // > through this reference must obviously happened before), and an
1625    // > "acquire" operation before deleting the object.
1626    //
1627    // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1628    //
1629    // Thread sanitizer does not support atomic fences. Use an atomic load
1630    // instead.
1631    (*ptr).ref_count.load(Ordering::Acquire);
1632
1633    // Drop the data
1634    drop(Box::from_raw(ptr));
1635}
1636
1637impl Shared {
1638    fn is_unique(&self) -> bool {
1639        // The goal is to check if the current handle is the only handle
1640        // that currently has access to the buffer. This is done by
1641        // checking if the `ref_count` is currently 1.
1642        //
1643        // The `Acquire` ordering synchronizes with the `Release` as
1644        // part of the `fetch_sub` in `release_shared`. The `fetch_sub`
1645        // operation guarantees that any mutations done in other threads
1646        // are ordered before the `ref_count` is decremented. As such,
1647        // this `Acquire` will guarantee that those mutations are
1648        // visible to the current thread.
1649        self.ref_count.load(Ordering::Acquire) == 1
1650    }
1651}
1652
1653#[inline]
1654fn original_capacity_to_repr(cap: usize) -> usize {
1655    let width = PTR_WIDTH - ((cap >> MIN_ORIGINAL_CAPACITY_WIDTH).leading_zeros() as usize);
1656    cmp::min(
1657        width,
1658        MAX_ORIGINAL_CAPACITY_WIDTH - MIN_ORIGINAL_CAPACITY_WIDTH,
1659    )
1660}
1661
1662fn original_capacity_from_repr(repr: usize) -> usize {
1663    if repr == 0 {
1664        return 0;
1665    }
1666
1667    1 << (repr + (MIN_ORIGINAL_CAPACITY_WIDTH - 1))
1668}
1669
1670#[cfg(test)]
1671mod tests {
1672    use super::*;
1673
1674    #[test]
1675    fn test_original_capacity_to_repr() {
1676        assert_eq!(original_capacity_to_repr(0), 0);
1677
1678        let max_width = 32;
1679
1680        for width in 1..(max_width + 1) {
1681            let cap = 1 << width - 1;
1682
1683            let expected = if width < MIN_ORIGINAL_CAPACITY_WIDTH {
1684                0
1685            } else if width < MAX_ORIGINAL_CAPACITY_WIDTH {
1686                width - MIN_ORIGINAL_CAPACITY_WIDTH
1687            } else {
1688                MAX_ORIGINAL_CAPACITY_WIDTH - MIN_ORIGINAL_CAPACITY_WIDTH
1689            };
1690
1691            assert_eq!(original_capacity_to_repr(cap), expected);
1692
1693            if width > 1 {
1694                assert_eq!(original_capacity_to_repr(cap + 1), expected);
1695            }
1696
1697            //  MIN_ORIGINAL_CAPACITY_WIDTH must be bigger than 7 to pass tests below
1698            if width == MIN_ORIGINAL_CAPACITY_WIDTH + 1 {
1699                assert_eq!(original_capacity_to_repr(cap - 24), expected - 1);
1700                assert_eq!(original_capacity_to_repr(cap + 76), expected);
1701            } else if width == MIN_ORIGINAL_CAPACITY_WIDTH + 2 {
1702                assert_eq!(original_capacity_to_repr(cap - 1), expected - 1);
1703                assert_eq!(original_capacity_to_repr(cap - 48), expected - 1);
1704            }
1705        }
1706    }
1707
1708    #[test]
1709    fn test_original_capacity_from_repr() {
1710        assert_eq!(0, original_capacity_from_repr(0));
1711
1712        let min_cap = 1 << MIN_ORIGINAL_CAPACITY_WIDTH;
1713
1714        assert_eq!(min_cap, original_capacity_from_repr(1));
1715        assert_eq!(min_cap * 2, original_capacity_from_repr(2));
1716        assert_eq!(min_cap * 4, original_capacity_from_repr(3));
1717        assert_eq!(min_cap * 8, original_capacity_from_repr(4));
1718        assert_eq!(min_cap * 16, original_capacity_from_repr(5));
1719        assert_eq!(min_cap * 32, original_capacity_from_repr(6));
1720        assert_eq!(min_cap * 64, original_capacity_from_repr(7));
1721    }
1722}
1723
1724unsafe impl Send for BytesMut {}
1725unsafe impl Sync for BytesMut {}
1726
1727/*
1728 *
1729 * ===== PartialEq / PartialOrd =====
1730 *
1731 */
1732
1733impl PartialEq<[u8]> for BytesMut {
1734    fn eq(&self, other: &[u8]) -> bool {
1735        &**self == other
1736    }
1737}
1738
1739impl PartialOrd<[u8]> for BytesMut {
1740    fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
1741        (**self).partial_cmp(other)
1742    }
1743}
1744
1745impl PartialEq<BytesMut> for [u8] {
1746    fn eq(&self, other: &BytesMut) -> bool {
1747        *other == *self
1748    }
1749}
1750
1751impl PartialOrd<BytesMut> for [u8] {
1752    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1753        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
1754    }
1755}
1756
1757impl PartialEq<str> for BytesMut {
1758    fn eq(&self, other: &str) -> bool {
1759        &**self == other.as_bytes()
1760    }
1761}
1762
1763impl PartialOrd<str> for BytesMut {
1764    fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1765        (**self).partial_cmp(other.as_bytes())
1766    }
1767}
1768
1769impl PartialEq<BytesMut> for str {
1770    fn eq(&self, other: &BytesMut) -> bool {
1771        *other == *self
1772    }
1773}
1774
1775impl PartialOrd<BytesMut> for str {
1776    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1777        <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
1778    }
1779}
1780
1781impl PartialEq<Vec<u8>> for BytesMut {
1782    fn eq(&self, other: &Vec<u8>) -> bool {
1783        *self == other[..]
1784    }
1785}
1786
1787impl PartialOrd<Vec<u8>> for BytesMut {
1788    fn partial_cmp(&self, other: &Vec<u8>) -> Option<cmp::Ordering> {
1789        (**self).partial_cmp(&other[..])
1790    }
1791}
1792
1793impl PartialEq<BytesMut> for Vec<u8> {
1794    fn eq(&self, other: &BytesMut) -> bool {
1795        *other == *self
1796    }
1797}
1798
1799impl PartialOrd<BytesMut> for Vec<u8> {
1800    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1801        other.partial_cmp(self)
1802    }
1803}
1804
1805impl PartialEq<String> for BytesMut {
1806    fn eq(&self, other: &String) -> bool {
1807        *self == other[..]
1808    }
1809}
1810
1811impl PartialOrd<String> for BytesMut {
1812    fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
1813        (**self).partial_cmp(other.as_bytes())
1814    }
1815}
1816
1817impl PartialEq<BytesMut> for String {
1818    fn eq(&self, other: &BytesMut) -> bool {
1819        *other == *self
1820    }
1821}
1822
1823impl PartialOrd<BytesMut> for String {
1824    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1825        <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
1826    }
1827}
1828
1829impl<'a, T: ?Sized> PartialEq<&'a T> for BytesMut
1830where
1831    BytesMut: PartialEq<T>,
1832{
1833    fn eq(&self, other: &&'a T) -> bool {
1834        *self == **other
1835    }
1836}
1837
1838impl<'a, T: ?Sized> PartialOrd<&'a T> for BytesMut
1839where
1840    BytesMut: PartialOrd<T>,
1841{
1842    fn partial_cmp(&self, other: &&'a T) -> Option<cmp::Ordering> {
1843        self.partial_cmp(*other)
1844    }
1845}
1846
1847impl PartialEq<BytesMut> for &[u8] {
1848    fn eq(&self, other: &BytesMut) -> bool {
1849        *other == *self
1850    }
1851}
1852
1853impl PartialOrd<BytesMut> for &[u8] {
1854    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1855        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
1856    }
1857}
1858
1859impl PartialEq<BytesMut> for &str {
1860    fn eq(&self, other: &BytesMut) -> bool {
1861        *other == *self
1862    }
1863}
1864
1865impl PartialOrd<BytesMut> for &str {
1866    fn partial_cmp(&self, other: &BytesMut) -> Option<cmp::Ordering> {
1867        other.partial_cmp(self)
1868    }
1869}
1870
1871impl PartialEq<BytesMut> for Bytes {
1872    fn eq(&self, other: &BytesMut) -> bool {
1873        other[..] == self[..]
1874    }
1875}
1876
1877impl PartialEq<Bytes> for BytesMut {
1878    fn eq(&self, other: &Bytes) -> bool {
1879        other[..] == self[..]
1880    }
1881}
1882
1883impl From<BytesMut> for Vec<u8> {
1884    fn from(bytes: BytesMut) -> Self {
1885        let kind = bytes.kind();
1886        let bytes = ManuallyDrop::new(bytes);
1887
1888        let mut vec = if kind == KIND_VEC {
1889            unsafe {
1890                let off = bytes.get_vec_pos();
1891                rebuild_vec(bytes.ptr.as_ptr(), bytes.len, bytes.cap, off)
1892            }
1893        } else {
1894            let shared = bytes.data;
1895
1896            if unsafe { (*shared).is_unique() } {
1897                let vec = core::mem::take(unsafe { &mut (*shared).vec });
1898
1899                unsafe { release_shared(shared) };
1900
1901                vec
1902            } else {
1903                return ManuallyDrop::into_inner(bytes).deref().to_vec();
1904            }
1905        };
1906
1907        let len = bytes.len;
1908
1909        unsafe {
1910            ptr::copy(bytes.ptr.as_ptr(), vec.as_mut_ptr(), len);
1911            vec.set_len(len);
1912        }
1913
1914        vec
1915    }
1916}
1917
1918#[inline]
1919fn vptr(ptr: *mut u8) -> NonNull<u8> {
1920    if cfg!(debug_assertions) {
1921        NonNull::new(ptr).expect("Vec pointer should be non-null")
1922    } else {
1923        unsafe { NonNull::new_unchecked(ptr) }
1924    }
1925}
1926
1927/// Returns a dangling pointer with the given address. This is used to store
1928/// integer data in pointer fields.
1929///
1930/// It is equivalent to `addr as *mut T`, but this fails on miri when strict
1931/// provenance checking is enabled.
1932#[inline]
1933fn invalid_ptr<T>(addr: usize) -> *mut T {
1934    let ptr = core::ptr::null_mut::<u8>().wrapping_add(addr);
1935    debug_assert_eq!(ptr as usize, addr);
1936    ptr.cast::<T>()
1937}
1938
1939unsafe fn rebuild_vec(ptr: *mut u8, mut len: usize, mut cap: usize, off: usize) -> Vec<u8> {
1940    let ptr = ptr.sub(off);
1941    len += off;
1942    cap += off;
1943
1944    Vec::from_raw_parts(ptr, len, cap)
1945}
1946
1947// ===== impl SharedVtable =====
1948
1949static SHARED_VTABLE: Vtable = Vtable {
1950    clone: shared_v_clone,
1951    into_vec: shared_v_to_vec,
1952    into_mut: shared_v_to_mut,
1953    is_unique: shared_v_is_unique,
1954    drop: shared_v_drop,
1955};
1956
1957unsafe fn shared_v_clone(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1958    let shared = data.load(Ordering::Relaxed) as *mut Shared;
1959    increment_shared(shared);
1960
1961    let data = AtomicPtr::new(shared as *mut ());
1962    Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE)
1963}
1964
1965unsafe fn shared_v_to_vec(shared: *mut (), ptr: *const u8, len: usize) -> Vec<u8> {
1966    let shared: *mut Shared = shared.cast();
1967
1968    if (*shared).is_unique() {
1969        let shared = &mut *shared;
1970
1971        // Drop shared
1972        let mut vec = core::mem::take(&mut shared.vec);
1973        release_shared(shared);
1974
1975        // Copy back buffer
1976        ptr::copy(ptr, vec.as_mut_ptr(), len);
1977        vec.set_len(len);
1978
1979        vec
1980    } else {
1981        let v = slice::from_raw_parts(ptr, len).to_vec();
1982        release_shared(shared);
1983        v
1984    }
1985}
1986
1987unsafe fn shared_v_to_mut(shared: *mut (), ptr: *const u8, len: usize) -> BytesMut {
1988    let shared: *mut Shared = shared.cast();
1989
1990    if (*shared).is_unique() {
1991        let shared = &mut *shared;
1992
1993        // The capacity is always the original capacity of the buffer
1994        // minus the offset from the start of the buffer
1995        let v = &mut shared.vec;
1996        let v_capacity = v.capacity();
1997        let v_ptr = v.as_mut_ptr();
1998        let offset = ptr.offset_from(v_ptr) as usize;
1999        let cap = v_capacity - offset;
2000
2001        let ptr = vptr(ptr as *mut u8);
2002
2003        BytesMut {
2004            ptr,
2005            len,
2006            cap,
2007            data: shared,
2008        }
2009    } else {
2010        let v = slice::from_raw_parts(ptr, len).to_vec();
2011        release_shared(shared);
2012        BytesMut::from_vec(v)
2013    }
2014}
2015
2016unsafe fn shared_v_is_unique(data: &AtomicPtr<()>) -> bool {
2017    let shared = data.load(Ordering::Acquire);
2018    let ref_count = (*shared.cast::<Shared>()).ref_count.load(Ordering::Relaxed);
2019    ref_count == 1
2020}
2021
2022unsafe fn shared_v_drop(shared: *mut (), _ptr: *const u8, _len: usize) {
2023    release_shared(shared.cast());
2024}
2025
2026// compile-fails
2027
2028/// ```compile_fail
2029/// use bytes::BytesMut;
2030/// #[deny(unused_must_use)]
2031/// {
2032///     let mut b1 = BytesMut::from("hello world");
2033///     b1.split_to(6);
2034/// }
2035/// ```
2036fn _split_to_must_use() {}
2037
2038/// ```compile_fail
2039/// use bytes::BytesMut;
2040/// #[deny(unused_must_use)]
2041/// {
2042///     let mut b1 = BytesMut::from("hello world");
2043///     b1.split_off(6);
2044/// }
2045/// ```
2046fn _split_off_must_use() {}
2047
2048/// ```compile_fail
2049/// use bytes::BytesMut;
2050/// #[deny(unused_must_use)]
2051/// {
2052///     let mut b1 = BytesMut::from("hello world");
2053///     b1.split();
2054/// }
2055/// ```
2056fn _split_must_use() {}
2057
2058// fuzz tests
2059#[cfg(all(test, loom))]
2060mod fuzz {
2061    use loom::sync::Arc;
2062    use loom::thread;
2063
2064    use super::BytesMut;
2065    use crate::Bytes;
2066
2067    #[test]
2068    fn bytes_mut_cloning_frozen() {
2069        loom::model(|| {
2070            let a = BytesMut::from(&b"abcdefgh"[..]).split().freeze();
2071            let addr = a.as_ptr() as usize;
2072
2073            // test the Bytes::clone is Sync by putting it in an Arc
2074            let a1 = Arc::new(a);
2075            let a2 = a1.clone();
2076
2077            let t1 = thread::spawn(move || {
2078                let b: Bytes = (*a1).clone();
2079                assert_eq!(b.as_ptr() as usize, addr);
2080            });
2081
2082            let t2 = thread::spawn(move || {
2083                let b: Bytes = (*a2).clone();
2084                assert_eq!(b.as_ptr() as usize, addr);
2085            });
2086
2087            t1.join().unwrap();
2088            t2.join().unwrap();
2089        });
2090    }
2091}