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