Coverage Report

Created: 2026-07-16 07:06

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