Coverage Report

Created: 2026-07-16 07:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/smallvec-1.15.1/src/lib.rs
Line
Count
Source
1
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4
// option. This file may not be copied, modified, or distributed
5
// except according to those terms.
6
7
//! Small vectors in various sizes. These store a certain number of elements inline, and fall back
8
//! to the heap for larger allocations.  This can be a useful optimization for improving cache
9
//! locality and reducing allocator traffic for workloads that fit within the inline buffer.
10
//!
11
//! ## `no_std` support
12
//!
13
//! By default, `smallvec` does not depend on `std`.  However, the optional
14
//! `write` feature implements the `std::io::Write` trait for vectors of `u8`.
15
//! When this feature is enabled, `smallvec` depends on `std`.
16
//!
17
//! ## Optional features
18
//!
19
//! ### `serde`
20
//!
21
//! When this optional dependency is enabled, `SmallVec` implements the `serde::Serialize` and
22
//! `serde::Deserialize` traits.
23
//!
24
//! ### `write`
25
//!
26
//! When this feature is enabled, `SmallVec<[u8; _]>` implements the `std::io::Write` trait.
27
//! This feature is not compatible with `#![no_std]` programs.
28
//!
29
//! ### `union`
30
//!
31
//! **This feature requires Rust 1.49.**
32
//!
33
//! When the `union` feature is enabled `smallvec` will track its state (inline or spilled)
34
//! without the use of an enum tag, reducing the size of the `smallvec` by one machine word.
35
//! This means that there is potentially no space overhead compared to `Vec`.
36
//! Note that `smallvec` can still be larger than `Vec` if the inline buffer is larger than two
37
//! machine words.
38
//!
39
//! To use this feature add `features = ["union"]` in the `smallvec` section of Cargo.toml.
40
//! Note that this feature requires Rust 1.49.
41
//!
42
//! Tracking issue: [rust-lang/rust#55149](https://github.com/rust-lang/rust/issues/55149)
43
//!
44
//! ### `const_generics`
45
//!
46
//! **This feature requires Rust 1.51.**
47
//!
48
//! When this feature is enabled, `SmallVec` works with any arrays of any size, not just a fixed
49
//! list of sizes.
50
//!
51
//! ### `const_new`
52
//!
53
//! **This feature requires Rust 1.51.**
54
//!
55
//! This feature exposes the functions [`SmallVec::new_const`], [`SmallVec::from_const`], and [`smallvec_inline`] which enables the `SmallVec` to be initialized from a const context.
56
//! For details, see the
57
//! [Rust Reference](https://doc.rust-lang.org/reference/const_eval.html#const-functions).
58
//!
59
//! ### `drain_filter`
60
//!
61
//! **This feature is unstable.** It may change to match the unstable `drain_filter` method in libstd.
62
//!
63
//! Enables the `drain_filter` method, which produces an iterator that calls a user-provided
64
//! closure to determine which elements of the vector to remove and yield from the iterator.
65
//!
66
//! ### `drain_keep_rest`
67
//!
68
//! **This feature is unstable.** It may change to match the unstable `drain_keep_rest` method in libstd.
69
//!
70
//! Enables the `DrainFilter::keep_rest` method.
71
//!
72
//! ### `specialization`
73
//!
74
//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
75
//!
76
//! When this feature is enabled, `SmallVec::from(slice)` has improved performance for slices
77
//! of `Copy` types.  (Without this feature, you can use `SmallVec::from_slice` to get optimal
78
//! performance for `Copy` types.)
79
//!
80
//! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844)
81
//!
82
//! ### `may_dangle`
83
//!
84
//! **This feature is unstable and requires a nightly build of the Rust toolchain.**
85
//!
86
//! This feature makes the Rust compiler less strict about use of vectors that contain borrowed
87
//! references. For details, see the
88
//! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch).
89
//!
90
//! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761)
91
92
#![no_std]
93
#![cfg_attr(docsrs, feature(doc_cfg))]
94
#![cfg_attr(feature = "specialization", allow(incomplete_features))]
95
#![cfg_attr(feature = "specialization", feature(specialization))]
96
#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
97
#![cfg_attr(
98
    feature = "debugger_visualizer",
99
    feature(debugger_visualizer),
100
    debugger_visualizer(natvis_file = "../debug_metadata/smallvec.natvis")
101
)]
102
#![deny(missing_docs)]
103
104
#[doc(hidden)]
105
pub extern crate alloc;
106
107
#[cfg(any(test, feature = "write"))]
108
extern crate std;
109
110
#[cfg(test)]
111
mod tests;
112
113
#[allow(deprecated)]
114
use alloc::alloc::{Layout, LayoutErr};
115
use alloc::boxed::Box;
116
use alloc::{vec, vec::Vec};
117
use core::borrow::{Borrow, BorrowMut};
118
use core::cmp;
119
use core::fmt;
120
use core::hash::{Hash, Hasher};
121
use core::hint::unreachable_unchecked;
122
use core::iter::{repeat, FromIterator, FusedIterator, IntoIterator};
123
use core::mem;
124
use core::mem::MaybeUninit;
125
use core::ops::{self, Range, RangeBounds};
126
use core::ptr::{self, NonNull};
127
use core::slice::{self, SliceIndex};
128
129
#[cfg(feature = "malloc_size_of")]
130
use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
131
132
#[cfg(feature = "serde")]
133
use serde::{
134
    de::{Deserialize, Deserializer, SeqAccess, Visitor},
135
    ser::{Serialize, SerializeSeq, Serializer},
136
};
137
138
#[cfg(feature = "serde")]
139
use core::marker::PhantomData;
140
141
#[cfg(feature = "write")]
142
use std::io;
143
144
#[cfg(feature = "drain_keep_rest")]
145
use core::mem::ManuallyDrop;
146
147
/// Creates a [`SmallVec`] containing the arguments.
148
///
149
/// `smallvec!` allows `SmallVec`s to be defined with the same syntax as array expressions.
150
/// There are two forms of this macro:
151
///
152
/// - Create a [`SmallVec`] containing a given list of elements:
153
///
154
/// ```
155
/// # use smallvec::{smallvec, SmallVec};
156
/// # fn main() {
157
/// let v: SmallVec<[_; 128]> = smallvec![1, 2, 3];
158
/// assert_eq!(v[0], 1);
159
/// assert_eq!(v[1], 2);
160
/// assert_eq!(v[2], 3);
161
/// # }
162
/// ```
163
///
164
/// - Create a [`SmallVec`] from a given element and size:
165
///
166
/// ```
167
/// # use smallvec::{smallvec, SmallVec};
168
/// # fn main() {
169
/// let v: SmallVec<[_; 0x8000]> = smallvec![1; 3];
170
/// assert_eq!(v, SmallVec::from_buf([1, 1, 1]));
171
/// # }
172
/// ```
173
///
174
/// Note that unlike array expressions this syntax supports all elements
175
/// which implement [`Clone`] and the number of elements doesn't have to be
176
/// a constant.
177
///
178
/// This will use `clone` to duplicate an expression, so one should be careful
179
/// using this with types having a nonstandard `Clone` implementation. For
180
/// example, `smallvec![Rc::new(1); 5]` will create a vector of five references
181
/// to the same boxed integer value, not five references pointing to independently
182
/// boxed integers.
183
#[macro_export]
184
macro_rules! smallvec {
185
    // count helper: transform any expression into 1
186
    (@one $x:expr) => (1usize);
187
    () => (
188
        $crate::SmallVec::new()
189
    );
190
    ($elem:expr; $n:expr) => ({
191
        $crate::SmallVec::from_elem($elem, $n)
192
    });
193
    ($($x:expr),+$(,)?) => ({
194
        let count = 0usize $(+ $crate::smallvec!(@one $x))+;
195
        let mut vec = $crate::SmallVec::new();
196
        if count <= vec.inline_size() {
197
            $(vec.push($x);)*
198
            vec
199
        } else {
200
            $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
201
        }
202
    });
203
}
204
205
/// Creates an inline [`SmallVec`] containing the arguments. This macro is enabled by the feature `const_new`.
206
///
207
/// `smallvec_inline!` allows `SmallVec`s to be defined with the same syntax as array expressions in `const` contexts.
208
/// The inline storage `A` will always be an array of the size specified by the arguments.
209
/// There are two forms of this macro:
210
///
211
/// - Create a [`SmallVec`] containing a given list of elements:
212
///
213
/// ```
214
/// # use smallvec::{smallvec_inline, SmallVec};
215
/// # fn main() {
216
/// const V: SmallVec<[i32; 3]> = smallvec_inline![1, 2, 3];
217
/// assert_eq!(V[0], 1);
218
/// assert_eq!(V[1], 2);
219
/// assert_eq!(V[2], 3);
220
/// # }
221
/// ```
222
///
223
/// - Create a [`SmallVec`] from a given element and size:
224
///
225
/// ```
226
/// # use smallvec::{smallvec_inline, SmallVec};
227
/// # fn main() {
228
/// const V: SmallVec<[i32; 3]> = smallvec_inline![1; 3];
229
/// assert_eq!(V, SmallVec::from_buf([1, 1, 1]));
230
/// # }
231
/// ```
232
///
233
/// Note that the behavior mimics that of array expressions, in contrast to [`smallvec`].
234
#[cfg(feature = "const_new")]
235
#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
236
#[macro_export]
237
macro_rules! smallvec_inline {
238
    // count helper: transform any expression into 1
239
    (@one $x:expr) => (1usize);
240
    ($elem:expr; $n:expr) => ({
241
        $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
242
    });
243
    ($($x:expr),+ $(,)?) => ({
244
        const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
245
        $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
246
    });
247
}
248
249
/// `panic!()` in debug builds, optimization hint in release.
250
#[cfg(not(feature = "union"))]
251
macro_rules! debug_unreachable {
252
    () => {
253
        debug_unreachable!("entered unreachable code")
254
    };
255
    ($e:expr) => {
256
        if cfg!(debug_assertions) {
257
            panic!($e);
258
        } else {
259
            unreachable_unchecked();
260
        }
261
    };
262
}
263
264
/// Trait to be implemented by a collection that can be extended from a slice
265
///
266
/// ## Example
267
///
268
/// ```rust
269
/// use smallvec::{ExtendFromSlice, SmallVec};
270
///
271
/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
272
///     v.extend_from_slice(b"Test!");
273
/// }
274
///
275
/// let mut vec = Vec::new();
276
/// initialize(&mut vec);
277
/// assert_eq!(&vec, b"Test!");
278
///
279
/// let mut small_vec = SmallVec::<[u8; 8]>::new();
280
/// initialize(&mut small_vec);
281
/// assert_eq!(&small_vec as &[_], b"Test!");
282
/// ```
283
#[doc(hidden)]
284
#[deprecated]
285
pub trait ExtendFromSlice<T> {
286
    /// Extends a collection from a slice of its element type
287
    fn extend_from_slice(&mut self, other: &[T]);
288
}
289
290
#[allow(deprecated)]
291
impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
292
0
    fn extend_from_slice(&mut self, other: &[T]) {
293
0
        Vec::extend_from_slice(self, other)
294
0
    }
295
}
296
297
/// Error type for APIs with fallible heap allocation
298
#[derive(Debug)]
299
pub enum CollectionAllocErr {
300
    /// Overflow `usize::MAX` or other error during size computation
301
    CapacityOverflow,
302
    /// The allocator return an error
303
    AllocErr {
304
        /// The layout that was passed to the allocator
305
        layout: Layout,
306
    },
307
}
308
309
impl fmt::Display for CollectionAllocErr {
310
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311
0
        write!(f, "Allocation error: {:?}", self)
312
0
    }
313
}
314
315
#[allow(deprecated)]
316
impl From<LayoutErr> for CollectionAllocErr {
317
0
    fn from(_: LayoutErr) -> Self {
318
0
        CollectionAllocErr::CapacityOverflow
319
0
    }
320
}
321
322
1.63M
fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
323
0
    match result {
324
1.63M
        Ok(x) => x,
325
0
        Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
326
0
        Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
327
    }
328
1.63M
}
smallvec::infallible::<()>
Line
Count
Source
322
1.63M
fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
323
0
    match result {
324
1.63M
        Ok(x) => x,
325
0
        Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
326
0
        Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
327
    }
328
1.63M
}
Unexecuted instantiation: smallvec::infallible::<_>
329
330
/// FIXME: use `Layout::array` when we require a Rust version where it’s stable
331
/// <https://github.com/rust-lang/rust/issues/55724>
332
1.67M
fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
333
1.67M
    let size = mem::size_of::<T>()
334
1.67M
        .checked_mul(n)
335
1.67M
        .ok_or(CollectionAllocErr::CapacityOverflow)?;
336
1.67M
    let align = mem::align_of::<T>();
337
1.67M
    Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
338
1.67M
}
smallvec::layout_array::<idna::uts46::AlreadyAsciiLabel>
Line
Count
Source
332
32.5k
fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
333
32.5k
    let size = mem::size_of::<T>()
334
32.5k
        .checked_mul(n)
335
32.5k
        .ok_or(CollectionAllocErr::CapacityOverflow)?;
336
32.5k
    let align = mem::align_of::<T>();
337
32.5k
    Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
338
32.5k
}
smallvec::layout_array::<(usize, char)>
Line
Count
Source
332
1.29M
fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
333
1.29M
    let size = mem::size_of::<T>()
334
1.29M
        .checked_mul(n)
335
1.29M
        .ok_or(CollectionAllocErr::CapacityOverflow)?;
336
1.29M
    let align = mem::align_of::<T>();
337
1.29M
    Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
338
1.29M
}
smallvec::layout_array::<char>
Line
Count
Source
332
325k
fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
333
325k
    let size = mem::size_of::<T>()
334
325k
        .checked_mul(n)
335
325k
        .ok_or(CollectionAllocErr::CapacityOverflow)?;
336
325k
    let align = mem::align_of::<T>();
337
325k
    Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
338
325k
}
smallvec::layout_array::<icu_normalizer::CharacterAndClass>
Line
Count
Source
332
25.1k
fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
333
25.1k
    let size = mem::size_of::<T>()
334
25.1k
        .checked_mul(n)
335
25.1k
        .ok_or(CollectionAllocErr::CapacityOverflow)?;
336
25.1k
    let align = mem::align_of::<T>();
337
25.1k
    Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
338
25.1k
}
Unexecuted instantiation: smallvec::layout_array::<_>
339
340
0
unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
341
    // This unwrap should succeed since the same did when allocating.
342
0
    let layout = layout_array::<T>(capacity).unwrap();
343
0
    alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
344
0
}
Unexecuted instantiation: smallvec::deallocate::<idna::uts46::AlreadyAsciiLabel>
Unexecuted instantiation: smallvec::deallocate::<(usize, char)>
Unexecuted instantiation: smallvec::deallocate::<char>
Unexecuted instantiation: smallvec::deallocate::<icu_normalizer::CharacterAndClass>
Unexecuted instantiation: smallvec::deallocate::<_>
345
346
/// An iterator that removes the items from a `SmallVec` and yields them by value.
347
///
348
/// Returned from [`SmallVec::drain`][1].
349
///
350
/// [1]: struct.SmallVec.html#method.drain
351
pub struct Drain<'a, T: 'a + Array> {
352
    tail_start: usize,
353
    tail_len: usize,
354
    iter: slice::Iter<'a, T::Item>,
355
    vec: NonNull<SmallVec<T>>,
356
}
357
358
impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
359
where
360
    T::Item: fmt::Debug,
361
{
362
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363
0
        f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
364
0
    }
365
}
366
367
unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
368
unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
369
370
impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
371
    type Item = T::Item;
372
373
    #[inline]
374
439k
    fn next(&mut self) -> Option<T::Item> {
375
439k
        self.iter
376
439k
            .next()
377
439k
            .map(|reference| unsafe { ptr::read(reference) })
<smallvec::Drain<[icu_normalizer::CharacterAndClass; 17]> as core::iter::traits::iterator::Iterator>::next::{closure#0}
Line
Count
Source
377
61.3k
            .map(|reference| unsafe { ptr::read(reference) })
Unexecuted instantiation: <smallvec::Drain<_> as core::iter::traits::iterator::Iterator>::next::{closure#0}
378
439k
    }
<smallvec::Drain<[icu_normalizer::CharacterAndClass; 17]> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
374
439k
    fn next(&mut self) -> Option<T::Item> {
375
439k
        self.iter
376
439k
            .next()
377
439k
            .map(|reference| unsafe { ptr::read(reference) })
378
439k
    }
Unexecuted instantiation: <smallvec::Drain<_> as core::iter::traits::iterator::Iterator>::next
379
380
    #[inline]
381
0
    fn size_hint(&self) -> (usize, Option<usize>) {
382
0
        self.iter.size_hint()
383
0
    }
384
}
385
386
impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
387
    #[inline]
388
0
    fn next_back(&mut self) -> Option<T::Item> {
389
0
        self.iter
390
0
            .next_back()
391
0
            .map(|reference| unsafe { ptr::read(reference) })
392
0
    }
393
}
394
395
impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
396
    #[inline]
397
0
    fn len(&self) -> usize {
398
0
        self.iter.len()
399
0
    }
400
}
401
402
impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
403
404
impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
405
378k
    fn drop(&mut self) {
406
378k
        self.for_each(drop);
407
408
378k
        if self.tail_len > 0 {
409
            unsafe {
410
378k
                let source_vec = self.vec.as_mut();
411
412
                // memmove back untouched tail, update to new length
413
378k
                let start = source_vec.len();
414
378k
                let tail = self.tail_start;
415
378k
                if tail != start {
416
53.0k
                    // as_mut_ptr creates a &mut, invalidating other pointers.
417
53.0k
                    // This pattern avoids calling it with a pointer already present.
418
53.0k
                    let ptr = source_vec.as_mut_ptr();
419
53.0k
                    let src = ptr.add(tail);
420
53.0k
                    let dst = ptr.add(start);
421
53.0k
                    ptr::copy(src, dst, self.tail_len);
422
325k
                }
423
378k
                source_vec.set_len(start + self.tail_len);
424
            }
425
0
        }
426
378k
    }
<smallvec::Drain<[icu_normalizer::CharacterAndClass; 17]> as core::ops::drop::Drop>::drop
Line
Count
Source
405
378k
    fn drop(&mut self) {
406
378k
        self.for_each(drop);
407
408
378k
        if self.tail_len > 0 {
409
            unsafe {
410
378k
                let source_vec = self.vec.as_mut();
411
412
                // memmove back untouched tail, update to new length
413
378k
                let start = source_vec.len();
414
378k
                let tail = self.tail_start;
415
378k
                if tail != start {
416
53.0k
                    // as_mut_ptr creates a &mut, invalidating other pointers.
417
53.0k
                    // This pattern avoids calling it with a pointer already present.
418
53.0k
                    let ptr = source_vec.as_mut_ptr();
419
53.0k
                    let src = ptr.add(tail);
420
53.0k
                    let dst = ptr.add(start);
421
53.0k
                    ptr::copy(src, dst, self.tail_len);
422
325k
                }
423
378k
                source_vec.set_len(start + self.tail_len);
424
            }
425
0
        }
426
378k
    }
Unexecuted instantiation: <smallvec::Drain<_> as core::ops::drop::Drop>::drop
427
}
428
429
#[cfg(feature = "drain_filter")]
430
/// An iterator which uses a closure to determine if an element should be removed.
431
///
432
/// Returned from [`SmallVec::drain_filter`][1].
433
///
434
/// [1]: struct.SmallVec.html#method.drain_filter
435
pub struct DrainFilter<'a, T, F>
436
where
437
    F: FnMut(&mut T::Item) -> bool,
438
    T: Array,
439
{
440
    vec: &'a mut SmallVec<T>,
441
    /// The index of the item that will be inspected by the next call to `next`.
442
    idx: usize,
443
    /// The number of items that have been drained (removed) thus far.
444
    del: usize,
445
    /// The original length of `vec` prior to draining.
446
    old_len: usize,
447
    /// The filter test predicate.
448
    pred: F,
449
    /// A flag that indicates a panic has occurred in the filter test predicate.
450
    /// This is used as a hint in the drop implementation to prevent consumption
451
    /// of the remainder of the `DrainFilter`. Any unprocessed items will be
452
    /// backshifted in the `vec`, but no further items will be dropped or
453
    /// tested by the filter predicate.
454
    panic_flag: bool,
455
}
456
457
#[cfg(feature = "drain_filter")]
458
impl <T, F> fmt::Debug for DrainFilter<'_, T, F>
459
where
460
    F: FnMut(&mut T::Item) -> bool,
461
    T: Array,
462
    T::Item: fmt::Debug,
463
{
464
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465
        f.debug_tuple("DrainFilter").field(&self.vec.as_slice()).finish()
466
    }
467
}
468
469
#[cfg(feature = "drain_filter")]
470
impl <T, F> Iterator for DrainFilter<'_, T, F>
471
where
472
    F: FnMut(&mut T::Item) -> bool,
473
    T: Array,
474
{
475
    type Item = T::Item;
476
477
    fn next(&mut self) -> Option<T::Item>
478
    {
479
        unsafe {
480
            while self.idx < self.old_len {
481
                let i = self.idx;
482
                let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
483
                self.panic_flag = true;
484
                let drained = (self.pred)(&mut v[i]);
485
                self.panic_flag = false;
486
                // Update the index *after* the predicate is called. If the index
487
                // is updated prior and the predicate panics, the element at this
488
                // index would be leaked.
489
                self.idx += 1;
490
                if drained {
491
                    self.del += 1;
492
                    return Some(ptr::read(&v[i]));
493
                } else if self.del > 0 {
494
                    let del = self.del;
495
                    let src: *const Self::Item = &v[i];
496
                    let dst: *mut Self::Item = &mut v[i - del];
497
                    ptr::copy_nonoverlapping(src, dst, 1);
498
                }
499
            }
500
            None
501
        }
502
    }
503
504
    fn size_hint(&self) -> (usize, Option<usize>) {
505
        (0, Some(self.old_len - self.idx))
506
    }
507
}
508
509
#[cfg(feature = "drain_filter")]
510
impl <T, F> Drop for DrainFilter<'_, T, F>
511
where
512
    F: FnMut(&mut T::Item) -> bool,
513
    T: Array,
514
{
515
    fn drop(&mut self) {
516
        struct BackshiftOnDrop<'a, 'b, T, F>
517
        where
518
            F: FnMut(&mut T::Item) -> bool,
519
            T: Array
520
        {
521
            drain: &'b mut DrainFilter<'a, T, F>,
522
        }
523
524
        impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
525
        where
526
            F: FnMut(&mut T::Item) -> bool,
527
            T: Array
528
        {
529
            fn drop(&mut self) {
530
                unsafe {
531
                    if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
532
                        // This is a pretty messed up state, and there isn't really an
533
                        // obviously right thing to do. We don't want to keep trying
534
                        // to execute `pred`, so we just backshift all the unprocessed
535
                        // elements and tell the vec that they still exist. The backshift
536
                        // is required to prevent a double-drop of the last successfully
537
                        // drained item prior to a panic in the predicate.
538
                        let ptr = self.drain.vec.as_mut_ptr();
539
                        let src = ptr.add(self.drain.idx);
540
                        let dst = src.sub(self.drain.del);
541
                        let tail_len = self.drain.old_len - self.drain.idx;
542
                        src.copy_to(dst, tail_len);
543
                    }
544
                    self.drain.vec.set_len(self.drain.old_len - self.drain.del);
545
                }
546
            }
547
        }
548
549
        let backshift = BackshiftOnDrop { drain: self };
550
551
        // Attempt to consume any remaining elements if the filter predicate
552
        // has not yet panicked. We'll backshift any remaining elements
553
        // whether we've already panicked or if the consumption here panics.
554
        if !backshift.drain.panic_flag {
555
            backshift.drain.for_each(drop);
556
        }
557
    }
558
}
559
560
#[cfg(feature = "drain_keep_rest")]
561
impl <T, F> DrainFilter<'_, T, F>
562
where
563
    F: FnMut(&mut T::Item) -> bool,
564
    T: Array
565
{
566
    /// Keep unyielded elements in the source `Vec`.
567
    ///
568
    /// # Examples
569
    ///
570
    /// ```
571
    /// # use smallvec::{smallvec, SmallVec};
572
    ///
573
    /// let mut vec: SmallVec<[char; 2]> = smallvec!['a', 'b', 'c'];
574
    /// let mut drain = vec.drain_filter(|_| true);
575
    ///
576
    /// assert_eq!(drain.next().unwrap(), 'a');
577
    ///
578
    /// // This call keeps 'b' and 'c' in the vec.
579
    /// drain.keep_rest();
580
    ///
581
    /// // If we wouldn't call `keep_rest()`,
582
    /// // `vec` would be empty.
583
    /// assert_eq!(vec, SmallVec::<[char; 2]>::from_slice(&['b', 'c']));
584
    /// ```
585
    pub fn keep_rest(self)
586
    {
587
        // At this moment layout looks like this:
588
        //
589
        //  _____________________/-- old_len
590
        // /                     \
591
        // [kept] [yielded] [tail]
592
        //        \_______/ ^-- idx
593
        //                \-- del
594
        //
595
        // Normally `Drop` impl would drop [tail] (via .for_each(drop), ie still calling `pred`)
596
        //
597
        // 1. Move [tail] after [kept]
598
        // 2. Update length of the original vec to `old_len - del`
599
        //    a. In case of ZST, this is the only thing we want to do
600
        // 3. Do *not* drop self, as everything is put in a consistent state already, there is nothing to do
601
        let mut this = ManuallyDrop::new(self);
602
603
        unsafe {
604
            // ZSTs have no identity, so we don't need to move them around.
605
            let needs_move = mem::size_of::<T>() != 0;
606
607
            if needs_move && this.idx < this.old_len && this.del > 0 {
608
                let ptr = this.vec.as_mut_ptr();
609
                let src = ptr.add(this.idx);
610
                let dst = src.sub(this.del);
611
                let tail_len = this.old_len - this.idx;
612
                src.copy_to(dst, tail_len);
613
            }
614
615
            let new_len = this.old_len - this.del;
616
            this.vec.set_len(new_len);
617
        }
618
    }
619
}
620
621
#[cfg(feature = "union")]
622
union SmallVecData<A: Array> {
623
    inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
624
    heap: (NonNull<A::Item>, usize),
625
}
626
627
#[cfg(all(feature = "union", feature = "const_new"))]
628
impl<T, const N: usize> SmallVecData<[T; N]> {
629
    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
630
    #[inline]
631
    const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
632
        SmallVecData {
633
            inline: core::mem::ManuallyDrop::new(inline),
634
        }
635
    }
636
}
637
638
#[cfg(feature = "union")]
639
impl<A: Array> SmallVecData<A> {
640
    #[inline]
641
    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
642
        ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
643
    }
644
    #[inline]
645
    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
646
        NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
647
    }
648
    #[inline]
649
    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
650
        SmallVecData {
651
            inline: core::mem::ManuallyDrop::new(inline),
652
        }
653
    }
654
    #[inline]
655
    unsafe fn into_inline(self) -> MaybeUninit<A> {
656
        core::mem::ManuallyDrop::into_inner(self.inline)
657
    }
658
    #[inline]
659
    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
660
        (ConstNonNull(self.heap.0), self.heap.1)
661
    }
662
    #[inline]
663
    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
664
        let h = &mut self.heap;
665
        (h.0, &mut h.1)
666
    }
667
    #[inline]
668
    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
669
        SmallVecData { heap: (ptr, len) }
670
    }
671
}
672
673
#[cfg(not(feature = "union"))]
674
enum SmallVecData<A: Array> {
675
    Inline(MaybeUninit<A>),
676
    // Using NonNull and NonZero here allows to reduce size of `SmallVec`.
677
    Heap {
678
        // Since we never allocate on heap
679
        // unless our capacity is bigger than inline capacity
680
        // heap capacity cannot be less than 1.
681
        // Therefore, pointer cannot be null too.
682
        ptr: NonNull<A::Item>,
683
        len: usize,
684
    },
685
}
686
687
#[cfg(all(not(feature = "union"), feature = "const_new"))]
688
impl<T, const N: usize> SmallVecData<[T; N]> {
689
    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
690
    #[inline]
691
0
    const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
692
0
        SmallVecData::Inline(inline)
693
0
    }
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::from_const
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::from_const
Unexecuted instantiation: <smallvec::SmallVecData<[_; _]>>::from_const
694
}
695
696
#[cfg(not(feature = "union"))]
697
impl<A: Array> SmallVecData<A> {
698
    #[inline]
699
103M
    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
700
103M
        match self {
701
103M
            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
702
0
            _ => debug_unreachable!(),
703
        }
704
103M
    }
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::inline
<smallvec::SmallVecData<[idna::uts46::AlreadyAsciiLabel; 8]>>::inline
Line
Count
Source
699
8.66k
    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
700
8.66k
        match self {
701
8.66k
            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
702
0
            _ => debug_unreachable!(),
703
        }
704
8.66k
    }
<smallvec::SmallVecData<[(usize, char); 59]>>::inline
Line
Count
Source
699
1.25M
    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
700
1.25M
        match self {
701
1.25M
            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
702
0
            _ => debug_unreachable!(),
703
        }
704
1.25M
    }
<smallvec::SmallVecData<[char; 59]>>::inline
Line
Count
Source
699
486k
    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
700
486k
        match self {
701
486k
            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
702
0
            _ => debug_unreachable!(),
703
        }
704
486k
    }
<smallvec::SmallVecData<[char; 253]>>::inline
Line
Count
Source
699
270k
    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
700
270k
        match self {
701
270k
            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
702
0
            _ => debug_unreachable!(),
703
        }
704
270k
    }
<smallvec::SmallVecData<[icu_normalizer::CharacterAndClass; 17]>>::inline
Line
Count
Source
699
101M
    unsafe fn inline(&self) -> ConstNonNull<A::Item> {
700
101M
        match self {
701
101M
            SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
702
0
            _ => debug_unreachable!(),
703
        }
704
101M
    }
Unexecuted instantiation: <smallvec::SmallVecData<_>>::inline
705
    #[inline]
706
70.1M
    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
707
70.1M
        match self {
708
70.1M
            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
709
0
            _ => debug_unreachable!(),
710
        }
711
70.1M
    }
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::inline_mut
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::inline_mut
<smallvec::SmallVecData<[idna::uts46::AlreadyAsciiLabel; 8]>>::inline_mut
Line
Count
Source
706
62.0k
    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
707
62.0k
        match self {
708
62.0k
            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
709
0
            _ => debug_unreachable!(),
710
        }
711
62.0k
    }
<smallvec::SmallVecData<[(usize, char); 59]>>::inline_mut
Line
Count
Source
706
50.3M
    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
707
50.3M
        match self {
708
50.3M
            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
709
0
            _ => debug_unreachable!(),
710
        }
711
50.3M
    }
<smallvec::SmallVecData<[char; 59]>>::inline_mut
Line
Count
Source
706
2.01M
    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
707
2.01M
        match self {
708
2.01M
            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
709
0
            _ => debug_unreachable!(),
710
        }
711
2.01M
    }
<smallvec::SmallVecData<[char; 253]>>::inline_mut
Line
Count
Source
706
2.19M
    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
707
2.19M
        match self {
708
2.19M
            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
709
0
            _ => debug_unreachable!(),
710
        }
711
2.19M
    }
<smallvec::SmallVecData<[icu_normalizer::CharacterAndClass; 17]>>::inline_mut
Line
Count
Source
706
15.4M
    unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
707
15.4M
        match self {
708
15.4M
            SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
709
0
            _ => debug_unreachable!(),
710
        }
711
15.4M
    }
Unexecuted instantiation: <smallvec::SmallVecData<_>>::inline_mut
712
    #[inline]
713
2.79M
    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
714
2.79M
        SmallVecData::Inline(inline)
715
2.79M
    }
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::from_inline
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::from_inline
<smallvec::SmallVecData<[idna::uts46::AlreadyAsciiLabel; 8]>>::from_inline
Line
Count
Source
713
17.3k
    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
714
17.3k
        SmallVecData::Inline(inline)
715
17.3k
    }
<smallvec::SmallVecData<[(usize, char); 59]>>::from_inline
Line
Count
Source
713
766k
    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
714
766k
        SmallVecData::Inline(inline)
715
766k
    }
<smallvec::SmallVecData<[char; 59]>>::from_inline
Line
Count
Source
713
766k
    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
714
766k
        SmallVecData::Inline(inline)
715
766k
    }
<smallvec::SmallVecData<[char; 253]>>::from_inline
Line
Count
Source
713
17.3k
    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
714
17.3k
        SmallVecData::Inline(inline)
715
17.3k
    }
<smallvec::SmallVecData<[icu_normalizer::CharacterAndClass; 17]>>::from_inline
Line
Count
Source
713
1.22M
    fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
714
1.22M
        SmallVecData::Inline(inline)
715
1.22M
    }
Unexecuted instantiation: <smallvec::SmallVecData<_>>::from_inline
716
    #[inline]
717
0
    unsafe fn into_inline(self) -> MaybeUninit<A> {
718
0
        match self {
719
0
            SmallVecData::Inline(a) => a,
720
0
            _ => debug_unreachable!(),
721
        }
722
0
    }
723
    #[inline]
724
32.0M
    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
725
32.0M
        match self {
726
32.0M
            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
727
0
            _ => debug_unreachable!(),
728
        }
729
32.0M
    }
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::heap
<smallvec::SmallVecData<[idna::uts46::AlreadyAsciiLabel; 8]>>::heap
Line
Count
Source
724
17.2k
    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
725
17.2k
        match self {
726
17.2k
            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
727
0
            _ => debug_unreachable!(),
728
        }
729
17.2k
    }
<smallvec::SmallVecData<[(usize, char); 59]>>::heap
Line
Count
Source
724
1.06M
    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
725
1.06M
        match self {
726
1.06M
            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
727
0
            _ => debug_unreachable!(),
728
        }
729
1.06M
    }
<smallvec::SmallVecData<[char; 59]>>::heap
Line
Count
Source
724
279k
    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
725
279k
        match self {
726
279k
            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
727
0
            _ => debug_unreachable!(),
728
        }
729
279k
    }
<smallvec::SmallVecData<[char; 253]>>::heap
Line
Count
Source
724
25.4M
    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
725
25.4M
        match self {
726
25.4M
            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
727
0
            _ => debug_unreachable!(),
728
        }
729
25.4M
    }
<smallvec::SmallVecData<[icu_normalizer::CharacterAndClass; 17]>>::heap
Line
Count
Source
724
5.24M
    unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
725
5.24M
        match self {
726
5.24M
            SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
727
0
            _ => debug_unreachable!(),
728
        }
729
5.24M
    }
Unexecuted instantiation: <smallvec::SmallVecData<_>>::heap
730
    #[inline]
731
276M
    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
732
276M
        match self {
733
276M
            SmallVecData::Heap { ptr, len } => (*ptr, len),
734
0
            _ => debug_unreachable!(),
735
        }
736
276M
    }
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::heap_mut
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::heap_mut
<smallvec::SmallVecData<[idna::uts46::AlreadyAsciiLabel; 8]>>::heap_mut
Line
Count
Source
731
24.6M
    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
732
24.6M
        match self {
733
24.6M
            SmallVecData::Heap { ptr, len } => (*ptr, len),
734
0
            _ => debug_unreachable!(),
735
        }
736
24.6M
    }
<smallvec::SmallVecData<[(usize, char); 59]>>::heap_mut
Line
Count
Source
731
79.4M
    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
732
79.4M
        match self {
733
79.4M
            SmallVecData::Heap { ptr, len } => (*ptr, len),
734
0
            _ => debug_unreachable!(),
735
        }
736
79.4M
    }
<smallvec::SmallVecData<[char; 59]>>::heap_mut
Line
Count
Source
731
559k
    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
732
559k
        match self {
733
559k
            SmallVecData::Heap { ptr, len } => (*ptr, len),
734
0
            _ => debug_unreachable!(),
735
        }
736
559k
    }
<smallvec::SmallVecData<[char; 253]>>::heap_mut
Line
Count
Source
731
170M
    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
732
170M
        match self {
733
170M
            SmallVecData::Heap { ptr, len } => (*ptr, len),
734
0
            _ => debug_unreachable!(),
735
        }
736
170M
    }
<smallvec::SmallVecData<[icu_normalizer::CharacterAndClass; 17]>>::heap_mut
Line
Count
Source
731
1.96M
    unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
732
1.96M
        match self {
733
1.96M
            SmallVecData::Heap { ptr, len } => (*ptr, len),
734
0
            _ => debug_unreachable!(),
735
        }
736
1.96M
    }
Unexecuted instantiation: <smallvec::SmallVecData<_>>::heap_mut
737
    #[inline]
738
1.12M
    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
739
1.12M
        SmallVecData::Heap { ptr, len }
740
1.12M
    }
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::from_heap
Unexecuted instantiation: <smallvec::SmallVecData<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::from_heap
<smallvec::SmallVecData<[idna::uts46::AlreadyAsciiLabel; 8]>>::from_heap
Line
Count
Source
738
18.0k
    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
739
18.0k
        SmallVecData::Heap { ptr, len }
740
18.0k
    }
<smallvec::SmallVecData<[(usize, char); 59]>>::from_heap
Line
Count
Source
738
784k
    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
739
784k
        SmallVecData::Heap { ptr, len }
740
784k
    }
<smallvec::SmallVecData<[char; 59]>>::from_heap
Line
Count
Source
738
279k
    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
739
279k
        SmallVecData::Heap { ptr, len }
740
279k
    }
<smallvec::SmallVecData<[char; 253]>>::from_heap
Line
Count
Source
738
25.6k
    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
739
25.6k
        SmallVecData::Heap { ptr, len }
740
25.6k
    }
<smallvec::SmallVecData<[icu_normalizer::CharacterAndClass; 17]>>::from_heap
Line
Count
Source
738
16.2k
    fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
739
16.2k
        SmallVecData::Heap { ptr, len }
740
16.2k
    }
Unexecuted instantiation: <smallvec::SmallVecData<_>>::from_heap
741
}
742
743
unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
744
unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
745
746
/// A `Vec`-like container that can store a small number of elements inline.
747
///
748
/// `SmallVec` acts like a vector, but can store a limited amount of data inline within the
749
/// `SmallVec` struct rather than in a separate allocation.  If the data exceeds this limit, the
750
/// `SmallVec` will "spill" its data onto the heap, allocating a new buffer to hold it.
751
///
752
/// The amount of data that a `SmallVec` can store inline depends on its backing store. The backing
753
/// store can be any type that implements the `Array` trait; usually it is a small fixed-sized
754
/// array.  For example a `SmallVec<[u64; 8]>` can hold up to eight 64-bit integers inline.
755
///
756
/// ## Example
757
///
758
/// ```rust
759
/// use smallvec::SmallVec;
760
/// let mut v = SmallVec::<[u8; 4]>::new(); // initialize an empty vector
761
///
762
/// // The vector can hold up to 4 items without spilling onto the heap.
763
/// v.extend(0..4);
764
/// assert_eq!(v.len(), 4);
765
/// assert!(!v.spilled());
766
///
767
/// // Pushing another element will force the buffer to spill:
768
/// v.push(4);
769
/// assert_eq!(v.len(), 5);
770
/// assert!(v.spilled());
771
/// ```
772
pub struct SmallVec<A: Array> {
773
    // The capacity field is used to determine which of the storage variants is active:
774
    // If capacity <= Self::inline_capacity() then the inline variant is used and capacity holds the current length of the vector (number of elements actually in use).
775
    // If capacity > Self::inline_capacity() then the heap variant is used and capacity holds the size of the memory allocation.
776
    capacity: usize,
777
    data: SmallVecData<A>,
778
}
779
780
impl<A: Array> SmallVec<A> {
781
    /// Construct an empty vector
782
    #[inline]
783
2.79M
    pub fn new() -> SmallVec<A> {
784
        // Try to detect invalid custom implementations of `Array`. Hopefully,
785
        // this check should be optimized away entirely for valid ones.
786
2.79M
        assert!(
787
2.79M
            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
788
2.79M
                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
789
        );
790
2.79M
        SmallVec {
791
2.79M
            capacity: 0,
792
2.79M
            data: SmallVecData::from_inline(MaybeUninit::uninit()),
793
2.79M
        }
794
2.79M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::new
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::new
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::new
Line
Count
Source
783
17.3k
    pub fn new() -> SmallVec<A> {
784
        // Try to detect invalid custom implementations of `Array`. Hopefully,
785
        // this check should be optimized away entirely for valid ones.
786
17.3k
        assert!(
787
17.3k
            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
788
17.3k
                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
789
        );
790
17.3k
        SmallVec {
791
17.3k
            capacity: 0,
792
17.3k
            data: SmallVecData::from_inline(MaybeUninit::uninit()),
793
17.3k
        }
794
17.3k
    }
<smallvec::SmallVec<[(usize, char); 59]>>::new
Line
Count
Source
783
766k
    pub fn new() -> SmallVec<A> {
784
        // Try to detect invalid custom implementations of `Array`. Hopefully,
785
        // this check should be optimized away entirely for valid ones.
786
766k
        assert!(
787
766k
            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
788
766k
                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
789
        );
790
766k
        SmallVec {
791
766k
            capacity: 0,
792
766k
            data: SmallVecData::from_inline(MaybeUninit::uninit()),
793
766k
        }
794
766k
    }
<smallvec::SmallVec<[char; 59]>>::new
Line
Count
Source
783
766k
    pub fn new() -> SmallVec<A> {
784
        // Try to detect invalid custom implementations of `Array`. Hopefully,
785
        // this check should be optimized away entirely for valid ones.
786
766k
        assert!(
787
766k
            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
788
766k
                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
789
        );
790
766k
        SmallVec {
791
766k
            capacity: 0,
792
766k
            data: SmallVecData::from_inline(MaybeUninit::uninit()),
793
766k
        }
794
766k
    }
<smallvec::SmallVec<[char; 253]>>::new
Line
Count
Source
783
17.3k
    pub fn new() -> SmallVec<A> {
784
        // Try to detect invalid custom implementations of `Array`. Hopefully,
785
        // this check should be optimized away entirely for valid ones.
786
17.3k
        assert!(
787
17.3k
            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
788
17.3k
                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
789
        );
790
17.3k
        SmallVec {
791
17.3k
            capacity: 0,
792
17.3k
            data: SmallVecData::from_inline(MaybeUninit::uninit()),
793
17.3k
        }
794
17.3k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::new
Line
Count
Source
783
1.22M
    pub fn new() -> SmallVec<A> {
784
        // Try to detect invalid custom implementations of `Array`. Hopefully,
785
        // this check should be optimized away entirely for valid ones.
786
1.22M
        assert!(
787
1.22M
            mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
788
1.22M
                && mem::align_of::<A>() >= mem::align_of::<A::Item>()
789
        );
790
1.22M
        SmallVec {
791
1.22M
            capacity: 0,
792
1.22M
            data: SmallVecData::from_inline(MaybeUninit::uninit()),
793
1.22M
        }
794
1.22M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::new
795
796
    /// Construct an empty vector with enough capacity pre-allocated to store at least `n`
797
    /// elements.
798
    ///
799
    /// Will create a heap allocation only if `n` is larger than the inline capacity.
800
    ///
801
    /// ```
802
    /// # use smallvec::SmallVec;
803
    ///
804
    /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100);
805
    ///
806
    /// assert!(v.is_empty());
807
    /// assert!(v.capacity() >= 100);
808
    /// ```
809
    #[inline]
810
0
    pub fn with_capacity(n: usize) -> Self {
811
0
        let mut v = SmallVec::new();
812
0
        v.reserve_exact(n);
813
0
        v
814
0
    }
815
816
    /// Construct a new `SmallVec` from a `Vec<A::Item>`.
817
    ///
818
    /// Elements will be copied to the inline buffer if `vec.capacity() <= Self::inline_capacity()`.
819
    ///
820
    /// ```rust
821
    /// use smallvec::SmallVec;
822
    ///
823
    /// let vec = vec![1, 2, 3, 4, 5];
824
    /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec);
825
    ///
826
    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
827
    /// ```
828
    #[inline]
829
0
    pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
830
0
        if vec.capacity() <= Self::inline_capacity() {
831
            // Cannot use Vec with smaller capacity
832
            // because we use value of `Self::capacity` field as indicator.
833
            unsafe {
834
0
                let mut data = SmallVecData::<A>::from_inline(MaybeUninit::uninit());
835
0
                let len = vec.len();
836
0
                vec.set_len(0);
837
0
                ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
838
839
0
                SmallVec {
840
0
                    capacity: len,
841
0
                    data,
842
0
                }
843
            }
844
        } else {
845
0
            let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
846
0
            mem::forget(vec);
847
0
            let ptr = NonNull::new(ptr)
848
                // See docs: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_ptr
849
0
                .expect("Cannot be null by `Vec` invariant");
850
851
0
            SmallVec {
852
0
                capacity: cap,
853
0
                data: SmallVecData::from_heap(ptr, len),
854
0
            }
855
        }
856
0
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::from_vec
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::from_vec
Unexecuted instantiation: <smallvec::SmallVec<_>>::from_vec
857
858
    /// Constructs a new `SmallVec` on the stack from an `A` without
859
    /// copying elements.
860
    ///
861
    /// ```rust
862
    /// use smallvec::SmallVec;
863
    ///
864
    /// let buf = [1, 2, 3, 4, 5];
865
    /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf);
866
    ///
867
    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
868
    /// ```
869
    #[inline]
870
0
    pub fn from_buf(buf: A) -> SmallVec<A> {
871
0
        SmallVec {
872
0
            capacity: A::size(),
873
0
            data: SmallVecData::from_inline(MaybeUninit::new(buf)),
874
0
        }
875
0
    }
876
877
    /// Constructs a new `SmallVec` on the stack from an `A` without
878
    /// copying elements. Also sets the length, which must be less or
879
    /// equal to the size of `buf`.
880
    ///
881
    /// ```rust
882
    /// use smallvec::SmallVec;
883
    ///
884
    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
885
    /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5);
886
    ///
887
    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
888
    /// ```
889
    #[inline]
890
0
    pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
891
0
        assert!(len <= A::size());
892
0
        unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
893
0
    }
894
895
    /// Constructs a new `SmallVec` on the stack from an `A` without
896
    /// copying elements. Also sets the length. The user is responsible
897
    /// for ensuring that `len <= A::size()`.
898
    ///
899
    /// ```rust
900
    /// use smallvec::SmallVec;
901
    /// use std::mem::MaybeUninit;
902
    ///
903
    /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
904
    /// let small_vec: SmallVec<_> = unsafe {
905
    ///     SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5)
906
    /// };
907
    ///
908
    /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
909
    /// ```
910
    #[inline]
911
0
    pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
912
0
        SmallVec {
913
0
            capacity: len,
914
0
            data: SmallVecData::from_inline(buf),
915
0
        }
916
0
    }
917
918
    /// Sets the length of a vector.
919
    ///
920
    /// This will explicitly set the size of the vector, without actually
921
    /// modifying its buffers, so it is up to the caller to ensure that the
922
    /// vector is actually the specified size.
923
757k
    pub unsafe fn set_len(&mut self, new_len: usize) {
924
757k
        let (_, len_ptr, _) = self.triple_mut();
925
757k
        *len_ptr = new_len;
926
757k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::set_len
Line
Count
Source
923
757k
    pub unsafe fn set_len(&mut self, new_len: usize) {
924
757k
        let (_, len_ptr, _) = self.triple_mut();
925
757k
        *len_ptr = new_len;
926
757k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::set_len
927
928
    /// The maximum number of elements this vector can hold inline
929
    #[inline]
930
660M
    fn inline_capacity() -> usize {
931
660M
        if mem::size_of::<A::Item>() > 0 {
932
660M
            A::size()
933
        } else {
934
            // For zero-size items code like `ptr.add(offset)` always returns the same pointer.
935
            // Therefore all items are at the same address,
936
            // and any array size has capacity for infinitely many items.
937
            // The capacity is limited by the bit width of the length field.
938
            //
939
            // `Vec` also does this:
940
            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
941
            //
942
            // In our case, this also ensures that a smallvec of zero-size items never spills,
943
            // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
944
0
            core::usize::MAX
945
        }
946
660M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::inline_capacity
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::inline_capacity
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::inline_capacity
Line
Count
Source
930
24.8M
    fn inline_capacity() -> usize {
931
24.8M
        if mem::size_of::<A::Item>() > 0 {
932
24.8M
            A::size()
933
        } else {
934
            // For zero-size items code like `ptr.add(offset)` always returns the same pointer.
935
            // Therefore all items are at the same address,
936
            // and any array size has capacity for infinitely many items.
937
            // The capacity is limited by the bit width of the length field.
938
            //
939
            // `Vec` also does this:
940
            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
941
            //
942
            // In our case, this also ensures that a smallvec of zero-size items never spills,
943
            // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
944
0
            core::usize::MAX
945
        }
946
24.8M
    }
<smallvec::SmallVec<[(usize, char); 59]>>::inline_capacity
Line
Count
Source
930
185M
    fn inline_capacity() -> usize {
931
185M
        if mem::size_of::<A::Item>() > 0 {
932
185M
            A::size()
933
        } else {
934
            // For zero-size items code like `ptr.add(offset)` always returns the same pointer.
935
            // Therefore all items are at the same address,
936
            // and any array size has capacity for infinitely many items.
937
            // The capacity is limited by the bit width of the length field.
938
            //
939
            // `Vec` also does this:
940
            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
941
            //
942
            // In our case, this also ensures that a smallvec of zero-size items never spills,
943
            // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
944
0
            core::usize::MAX
945
        }
946
185M
    }
<smallvec::SmallVec<[char; 59]>>::inline_capacity
Line
Count
Source
930
6.89M
    fn inline_capacity() -> usize {
931
6.89M
        if mem::size_of::<A::Item>() > 0 {
932
6.89M
            A::size()
933
        } else {
934
            // For zero-size items code like `ptr.add(offset)` always returns the same pointer.
935
            // Therefore all items are at the same address,
936
            // and any array size has capacity for infinitely many items.
937
            // The capacity is limited by the bit width of the length field.
938
            //
939
            // `Vec` also does this:
940
            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
941
            //
942
            // In our case, this also ensures that a smallvec of zero-size items never spills,
943
            // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
944
0
            core::usize::MAX
945
        }
946
6.89M
    }
<smallvec::SmallVec<[char; 253]>>::inline_capacity
Line
Count
Source
930
200M
    fn inline_capacity() -> usize {
931
200M
        if mem::size_of::<A::Item>() > 0 {
932
200M
            A::size()
933
        } else {
934
            // For zero-size items code like `ptr.add(offset)` always returns the same pointer.
935
            // Therefore all items are at the same address,
936
            // and any array size has capacity for infinitely many items.
937
            // The capacity is limited by the bit width of the length field.
938
            //
939
            // `Vec` also does this:
940
            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
941
            //
942
            // In our case, this also ensures that a smallvec of zero-size items never spills,
943
            // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
944
0
            core::usize::MAX
945
        }
946
200M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::inline_capacity
Line
Count
Source
930
243M
    fn inline_capacity() -> usize {
931
243M
        if mem::size_of::<A::Item>() > 0 {
932
243M
            A::size()
933
        } else {
934
            // For zero-size items code like `ptr.add(offset)` always returns the same pointer.
935
            // Therefore all items are at the same address,
936
            // and any array size has capacity for infinitely many items.
937
            // The capacity is limited by the bit width of the length field.
938
            //
939
            // `Vec` also does this:
940
            // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
941
            //
942
            // In our case, this also ensures that a smallvec of zero-size items never spills,
943
            // and we never try to allocate zero bytes which `std::alloc::alloc` disallows.
944
0
            core::usize::MAX
945
        }
946
243M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::inline_capacity
947
948
    /// The maximum number of elements this vector can hold inline
949
    #[inline]
950
0
    pub fn inline_size(&self) -> usize {
951
0
        Self::inline_capacity()
952
0
    }
953
954
    /// The number of elements stored in the vector
955
    #[inline]
956
35.3M
    pub fn len(&self) -> usize {
957
35.3M
        self.triple().1
958
35.3M
    }
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::len
Line
Count
Source
956
18.0k
    pub fn len(&self) -> usize {
957
18.0k
        self.triple().1
958
18.0k
    }
<smallvec::SmallVec<[(usize, char); 59]>>::len
Line
Count
Source
956
1.55M
    pub fn len(&self) -> usize {
957
1.55M
        self.triple().1
958
1.55M
    }
Unexecuted instantiation: <smallvec::SmallVec<[char; 59]>>::len
<smallvec::SmallVec<[char; 253]>>::len
Line
Count
Source
956
24.9M
    pub fn len(&self) -> usize {
957
24.9M
        self.triple().1
958
24.9M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::len
Line
Count
Source
956
8.80M
    pub fn len(&self) -> usize {
957
8.80M
        self.triple().1
958
8.80M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::len
959
960
    /// Returns `true` if the vector is empty
961
    #[inline]
962
5.90M
    pub fn is_empty(&self) -> bool {
963
5.90M
        self.len() == 0
964
5.90M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::is_empty
Line
Count
Source
962
5.90M
    pub fn is_empty(&self) -> bool {
963
5.90M
        self.len() == 0
964
5.90M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::is_empty
965
966
    /// The number of items the vector can hold without reallocating
967
    #[inline]
968
0
    pub fn capacity(&self) -> usize {
969
0
        self.triple().2
970
0
    }
971
972
    /// Returns a tuple with (data ptr, len, capacity)
973
    /// Useful to get all `SmallVec` properties with a single check of the current storage variant.
974
    #[inline]
975
135M
    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
976
        unsafe {
977
135M
            if self.spilled() {
978
32.0M
                let (ptr, len) = self.data.heap();
979
32.0M
                (ptr, len, self.capacity)
980
            } else {
981
103M
                (self.data.inline(), self.capacity, Self::inline_capacity())
982
            }
983
        }
984
135M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::triple
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::triple
Line
Count
Source
975
25.8k
    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
976
        unsafe {
977
25.8k
            if self.spilled() {
978
17.2k
                let (ptr, len) = self.data.heap();
979
17.2k
                (ptr, len, self.capacity)
980
            } else {
981
8.66k
                (self.data.inline(), self.capacity, Self::inline_capacity())
982
            }
983
        }
984
25.8k
    }
<smallvec::SmallVec<[(usize, char); 59]>>::triple
Line
Count
Source
975
2.31M
    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
976
        unsafe {
977
2.31M
            if self.spilled() {
978
1.06M
                let (ptr, len) = self.data.heap();
979
1.06M
                (ptr, len, self.capacity)
980
            } else {
981
1.25M
                (self.data.inline(), self.capacity, Self::inline_capacity())
982
            }
983
        }
984
2.31M
    }
<smallvec::SmallVec<[char; 59]>>::triple
Line
Count
Source
975
766k
    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
976
        unsafe {
977
766k
            if self.spilled() {
978
279k
                let (ptr, len) = self.data.heap();
979
279k
                (ptr, len, self.capacity)
980
            } else {
981
486k
                (self.data.inline(), self.capacity, Self::inline_capacity())
982
            }
983
        }
984
766k
    }
<smallvec::SmallVec<[char; 253]>>::triple
Line
Count
Source
975
25.6M
    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
976
        unsafe {
977
25.6M
            if self.spilled() {
978
25.4M
                let (ptr, len) = self.data.heap();
979
25.4M
                (ptr, len, self.capacity)
980
            } else {
981
270k
                (self.data.inline(), self.capacity, Self::inline_capacity())
982
            }
983
        }
984
25.6M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::triple
Line
Count
Source
975
107M
    fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
976
        unsafe {
977
107M
            if self.spilled() {
978
5.24M
                let (ptr, len) = self.data.heap();
979
5.24M
                (ptr, len, self.capacity)
980
            } else {
981
101M
                (self.data.inline(), self.capacity, Self::inline_capacity())
982
            }
983
        }
984
107M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::triple
985
986
    /// Returns a tuple with (data ptr, len ptr, capacity)
987
    #[inline]
988
345M
    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
989
        unsafe {
990
345M
            if self.spilled() {
991
275M
                let (ptr, len_ptr) = self.data.heap_mut();
992
275M
                (ptr, len_ptr, self.capacity)
993
            } else {
994
70.1M
                (
995
70.1M
                    self.data.inline_mut(),
996
70.1M
                    &mut self.capacity,
997
70.1M
                    Self::inline_capacity(),
998
70.1M
                )
999
            }
1000
        }
1001
345M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::triple_mut
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::triple_mut
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::triple_mut
Line
Count
Source
988
24.7M
    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
989
        unsafe {
990
24.7M
            if self.spilled() {
991
24.6M
                let (ptr, len_ptr) = self.data.heap_mut();
992
24.6M
                (ptr, len_ptr, self.capacity)
993
            } else {
994
62.0k
                (
995
62.0k
                    self.data.inline_mut(),
996
62.0k
                    &mut self.capacity,
997
62.0k
                    Self::inline_capacity(),
998
62.0k
                )
999
            }
1000
        }
1001
24.7M
    }
<smallvec::SmallVec<[(usize, char); 59]>>::triple_mut
Line
Count
Source
988
128M
    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
989
        unsafe {
990
128M
            if self.spilled() {
991
78.3M
                let (ptr, len_ptr) = self.data.heap_mut();
992
78.3M
                (ptr, len_ptr, self.capacity)
993
            } else {
994
50.3M
                (
995
50.3M
                    self.data.inline_mut(),
996
50.3M
                    &mut self.capacity,
997
50.3M
                    Self::inline_capacity(),
998
50.3M
                )
999
            }
1000
        }
1001
128M
    }
<smallvec::SmallVec<[char; 59]>>::triple_mut
Line
Count
Source
988
2.29M
    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
989
        unsafe {
990
2.29M
            if self.spilled() {
991
279k
                let (ptr, len_ptr) = self.data.heap_mut();
992
279k
                (ptr, len_ptr, self.capacity)
993
            } else {
994
2.01M
                (
995
2.01M
                    self.data.inline_mut(),
996
2.01M
                    &mut self.capacity,
997
2.01M
                    Self::inline_capacity(),
998
2.01M
                )
999
            }
1000
        }
1001
2.29M
    }
<smallvec::SmallVec<[char; 253]>>::triple_mut
Line
Count
Source
988
172M
    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
989
        unsafe {
990
172M
            if self.spilled() {
991
170M
                let (ptr, len_ptr) = self.data.heap_mut();
992
170M
                (ptr, len_ptr, self.capacity)
993
            } else {
994
2.19M
                (
995
2.19M
                    self.data.inline_mut(),
996
2.19M
                    &mut self.capacity,
997
2.19M
                    Self::inline_capacity(),
998
2.19M
                )
999
            }
1000
        }
1001
172M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::triple_mut
Line
Count
Source
988
17.4M
    fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
989
        unsafe {
990
17.4M
            if self.spilled() {
991
1.94M
                let (ptr, len_ptr) = self.data.heap_mut();
992
1.94M
                (ptr, len_ptr, self.capacity)
993
            } else {
994
15.4M
                (
995
15.4M
                    self.data.inline_mut(),
996
15.4M
                    &mut self.capacity,
997
15.4M
                    Self::inline_capacity(),
998
15.4M
                )
999
            }
1000
        }
1001
17.4M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::triple_mut
1002
1003
    /// Returns `true` if the data has spilled into a separate heap-allocated buffer.
1004
    #[inline]
1005
485M
    pub fn spilled(&self) -> bool {
1006
485M
        self.capacity > Self::inline_capacity()
1007
485M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::spilled
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::spilled
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::spilled
Line
Count
Source
1005
24.7M
    pub fn spilled(&self) -> bool {
1006
24.7M
        self.capacity > Self::inline_capacity()
1007
24.7M
    }
<smallvec::SmallVec<[(usize, char); 59]>>::spilled
Line
Count
Source
1005
132M
    pub fn spilled(&self) -> bool {
1006
132M
        self.capacity > Self::inline_capacity()
1007
132M
    }
<smallvec::SmallVec<[char; 59]>>::spilled
Line
Count
Source
1005
4.10M
    pub fn spilled(&self) -> bool {
1006
4.10M
        self.capacity > Self::inline_capacity()
1007
4.10M
    }
<smallvec::SmallVec<[char; 253]>>::spilled
Line
Count
Source
1005
198M
    pub fn spilled(&self) -> bool {
1006
198M
        self.capacity > Self::inline_capacity()
1007
198M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::spilled
Line
Count
Source
1005
125M
    pub fn spilled(&self) -> bool {
1006
125M
        self.capacity > Self::inline_capacity()
1007
125M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::spilled
1008
1009
    /// Creates a draining iterator that removes the specified range in the vector
1010
    /// and yields the removed items.
1011
    ///
1012
    /// Note 1: The element range is removed even if the iterator is only
1013
    /// partially consumed or not consumed at all.
1014
    ///
1015
    /// Note 2: It is unspecified how many elements are removed from the vector
1016
    /// if the `Drain` value is leaked.
1017
    ///
1018
    /// # Panics
1019
    ///
1020
    /// Panics if the starting point is greater than the end point or if
1021
    /// the end point is greater than the length of the vector.
1022
378k
    pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1023
378k
    where
1024
378k
        R: RangeBounds<usize>,
1025
    {
1026
        use core::ops::Bound::*;
1027
1028
378k
        let len = self.len();
1029
378k
        let start = match range.start_bound() {
1030
378k
            Included(&n) => n,
1031
0
            Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1032
0
            Unbounded => 0,
1033
        };
1034
378k
        let end = match range.end_bound() {
1035
0
            Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1036
378k
            Excluded(&n) => n,
1037
0
            Unbounded => len,
1038
        };
1039
1040
378k
        assert!(start <= end);
1041
378k
        assert!(end <= len);
1042
1043
        unsafe {
1044
378k
            self.set_len(start);
1045
1046
378k
            let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1047
1048
378k
            Drain {
1049
378k
                tail_start: end,
1050
378k
                tail_len: len - end,
1051
378k
                iter: range_slice.iter(),
1052
378k
                // Since self is a &mut, passing it to a function would invalidate the slice iterator.
1053
378k
                vec: NonNull::new_unchecked(self as *mut _),
1054
378k
            }
1055
        }
1056
378k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::drain::<core::ops::range::Range<usize>>
Line
Count
Source
1022
378k
    pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1023
378k
    where
1024
378k
        R: RangeBounds<usize>,
1025
    {
1026
        use core::ops::Bound::*;
1027
1028
378k
        let len = self.len();
1029
378k
        let start = match range.start_bound() {
1030
378k
            Included(&n) => n,
1031
0
            Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1032
0
            Unbounded => 0,
1033
        };
1034
378k
        let end = match range.end_bound() {
1035
0
            Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1036
378k
            Excluded(&n) => n,
1037
0
            Unbounded => len,
1038
        };
1039
1040
378k
        assert!(start <= end);
1041
378k
        assert!(end <= len);
1042
1043
        unsafe {
1044
378k
            self.set_len(start);
1045
1046
378k
            let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1047
1048
378k
            Drain {
1049
378k
                tail_start: end,
1050
378k
                tail_len: len - end,
1051
378k
                iter: range_slice.iter(),
1052
378k
                // Since self is a &mut, passing it to a function would invalidate the slice iterator.
1053
378k
                vec: NonNull::new_unchecked(self as *mut _),
1054
378k
            }
1055
        }
1056
378k
    }
Unexecuted instantiation: <smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::drain::<core::ops::range::RangeTo<usize>>
Unexecuted instantiation: <smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::drain::<core::ops::range::RangeFull>
Unexecuted instantiation: <smallvec::SmallVec<_>>::drain::<_>
1057
1058
    #[cfg(feature = "drain_filter")]
1059
    /// Creates an iterator which uses a closure to determine if an element should be removed.
1060
    ///
1061
    /// If the closure returns true, the element is removed and yielded. If the closure returns
1062
    /// false, the element will remain in the vector and will not be yielded by the iterator.
1063
    ///
1064
    /// Using this method is equivalent to the following code:
1065
    /// ```
1066
    /// # use smallvec::SmallVec;
1067
    /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
1068
    /// # let mut vec: SmallVec<[i32; 8]> = SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6]);
1069
    /// let mut i = 0;
1070
    /// while i < vec.len() {
1071
    ///     if some_predicate(&mut vec[i]) {
1072
    ///         let val = vec.remove(i);
1073
    ///         // your code here
1074
    ///     } else {
1075
    ///         i += 1;
1076
    ///     }
1077
    /// }
1078
    ///
1079
    /// # assert_eq!(vec, SmallVec::<[i32; 8]>::from_slice(&[1i32, 4, 5]));
1080
    /// ```
1081
    /// ///
1082
    /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
1083
    /// because it can backshift the elements of the array in bulk.
1084
    ///
1085
    /// Note that `drain_filter` also lets you mutate every element in the filter closure,
1086
    /// regardless of whether you choose to keep or remove it.
1087
    ///
1088
    /// # Examples
1089
    ///
1090
    /// Splitting an array into evens and odds, reusing the original allocation:
1091
    ///
1092
    /// ```
1093
    /// # use smallvec::SmallVec;
1094
    /// let mut numbers: SmallVec<[i32; 16]> = SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
1095
    ///
1096
    /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<SmallVec<[i32; 16]>>();
1097
    /// let odds = numbers;
1098
    ///
1099
    /// assert_eq!(evens, SmallVec::<[i32; 16]>::from_slice(&[2i32, 4, 6, 8, 14]));
1100
    /// assert_eq!(odds, SmallVec::<[i32; 16]>::from_slice(&[1i32, 3, 5, 9, 11, 13, 15]));
1101
    /// ```
1102
    pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F,>
1103
    where
1104
        F: FnMut(&mut A::Item) -> bool,
1105
    {
1106
        let old_len = self.len();
1107
1108
        // Guard against us getting leaked (leak amplification)
1109
        unsafe {
1110
            self.set_len(0);
1111
        }
1112
1113
        DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
1114
    }
1115
1116
    /// Append an item to the vector.
1117
    #[inline]
1118
259M
    pub fn push(&mut self, value: A::Item) {
1119
        unsafe {
1120
259M
            let (mut ptr, mut len, cap) = self.triple_mut();
1121
259M
            if *len == cap {
1122
844k
                self.reserve_one_unchecked();
1123
844k
                let (heap_ptr, heap_len) = self.data.heap_mut();
1124
844k
                ptr = heap_ptr;
1125
844k
                len = heap_len;
1126
259M
            }
1127
259M
            ptr::write(ptr.as_ptr().add(*len), value);
1128
259M
            *len += 1;
1129
        }
1130
259M
    }
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::push
Line
Count
Source
1118
24.6M
    pub fn push(&mut self, value: A::Item) {
1119
        unsafe {
1120
24.6M
            let (mut ptr, mut len, cap) = self.triple_mut();
1121
24.6M
            if *len == cap {
1122
18.0k
                self.reserve_one_unchecked();
1123
18.0k
                let (heap_ptr, heap_len) = self.data.heap_mut();
1124
18.0k
                ptr = heap_ptr;
1125
18.0k
                len = heap_len;
1126
24.6M
            }
1127
24.6M
            ptr::write(ptr.as_ptr().add(*len), value);
1128
24.6M
            *len += 1;
1129
        }
1130
24.6M
    }
<smallvec::SmallVec<[(usize, char); 59]>>::push
Line
Count
Source
1118
62.9M
    pub fn push(&mut self, value: A::Item) {
1119
        unsafe {
1120
62.9M
            let (mut ptr, mut len, cap) = self.triple_mut();
1121
62.9M
            if *len == cap {
1122
784k
                self.reserve_one_unchecked();
1123
784k
                let (heap_ptr, heap_len) = self.data.heap_mut();
1124
784k
                ptr = heap_ptr;
1125
784k
                len = heap_len;
1126
62.1M
            }
1127
62.9M
            ptr::write(ptr.as_ptr().add(*len), value);
1128
62.9M
            *len += 1;
1129
        }
1130
62.9M
    }
Unexecuted instantiation: <smallvec::SmallVec<[char; 59]>>::push
<smallvec::SmallVec<[char; 253]>>::push
Line
Count
Source
1118
170M
    pub fn push(&mut self, value: A::Item) {
1119
        unsafe {
1120
170M
            let (mut ptr, mut len, cap) = self.triple_mut();
1121
170M
            if *len == cap {
1122
25.6k
                self.reserve_one_unchecked();
1123
25.6k
                let (heap_ptr, heap_len) = self.data.heap_mut();
1124
25.6k
                ptr = heap_ptr;
1125
25.6k
                len = heap_len;
1126
169M
            }
1127
170M
            ptr::write(ptr.as_ptr().add(*len), value);
1128
170M
            *len += 1;
1129
        }
1130
170M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::push
Line
Count
Source
1118
2.21M
    pub fn push(&mut self, value: A::Item) {
1119
        unsafe {
1120
2.21M
            let (mut ptr, mut len, cap) = self.triple_mut();
1121
2.21M
            if *len == cap {
1122
16.2k
                self.reserve_one_unchecked();
1123
16.2k
                let (heap_ptr, heap_len) = self.data.heap_mut();
1124
16.2k
                ptr = heap_ptr;
1125
16.2k
                len = heap_len;
1126
2.19M
            }
1127
2.21M
            ptr::write(ptr.as_ptr().add(*len), value);
1128
2.21M
            *len += 1;
1129
        }
1130
2.21M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::push
1131
1132
    /// Remove an item from the end of the vector and return it, or None if empty.
1133
    #[inline]
1134
0
    pub fn pop(&mut self) -> Option<A::Item> {
1135
        unsafe {
1136
0
            let (ptr, len_ptr, _) = self.triple_mut();
1137
0
            let ptr: *const _ = ptr.as_ptr();
1138
0
            if *len_ptr == 0 {
1139
0
                return None;
1140
0
            }
1141
0
            let last_index = *len_ptr - 1;
1142
0
            *len_ptr = last_index;
1143
0
            Some(ptr::read(ptr.add(last_index)))
1144
        }
1145
0
    }
1146
1147
    /// Moves all the elements of `other` into `self`, leaving `other` empty.
1148
    ///
1149
    /// # Example
1150
    ///
1151
    /// ```
1152
    /// # use smallvec::{SmallVec, smallvec};
1153
    /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3];
1154
    /// let mut v1: SmallVec<[u8; 32]> = smallvec![4, 5, 6];
1155
    /// v0.append(&mut v1);
1156
    /// assert_eq!(*v0, [1, 2, 3, 4, 5, 6]);
1157
    /// assert_eq!(*v1, []);
1158
    /// ```
1159
0
    pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1160
0
    where
1161
0
        B: Array<Item = A::Item>,
1162
    {
1163
0
        self.extend(other.drain(..))
1164
0
    }
1165
1166
    /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1167
    ///
1168
    /// Panics if `new_cap` is less than the vector's length
1169
    /// or if the capacity computation overflows `usize`.
1170
0
    pub fn grow(&mut self, new_cap: usize) {
1171
0
        infallible(self.try_grow(new_cap))
1172
0
    }
1173
1174
    /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1175
    ///
1176
    /// Panics if `new_cap` is less than the vector's length
1177
1.12M
    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1178
        unsafe {
1179
1.12M
            let unspilled = !self.spilled();
1180
1.12M
            let (ptr, &mut len, cap) = self.triple_mut();
1181
1.12M
            assert!(new_cap >= len);
1182
1.12M
            if new_cap <= Self::inline_capacity() {
1183
0
                if unspilled {
1184
0
                    return Ok(());
1185
0
                }
1186
0
                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1187
0
                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1188
0
                self.capacity = len;
1189
0
                deallocate(ptr, cap);
1190
1.12M
            } else if new_cap != cap {
1191
1.12M
                let layout = layout_array::<A::Item>(new_cap)?;
1192
1.12M
                debug_assert!(layout.size() > 0);
1193
                let new_alloc;
1194
1.12M
                if unspilled {
1195
575k
                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1196
575k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1197
575k
                        .cast();
1198
575k
                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1199
                } else {
1200
                    // This should never fail since the same succeeded
1201
                    // when previously allocating `ptr`.
1202
549k
                    let old_layout = layout_array::<A::Item>(cap)?;
1203
1204
549k
                    let new_ptr =
1205
549k
                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1206
549k
                    new_alloc = NonNull::new(new_ptr)
1207
549k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1208
549k
                        .cast();
1209
                }
1210
1.12M
                self.data = SmallVecData::from_heap(new_alloc, len);
1211
1.12M
                self.capacity = new_cap;
1212
0
            }
1213
1.12M
            Ok(())
1214
        }
1215
1.12M
    }
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::try_grow
Line
Count
Source
1177
18.0k
    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1178
        unsafe {
1179
18.0k
            let unspilled = !self.spilled();
1180
18.0k
            let (ptr, &mut len, cap) = self.triple_mut();
1181
18.0k
            assert!(new_cap >= len);
1182
18.0k
            if new_cap <= Self::inline_capacity() {
1183
0
                if unspilled {
1184
0
                    return Ok(());
1185
0
                }
1186
0
                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1187
0
                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1188
0
                self.capacity = len;
1189
0
                deallocate(ptr, cap);
1190
18.0k
            } else if new_cap != cap {
1191
18.0k
                let layout = layout_array::<A::Item>(new_cap)?;
1192
18.0k
                debug_assert!(layout.size() > 0);
1193
                let new_alloc;
1194
18.0k
                if unspilled {
1195
3.59k
                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1196
3.59k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1197
3.59k
                        .cast();
1198
3.59k
                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1199
                } else {
1200
                    // This should never fail since the same succeeded
1201
                    // when previously allocating `ptr`.
1202
14.4k
                    let old_layout = layout_array::<A::Item>(cap)?;
1203
1204
14.4k
                    let new_ptr =
1205
14.4k
                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1206
14.4k
                    new_alloc = NonNull::new(new_ptr)
1207
14.4k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1208
14.4k
                        .cast();
1209
                }
1210
18.0k
                self.data = SmallVecData::from_heap(new_alloc, len);
1211
18.0k
                self.capacity = new_cap;
1212
0
            }
1213
18.0k
            Ok(())
1214
        }
1215
18.0k
    }
<smallvec::SmallVec<[(usize, char); 59]>>::try_grow
Line
Count
Source
1177
784k
    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1178
        unsafe {
1179
784k
            let unspilled = !self.spilled();
1180
784k
            let (ptr, &mut len, cap) = self.triple_mut();
1181
784k
            assert!(new_cap >= len);
1182
784k
            if new_cap <= Self::inline_capacity() {
1183
0
                if unspilled {
1184
0
                    return Ok(());
1185
0
                }
1186
0
                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1187
0
                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1188
0
                self.capacity = len;
1189
0
                deallocate(ptr, cap);
1190
784k
            } else if new_cap != cap {
1191
784k
                let layout = layout_array::<A::Item>(new_cap)?;
1192
784k
                debug_assert!(layout.size() > 0);
1193
                let new_alloc;
1194
784k
                if unspilled {
1195
279k
                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1196
279k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1197
279k
                        .cast();
1198
279k
                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1199
                } else {
1200
                    // This should never fail since the same succeeded
1201
                    // when previously allocating `ptr`.
1202
505k
                    let old_layout = layout_array::<A::Item>(cap)?;
1203
1204
505k
                    let new_ptr =
1205
505k
                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1206
505k
                    new_alloc = NonNull::new(new_ptr)
1207
505k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1208
505k
                        .cast();
1209
                }
1210
784k
                self.data = SmallVecData::from_heap(new_alloc, len);
1211
784k
                self.capacity = new_cap;
1212
0
            }
1213
784k
            Ok(())
1214
        }
1215
784k
    }
<smallvec::SmallVec<[char; 59]>>::try_grow
Line
Count
Source
1177
279k
    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1178
        unsafe {
1179
279k
            let unspilled = !self.spilled();
1180
279k
            let (ptr, &mut len, cap) = self.triple_mut();
1181
279k
            assert!(new_cap >= len);
1182
279k
            if new_cap <= Self::inline_capacity() {
1183
0
                if unspilled {
1184
0
                    return Ok(());
1185
0
                }
1186
0
                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1187
0
                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1188
0
                self.capacity = len;
1189
0
                deallocate(ptr, cap);
1190
279k
            } else if new_cap != cap {
1191
279k
                let layout = layout_array::<A::Item>(new_cap)?;
1192
279k
                debug_assert!(layout.size() > 0);
1193
                let new_alloc;
1194
279k
                if unspilled {
1195
279k
                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1196
279k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1197
279k
                        .cast();
1198
279k
                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1199
                } else {
1200
                    // This should never fail since the same succeeded
1201
                    // when previously allocating `ptr`.
1202
0
                    let old_layout = layout_array::<A::Item>(cap)?;
1203
1204
0
                    let new_ptr =
1205
0
                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1206
0
                    new_alloc = NonNull::new(new_ptr)
1207
0
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1208
0
                        .cast();
1209
                }
1210
279k
                self.data = SmallVecData::from_heap(new_alloc, len);
1211
279k
                self.capacity = new_cap;
1212
0
            }
1213
279k
            Ok(())
1214
        }
1215
279k
    }
<smallvec::SmallVec<[char; 253]>>::try_grow
Line
Count
Source
1177
25.6k
    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1178
        unsafe {
1179
25.6k
            let unspilled = !self.spilled();
1180
25.6k
            let (ptr, &mut len, cap) = self.triple_mut();
1181
25.6k
            assert!(new_cap >= len);
1182
25.6k
            if new_cap <= Self::inline_capacity() {
1183
0
                if unspilled {
1184
0
                    return Ok(());
1185
0
                }
1186
0
                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1187
0
                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1188
0
                self.capacity = len;
1189
0
                deallocate(ptr, cap);
1190
25.6k
            } else if new_cap != cap {
1191
25.6k
                let layout = layout_array::<A::Item>(new_cap)?;
1192
25.6k
                debug_assert!(layout.size() > 0);
1193
                let new_alloc;
1194
25.6k
                if unspilled {
1195
5.45k
                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1196
5.45k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1197
5.45k
                        .cast();
1198
5.45k
                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1199
                } else {
1200
                    // This should never fail since the same succeeded
1201
                    // when previously allocating `ptr`.
1202
20.2k
                    let old_layout = layout_array::<A::Item>(cap)?;
1203
1204
20.2k
                    let new_ptr =
1205
20.2k
                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1206
20.2k
                    new_alloc = NonNull::new(new_ptr)
1207
20.2k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1208
20.2k
                        .cast();
1209
                }
1210
25.6k
                self.data = SmallVecData::from_heap(new_alloc, len);
1211
25.6k
                self.capacity = new_cap;
1212
0
            }
1213
25.6k
            Ok(())
1214
        }
1215
25.6k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::try_grow
Line
Count
Source
1177
16.2k
    pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1178
        unsafe {
1179
16.2k
            let unspilled = !self.spilled();
1180
16.2k
            let (ptr, &mut len, cap) = self.triple_mut();
1181
16.2k
            assert!(new_cap >= len);
1182
16.2k
            if new_cap <= Self::inline_capacity() {
1183
0
                if unspilled {
1184
0
                    return Ok(());
1185
0
                }
1186
0
                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1187
0
                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1188
0
                self.capacity = len;
1189
0
                deallocate(ptr, cap);
1190
16.2k
            } else if new_cap != cap {
1191
16.2k
                let layout = layout_array::<A::Item>(new_cap)?;
1192
16.2k
                debug_assert!(layout.size() > 0);
1193
                let new_alloc;
1194
16.2k
                if unspilled {
1195
7.41k
                    new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1196
7.41k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1197
7.41k
                        .cast();
1198
7.41k
                    ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1199
                } else {
1200
                    // This should never fail since the same succeeded
1201
                    // when previously allocating `ptr`.
1202
8.87k
                    let old_layout = layout_array::<A::Item>(cap)?;
1203
1204
8.87k
                    let new_ptr =
1205
8.87k
                        alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1206
8.87k
                    new_alloc = NonNull::new(new_ptr)
1207
8.87k
                        .ok_or(CollectionAllocErr::AllocErr { layout })?
1208
8.87k
                        .cast();
1209
                }
1210
16.2k
                self.data = SmallVecData::from_heap(new_alloc, len);
1211
16.2k
                self.capacity = new_cap;
1212
0
            }
1213
16.2k
            Ok(())
1214
        }
1215
16.2k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::try_grow
1216
1217
    /// Reserve capacity for `additional` more elements to be inserted.
1218
    ///
1219
    /// May reserve more space to avoid frequent reallocations.
1220
    ///
1221
    /// Panics if the capacity computation overflows `usize`.
1222
    #[inline]
1223
793k
    pub fn reserve(&mut self, additional: usize) {
1224
793k
        infallible(self.try_reserve(additional))
1225
793k
    }
<smallvec::SmallVec<[char; 59]>>::reserve
Line
Count
Source
1223
766k
    pub fn reserve(&mut self, additional: usize) {
1224
766k
        infallible(self.try_reserve(additional))
1225
766k
    }
Unexecuted instantiation: <smallvec::SmallVec<[char; 253]>>::reserve
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::reserve
Line
Count
Source
1223
27.0k
    pub fn reserve(&mut self, additional: usize) {
1224
27.0k
        infallible(self.try_reserve(additional))
1225
27.0k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::reserve
1226
1227
    /// Internal method used to grow in push() and insert(), where we know already we have to grow.
1228
    #[cold]
1229
844k
    fn reserve_one_unchecked(&mut self) {
1230
844k
        debug_assert_eq!(self.len(), self.capacity());
1231
844k
        let new_cap = self.len()
1232
844k
            .checked_add(1)
1233
844k
            .and_then(usize::checked_next_power_of_two)
1234
844k
            .expect("capacity overflow");
1235
844k
        infallible(self.try_grow(new_cap))
1236
844k
    }
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]>>::reserve_one_unchecked
Line
Count
Source
1229
18.0k
    fn reserve_one_unchecked(&mut self) {
1230
18.0k
        debug_assert_eq!(self.len(), self.capacity());
1231
18.0k
        let new_cap = self.len()
1232
18.0k
            .checked_add(1)
1233
18.0k
            .and_then(usize::checked_next_power_of_two)
1234
18.0k
            .expect("capacity overflow");
1235
18.0k
        infallible(self.try_grow(new_cap))
1236
18.0k
    }
<smallvec::SmallVec<[(usize, char); 59]>>::reserve_one_unchecked
Line
Count
Source
1229
784k
    fn reserve_one_unchecked(&mut self) {
1230
784k
        debug_assert_eq!(self.len(), self.capacity());
1231
784k
        let new_cap = self.len()
1232
784k
            .checked_add(1)
1233
784k
            .and_then(usize::checked_next_power_of_two)
1234
784k
            .expect("capacity overflow");
1235
784k
        infallible(self.try_grow(new_cap))
1236
784k
    }
Unexecuted instantiation: <smallvec::SmallVec<[char; 59]>>::reserve_one_unchecked
<smallvec::SmallVec<[char; 253]>>::reserve_one_unchecked
Line
Count
Source
1229
25.6k
    fn reserve_one_unchecked(&mut self) {
1230
25.6k
        debug_assert_eq!(self.len(), self.capacity());
1231
25.6k
        let new_cap = self.len()
1232
25.6k
            .checked_add(1)
1233
25.6k
            .and_then(usize::checked_next_power_of_two)
1234
25.6k
            .expect("capacity overflow");
1235
25.6k
        infallible(self.try_grow(new_cap))
1236
25.6k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::reserve_one_unchecked
Line
Count
Source
1229
16.2k
    fn reserve_one_unchecked(&mut self) {
1230
16.2k
        debug_assert_eq!(self.len(), self.capacity());
1231
16.2k
        let new_cap = self.len()
1232
16.2k
            .checked_add(1)
1233
16.2k
            .and_then(usize::checked_next_power_of_two)
1234
16.2k
            .expect("capacity overflow");
1235
16.2k
        infallible(self.try_grow(new_cap))
1236
16.2k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::reserve_one_unchecked
1237
1238
    /// Reserve capacity for `additional` more elements to be inserted.
1239
    ///
1240
    /// May reserve more space to avoid frequent reallocations.
1241
793k
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1242
        // prefer triple_mut() even if triple() would work so that the optimizer removes duplicated
1243
        // calls to it from callers.
1244
793k
        let (_, &mut len, cap) = self.triple_mut();
1245
793k
        if cap - len >= additional {
1246
513k
            return Ok(());
1247
279k
        }
1248
279k
        let new_cap = len
1249
279k
            .checked_add(additional)
1250
279k
            .and_then(usize::checked_next_power_of_two)
1251
279k
            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1252
279k
        self.try_grow(new_cap)
1253
793k
    }
<smallvec::SmallVec<[char; 59]>>::try_reserve
Line
Count
Source
1241
766k
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1242
        // prefer triple_mut() even if triple() would work so that the optimizer removes duplicated
1243
        // calls to it from callers.
1244
766k
        let (_, &mut len, cap) = self.triple_mut();
1245
766k
        if cap - len >= additional {
1246
486k
            return Ok(());
1247
279k
        }
1248
279k
        let new_cap = len
1249
279k
            .checked_add(additional)
1250
279k
            .and_then(usize::checked_next_power_of_two)
1251
279k
            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1252
279k
        self.try_grow(new_cap)
1253
766k
    }
Unexecuted instantiation: <smallvec::SmallVec<[char; 253]>>::try_reserve
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::try_reserve
Line
Count
Source
1241
27.0k
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1242
        // prefer triple_mut() even if triple() would work so that the optimizer removes duplicated
1243
        // calls to it from callers.
1244
27.0k
        let (_, &mut len, cap) = self.triple_mut();
1245
27.0k
        if cap - len >= additional {
1246
27.0k
            return Ok(());
1247
0
        }
1248
0
        let new_cap = len
1249
0
            .checked_add(additional)
1250
0
            .and_then(usize::checked_next_power_of_two)
1251
0
            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1252
0
        self.try_grow(new_cap)
1253
27.0k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::try_reserve
1254
1255
    /// Reserve the minimum capacity for `additional` more elements to be inserted.
1256
    ///
1257
    /// Panics if the new capacity overflows `usize`.
1258
0
    pub fn reserve_exact(&mut self, additional: usize) {
1259
0
        infallible(self.try_reserve_exact(additional))
1260
0
    }
1261
1262
    /// Reserve the minimum capacity for `additional` more elements to be inserted.
1263
0
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1264
0
        let (_, &mut len, cap) = self.triple_mut();
1265
0
        if cap - len >= additional {
1266
0
            return Ok(());
1267
0
        }
1268
0
        let new_cap = len
1269
0
            .checked_add(additional)
1270
0
            .ok_or(CollectionAllocErr::CapacityOverflow)?;
1271
0
        self.try_grow(new_cap)
1272
0
    }
1273
1274
    /// Shrink the capacity of the vector as much as possible.
1275
    ///
1276
    /// When possible, this will move data from an external heap buffer to the vector's inline
1277
    /// storage.
1278
0
    pub fn shrink_to_fit(&mut self) {
1279
0
        if !self.spilled() {
1280
0
            return;
1281
0
        }
1282
0
        let len = self.len();
1283
0
        if self.inline_size() >= len {
1284
0
            unsafe {
1285
0
                let (ptr, len) = self.data.heap();
1286
0
                self.data = SmallVecData::from_inline(MaybeUninit::uninit());
1287
0
                ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1288
0
                deallocate(ptr.0, self.capacity);
1289
0
                self.capacity = len;
1290
0
            }
1291
0
        } else if self.capacity() > len {
1292
0
            self.grow(len);
1293
0
        }
1294
0
    }
1295
1296
    /// Shorten the vector, keeping the first `len` elements and dropping the rest.
1297
    ///
1298
    /// If `len` is greater than or equal to the vector's current length, this has no
1299
    /// effect.
1300
    ///
1301
    /// This does not re-allocate.  If you want the vector's capacity to shrink, call
1302
    /// `shrink_to_fit` after truncating.
1303
6.94M
    pub fn truncate(&mut self, len: usize) {
1304
        unsafe {
1305
6.94M
            let (ptr, len_ptr, _) = self.triple_mut();
1306
6.94M
            let ptr = ptr.as_ptr();
1307
51.1M
            while len < *len_ptr {
1308
44.2M
                let last_index = *len_ptr - 1;
1309
44.2M
                *len_ptr = last_index;
1310
44.2M
                ptr::drop_in_place(ptr.add(last_index));
1311
44.2M
            }
1312
        }
1313
6.94M
    }
<smallvec::SmallVec<[(usize, char); 59]>>::truncate
Line
Count
Source
1303
766k
    pub fn truncate(&mut self, len: usize) {
1304
        unsafe {
1305
766k
            let (ptr, len_ptr, _) = self.triple_mut();
1306
766k
            let ptr = ptr.as_ptr();
1307
766k
            while len < *len_ptr {
1308
0
                let last_index = *len_ptr - 1;
1309
0
                *len_ptr = last_index;
1310
0
                ptr::drop_in_place(ptr.add(last_index));
1311
0
            }
1312
        }
1313
766k
    }
<smallvec::SmallVec<[char; 253]>>::truncate
Line
Count
Source
1303
224k
    pub fn truncate(&mut self, len: usize) {
1304
        unsafe {
1305
224k
            let (ptr, len_ptr, _) = self.triple_mut();
1306
224k
            let ptr = ptr.as_ptr();
1307
42.2M
            while len < *len_ptr {
1308
42.0M
                let last_index = *len_ptr - 1;
1309
42.0M
                *len_ptr = last_index;
1310
42.0M
                ptr::drop_in_place(ptr.add(last_index));
1311
42.0M
            }
1312
        }
1313
224k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::truncate
Line
Count
Source
1303
5.95M
    pub fn truncate(&mut self, len: usize) {
1304
        unsafe {
1305
5.95M
            let (ptr, len_ptr, _) = self.triple_mut();
1306
5.95M
            let ptr = ptr.as_ptr();
1307
8.08M
            while len < *len_ptr {
1308
2.13M
                let last_index = *len_ptr - 1;
1309
2.13M
                *len_ptr = last_index;
1310
2.13M
                ptr::drop_in_place(ptr.add(last_index));
1311
2.13M
            }
1312
        }
1313
5.95M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::truncate
1314
1315
    /// Extracts a slice containing the entire vector.
1316
    ///
1317
    /// Equivalent to `&s[..]`.
1318
0
    pub fn as_slice(&self) -> &[A::Item] {
1319
0
        self
1320
0
    }
1321
1322
    /// Extracts a mutable slice of the entire vector.
1323
    ///
1324
    /// Equivalent to `&mut s[..]`.
1325
0
    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1326
0
        self
1327
0
    }
1328
1329
    /// Remove the element at position `index`, replacing it with the last element.
1330
    ///
1331
    /// This does not preserve ordering, but is O(1).
1332
    ///
1333
    /// Panics if `index` is out of bounds.
1334
    #[inline]
1335
0
    pub fn swap_remove(&mut self, index: usize) -> A::Item {
1336
0
        let len = self.len();
1337
0
        self.swap(len - 1, index);
1338
0
        self.pop()
1339
0
            .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1340
0
    }
1341
1342
    /// Remove all elements from the vector.
1343
    #[inline]
1344
6.71M
    pub fn clear(&mut self) {
1345
6.71M
        self.truncate(0);
1346
6.71M
    }
<smallvec::SmallVec<[(usize, char); 59]>>::clear
Line
Count
Source
1344
766k
    pub fn clear(&mut self) {
1345
766k
        self.truncate(0);
1346
766k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::clear
Line
Count
Source
1344
5.95M
    pub fn clear(&mut self) {
1345
5.95M
        self.truncate(0);
1346
5.95M
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::clear
1347
1348
    /// Remove and return the element at position `index`, shifting all elements after it to the
1349
    /// left.
1350
    ///
1351
    /// Panics if `index` is out of bounds.
1352
9.51k
    pub fn remove(&mut self, index: usize) -> A::Item {
1353
        unsafe {
1354
9.51k
            let (ptr, len_ptr, _) = self.triple_mut();
1355
9.51k
            let len = *len_ptr;
1356
9.51k
            assert!(index < len);
1357
9.51k
            *len_ptr = len - 1;
1358
9.51k
            let ptr = ptr.as_ptr().add(index);
1359
9.51k
            let item = ptr::read(ptr);
1360
9.51k
            ptr::copy(ptr.add(1), ptr, len - index - 1);
1361
9.51k
            item
1362
        }
1363
9.51k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::remove
Line
Count
Source
1352
9.51k
    pub fn remove(&mut self, index: usize) -> A::Item {
1353
        unsafe {
1354
9.51k
            let (ptr, len_ptr, _) = self.triple_mut();
1355
9.51k
            let len = *len_ptr;
1356
9.51k
            assert!(index < len);
1357
9.51k
            *len_ptr = len - 1;
1358
9.51k
            let ptr = ptr.as_ptr().add(index);
1359
9.51k
            let item = ptr::read(ptr);
1360
9.51k
            ptr::copy(ptr.add(1), ptr, len - index - 1);
1361
9.51k
            item
1362
        }
1363
9.51k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::remove
1364
1365
    /// Insert an element at position `index`, shifting all elements after it to the right.
1366
    ///
1367
    /// Panics if `index > len`.
1368
0
    pub fn insert(&mut self, index: usize, element: A::Item) {
1369
        unsafe {
1370
0
            let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1371
0
            if *len_ptr == cap {
1372
0
                self.reserve_one_unchecked();
1373
0
                let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1374
0
                ptr = heap_ptr;
1375
0
                len_ptr = heap_len_ptr;
1376
0
            }
1377
0
            let mut ptr = ptr.as_ptr();
1378
0
            let len = *len_ptr;
1379
0
            if index > len {
1380
0
                panic!("index exceeds length");
1381
0
            }
1382
            // SAFETY: add is UB if index > len, but we panicked first
1383
0
            ptr = ptr.add(index);
1384
0
            if index < len {
1385
0
                // Shift element to the right of `index`.
1386
0
                ptr::copy(ptr, ptr.add(1), len - index);
1387
0
            }
1388
0
            *len_ptr = len + 1;
1389
0
            ptr::write(ptr, element);
1390
        }
1391
0
    }
1392
1393
    /// Insert multiple elements at position `index`, shifting all following elements toward the
1394
    /// back.
1395
0
    pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1396
0
        let mut iter = iterable.into_iter();
1397
0
        if index == self.len() {
1398
0
            return self.extend(iter);
1399
0
        }
1400
1401
0
        let (lower_size_bound, _) = iter.size_hint();
1402
0
        assert!(lower_size_bound <= core::isize::MAX as usize); // Ensure offset is indexable
1403
0
        assert!(index + lower_size_bound >= index); // Protect against overflow
1404
1405
0
        let mut num_added = 0;
1406
0
        let old_len = self.len();
1407
0
        assert!(index <= old_len);
1408
1409
        unsafe {
1410
            // Reserve space for `lower_size_bound` elements.
1411
0
            self.reserve(lower_size_bound);
1412
0
            let start = self.as_mut_ptr();
1413
0
            let ptr = start.add(index);
1414
1415
            // Move the trailing elements.
1416
0
            ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1417
1418
            // In case the iterator panics, don't double-drop the items we just copied above.
1419
0
            self.set_len(0);
1420
0
            let mut guard = DropOnPanic {
1421
0
                start,
1422
0
                skip: index..(index + lower_size_bound),
1423
0
                len: old_len + lower_size_bound,
1424
0
            };
1425
1426
            // The set_len above invalidates the previous pointers, so we must re-create them.
1427
0
            let start = self.as_mut_ptr();
1428
0
            let ptr = start.add(index);
1429
1430
0
            while num_added < lower_size_bound {
1431
0
                let element = match iter.next() {
1432
0
                    Some(x) => x,
1433
0
                    None => break,
1434
                };
1435
0
                let cur = ptr.add(num_added);
1436
0
                ptr::write(cur, element);
1437
0
                guard.skip.start += 1;
1438
0
                num_added += 1;
1439
            }
1440
1441
0
            if num_added < lower_size_bound {
1442
0
                // Iterator provided fewer elements than the hint. Move the tail backward.
1443
0
                ptr::copy(
1444
0
                    ptr.add(lower_size_bound),
1445
0
                    ptr.add(num_added),
1446
0
                    old_len - index,
1447
0
                );
1448
0
            }
1449
            // There are no more duplicate or uninitialized slots, so the guard is not needed.
1450
0
            self.set_len(old_len + num_added);
1451
0
            mem::forget(guard);
1452
        }
1453
1454
        // Insert any remaining elements one-by-one.
1455
0
        for element in iter {
1456
0
            self.insert(index + num_added, element);
1457
0
            num_added += 1;
1458
0
        }
1459
1460
        struct DropOnPanic<T> {
1461
            start: *mut T,
1462
            skip: Range<usize>, // Space we copied-out-of, but haven't written-to yet.
1463
            len: usize,
1464
        }
1465
1466
        impl<T> Drop for DropOnPanic<T> {
1467
0
            fn drop(&mut self) {
1468
0
                for i in 0..self.len {
1469
0
                    if !self.skip.contains(&i) {
1470
0
                        unsafe {
1471
0
                            ptr::drop_in_place(self.start.add(i));
1472
0
                        }
1473
0
                    }
1474
                }
1475
0
            }
1476
        }
1477
0
    }
1478
1479
    /// Convert a `SmallVec` to a `Vec`, without reallocating if the `SmallVec` has already spilled onto
1480
    /// the heap.
1481
0
    pub fn into_vec(mut self) -> Vec<A::Item> {
1482
0
        if self.spilled() {
1483
            unsafe {
1484
0
                let (ptr, &mut len) = self.data.heap_mut();
1485
0
                let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1486
0
                mem::forget(self);
1487
0
                v
1488
            }
1489
        } else {
1490
0
            self.into_iter().collect()
1491
        }
1492
0
    }
1493
1494
    /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the `SmallVec` has already spilled
1495
    /// onto the heap.
1496
    ///
1497
    /// Note that this will drop any excess capacity.
1498
0
    pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1499
0
        self.into_vec().into_boxed_slice()
1500
0
    }
1501
1502
    /// Convert the `SmallVec` into an `A` if possible. Otherwise return `Err(Self)`.
1503
    ///
1504
    /// This method returns `Err(Self)` if the `SmallVec` is too short (and the `A` contains uninitialized elements),
1505
    /// or if the `SmallVec` is too long (and all the elements were spilled to the heap).
1506
0
    pub fn into_inner(self) -> Result<A, Self> {
1507
0
        if self.spilled() || self.len() != A::size() {
1508
            // Note: A::size, not Self::inline_capacity
1509
0
            Err(self)
1510
        } else {
1511
            unsafe {
1512
0
                let data = ptr::read(&self.data);
1513
0
                mem::forget(self);
1514
0
                Ok(data.into_inline().assume_init())
1515
            }
1516
        }
1517
0
    }
1518
1519
    /// Retains only the elements specified by the predicate.
1520
    ///
1521
    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1522
    /// This method operates in place and preserves the order of the retained
1523
    /// elements.
1524
0
    pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1525
0
        let mut del = 0;
1526
0
        let len = self.len();
1527
0
        for i in 0..len {
1528
0
            if !f(&mut self[i]) {
1529
0
                del += 1;
1530
0
            } else if del > 0 {
1531
0
                self.swap(i - del, i);
1532
0
            }
1533
        }
1534
0
        self.truncate(len - del);
1535
0
    }
1536
1537
    /// Retains only the elements specified by the predicate.
1538
    ///
1539
    /// This method is identical in behaviour to [`retain`]; it is included only
1540
    /// to maintain api-compatibility with `std::Vec`, where the methods are
1541
    /// separate for historical reasons.
1542
0
    pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1543
0
        self.retain(f)
1544
0
    }
1545
1546
    /// Removes consecutive duplicate elements.
1547
0
    pub fn dedup(&mut self)
1548
0
    where
1549
0
        A::Item: PartialEq<A::Item>,
1550
    {
1551
0
        self.dedup_by(|a, b| a == b);
1552
0
    }
1553
1554
    /// Removes consecutive duplicate elements using the given equality relation.
1555
0
    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1556
0
    where
1557
0
        F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1558
    {
1559
        // See the implementation of Vec::dedup_by in the
1560
        // standard library for an explanation of this algorithm.
1561
0
        let len = self.len();
1562
0
        if len <= 1 {
1563
0
            return;
1564
0
        }
1565
1566
0
        let ptr = self.as_mut_ptr();
1567
0
        let mut w: usize = 1;
1568
1569
        unsafe {
1570
0
            for r in 1..len {
1571
0
                let p_r = ptr.add(r);
1572
0
                let p_wm1 = ptr.add(w - 1);
1573
0
                if !same_bucket(&mut *p_r, &mut *p_wm1) {
1574
0
                    if r != w {
1575
0
                        let p_w = p_wm1.add(1);
1576
0
                        mem::swap(&mut *p_r, &mut *p_w);
1577
0
                    }
1578
0
                    w += 1;
1579
0
                }
1580
            }
1581
        }
1582
1583
0
        self.truncate(w);
1584
0
    }
1585
1586
    /// Removes consecutive elements that map to the same key.
1587
0
    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1588
0
    where
1589
0
        F: FnMut(&mut A::Item) -> K,
1590
0
        K: PartialEq<K>,
1591
    {
1592
0
        self.dedup_by(|a, b| key(a) == key(b));
1593
0
    }
1594
1595
    /// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`.
1596
    ///
1597
    /// If `new_len` is greater than `len`, the `SmallVec` is extended by the difference, with each
1598
    /// additional slot filled with the result of calling the closure `f`. The return values from `f`
1599
    /// will end up in the `SmallVec` in the order they have been generated.
1600
    ///
1601
    /// If `new_len` is less than `len`, the `SmallVec` is simply truncated.
1602
    ///
1603
    /// This method uses a closure to create new values on every push. If you'd rather `Clone` a given
1604
    /// value, use `resize`. If you want to use the `Default` trait to generate values, you can pass
1605
    /// `Default::default()` as the second argument.
1606
    ///
1607
    /// Added for `std::vec::Vec` compatibility (added in Rust 1.33.0)
1608
    ///
1609
    /// ```
1610
    /// # use smallvec::{smallvec, SmallVec};
1611
    /// let mut vec : SmallVec<[_; 4]> = smallvec![1, 2, 3];
1612
    /// vec.resize_with(5, Default::default);
1613
    /// assert_eq!(&*vec, &[1, 2, 3, 0, 0]);
1614
    ///
1615
    /// let mut vec : SmallVec<[_; 4]> = smallvec![];
1616
    /// let mut p = 1;
1617
    /// vec.resize_with(4, || { p *= 2; p });
1618
    /// assert_eq!(&*vec, &[2, 4, 8, 16]);
1619
    /// ```
1620
0
    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1621
0
    where
1622
0
        F: FnMut() -> A::Item,
1623
    {
1624
0
        let old_len = self.len();
1625
0
        if old_len < new_len {
1626
0
            let mut f = f;
1627
0
            let additional = new_len - old_len;
1628
0
            self.reserve(additional);
1629
0
            for _ in 0..additional {
1630
0
                self.push(f());
1631
0
            }
1632
0
        } else if old_len > new_len {
1633
0
            self.truncate(new_len);
1634
0
        }
1635
0
    }
1636
1637
    /// Creates a `SmallVec` directly from the raw components of another
1638
    /// `SmallVec`.
1639
    ///
1640
    /// # Safety
1641
    ///
1642
    /// This is highly unsafe, due to the number of invariants that aren't
1643
    /// checked:
1644
    ///
1645
    /// * `ptr` needs to have been previously allocated via `SmallVec` for its
1646
    ///   spilled storage (at least, it's highly likely to be incorrect if it
1647
    ///   wasn't).
1648
    /// * `ptr`'s `A::Item` type needs to be the same size and alignment that
1649
    ///   it was allocated with
1650
    /// * `length` needs to be less than or equal to `capacity`.
1651
    /// * `capacity` needs to be the capacity that the pointer was allocated
1652
    ///   with.
1653
    ///
1654
    /// Violating these may cause problems like corrupting the allocator's
1655
    /// internal data structures.
1656
    ///
1657
    /// Additionally, `capacity` must be greater than the amount of inline
1658
    /// storage `A` has; that is, the new `SmallVec` must need to spill over
1659
    /// into heap allocated storage. This condition is asserted against.
1660
    ///
1661
    /// The ownership of `ptr` is effectively transferred to the
1662
    /// `SmallVec` which may then deallocate, reallocate or change the
1663
    /// contents of memory pointed to by the pointer at will. Ensure
1664
    /// that nothing else uses the pointer after calling this
1665
    /// function.
1666
    ///
1667
    /// # Examples
1668
    ///
1669
    /// ```
1670
    /// # use smallvec::{smallvec, SmallVec};
1671
    /// use std::mem;
1672
    /// use std::ptr;
1673
    ///
1674
    /// fn main() {
1675
    ///     let mut v: SmallVec<[_; 1]> = smallvec![1, 2, 3];
1676
    ///
1677
    ///     // Pull out the important parts of `v`.
1678
    ///     let p = v.as_mut_ptr();
1679
    ///     let len = v.len();
1680
    ///     let cap = v.capacity();
1681
    ///     let spilled = v.spilled();
1682
    ///
1683
    ///     unsafe {
1684
    ///         // Forget all about `v`. The heap allocation that stored the
1685
    ///         // three values won't be deallocated.
1686
    ///         mem::forget(v);
1687
    ///
1688
    ///         // Overwrite memory with [4, 5, 6].
1689
    ///         //
1690
    ///         // This is only safe if `spilled` is true! Otherwise, we are
1691
    ///         // writing into the old `SmallVec`'s inline storage on the
1692
    ///         // stack.
1693
    ///         assert!(spilled);
1694
    ///         for i in 0..len {
1695
    ///             ptr::write(p.add(i), 4 + i);
1696
    ///         }
1697
    ///
1698
    ///         // Put everything back together into a SmallVec with a different
1699
    ///         // amount of inline storage, but which is still less than `cap`.
1700
    ///         let rebuilt = SmallVec::<[_; 2]>::from_raw_parts(p, len, cap);
1701
    ///         assert_eq!(&*rebuilt, &[4, 5, 6]);
1702
    ///     }
1703
    /// }
1704
    #[inline]
1705
0
    pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1706
        // SAFETY: We require caller to provide same ptr as we alloc
1707
        // and we never alloc null pointer.
1708
0
        let ptr = unsafe {
1709
0
            debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1710
0
            NonNull::new_unchecked(ptr)
1711
        };
1712
0
        assert!(capacity > Self::inline_capacity());
1713
0
        SmallVec {
1714
0
            capacity,
1715
0
            data: SmallVecData::from_heap(ptr, length),
1716
0
        }
1717
0
    }
1718
1719
    /// Returns a raw pointer to the vector's buffer.
1720
378k
    pub fn as_ptr(&self) -> *const A::Item {
1721
        // We shadow the slice method of the same name to avoid going through
1722
        // `deref`, which creates an intermediate reference that may place
1723
        // additional safety constraints on the contents of the slice.
1724
378k
        self.triple().0.as_ptr()
1725
378k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::as_ptr
Line
Count
Source
1720
378k
    pub fn as_ptr(&self) -> *const A::Item {
1721
        // We shadow the slice method of the same name to avoid going through
1722
        // `deref`, which creates an intermediate reference that may place
1723
        // additional safety constraints on the contents of the slice.
1724
378k
        self.triple().0.as_ptr()
1725
378k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::as_ptr
1726
1727
    /// Returns a raw mutable pointer to the vector's buffer.
1728
53.0k
    pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1729
        // We shadow the slice method of the same name to avoid going through
1730
        // `deref_mut`, which creates an intermediate reference that may place
1731
        // additional safety constraints on the contents of the slice.
1732
53.0k
        self.triple_mut().0.as_ptr()
1733
53.0k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]>>::as_mut_ptr
Line
Count
Source
1728
53.0k
    pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1729
        // We shadow the slice method of the same name to avoid going through
1730
        // `deref_mut`, which creates an intermediate reference that may place
1731
        // additional safety constraints on the contents of the slice.
1732
53.0k
        self.triple_mut().0.as_ptr()
1733
53.0k
    }
Unexecuted instantiation: <smallvec::SmallVec<_>>::as_mut_ptr
1734
}
1735
1736
impl<A: Array> SmallVec<A>
1737
where
1738
    A::Item: Copy,
1739
{
1740
    /// Copy the elements from a slice into a new `SmallVec`.
1741
    ///
1742
    /// For slices of `Copy` types, this is more efficient than `SmallVec::from(slice)`.
1743
0
    pub fn from_slice(slice: &[A::Item]) -> Self {
1744
0
        let len = slice.len();
1745
0
        if len <= Self::inline_capacity() {
1746
0
            SmallVec {
1747
0
                capacity: len,
1748
0
                data: SmallVecData::from_inline(unsafe {
1749
0
                    let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1750
0
                    ptr::copy_nonoverlapping(
1751
0
                        slice.as_ptr(),
1752
0
                        data.as_mut_ptr() as *mut A::Item,
1753
0
                        len,
1754
0
                    );
1755
0
                    data
1756
0
                }),
1757
0
            }
1758
        } else {
1759
0
            let mut b = slice.to_vec();
1760
0
            let cap = b.capacity();
1761
0
            let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1762
0
            mem::forget(b);
1763
0
            SmallVec {
1764
0
                capacity: cap,
1765
0
                data: SmallVecData::from_heap(ptr, len),
1766
0
            }
1767
        }
1768
0
    }
1769
1770
    /// Copy elements from a slice into the vector at position `index`, shifting any following
1771
    /// elements toward the back.
1772
    ///
1773
    /// For slices of `Copy` types, this is more efficient than `insert`.
1774
    #[inline]
1775
0
    pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1776
0
        self.reserve(slice.len());
1777
1778
0
        let len = self.len();
1779
0
        assert!(index <= len);
1780
1781
0
        unsafe {
1782
0
            let slice_ptr = slice.as_ptr();
1783
0
            let ptr = self.as_mut_ptr().add(index);
1784
0
            ptr::copy(ptr, ptr.add(slice.len()), len - index);
1785
0
            ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1786
0
            self.set_len(len + slice.len());
1787
0
        }
1788
0
    }
1789
1790
    /// Copy elements from a slice and append them to the vector.
1791
    ///
1792
    /// For slices of `Copy` types, this is more efficient than `extend`.
1793
    #[inline]
1794
0
    pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1795
0
        let len = self.len();
1796
0
        self.insert_from_slice(len, slice);
1797
0
    }
1798
}
1799
1800
impl<A: Array> SmallVec<A>
1801
where
1802
    A::Item: Clone,
1803
{
1804
    /// Resizes the vector so that its length is equal to `len`.
1805
    ///
1806
    /// If `len` is less than the current length, the vector simply truncated.
1807
    ///
1808
    /// If `len` is greater than the current length, `value` is appended to the
1809
    /// vector until its length equals `len`.
1810
0
    pub fn resize(&mut self, len: usize, value: A::Item) {
1811
0
        let old_len = self.len();
1812
1813
0
        if len > old_len {
1814
0
            self.extend(repeat(value).take(len - old_len));
1815
0
        } else {
1816
0
            self.truncate(len);
1817
0
        }
1818
0
    }
1819
1820
    /// Creates a `SmallVec` with `n` copies of `elem`.
1821
    /// ```
1822
    /// use smallvec::SmallVec;
1823
    ///
1824
    /// let v = SmallVec::<[char; 128]>::from_elem('d', 2);
1825
    /// assert_eq!(v, SmallVec::from_buf(['d', 'd']));
1826
    /// ```
1827
0
    pub fn from_elem(elem: A::Item, n: usize) -> Self {
1828
0
        if n > Self::inline_capacity() {
1829
0
            vec![elem; n].into()
1830
        } else {
1831
0
            let mut v = SmallVec::<A>::new();
1832
            unsafe {
1833
0
                let (ptr, len_ptr, _) = v.triple_mut();
1834
0
                let ptr = ptr.as_ptr();
1835
0
                let mut local_len = SetLenOnDrop::new(len_ptr);
1836
1837
0
                for i in 0..n {
1838
0
                    ::core::ptr::write(ptr.add(i), elem.clone());
1839
0
                    local_len.increment_len(1);
1840
0
                }
1841
            }
1842
0
            v
1843
        }
1844
0
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::from_elem
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::from_elem
Unexecuted instantiation: <smallvec::SmallVec<_>>::from_elem
1845
}
1846
1847
impl<A: Array> ops::Deref for SmallVec<A> {
1848
    type Target = [A::Item];
1849
    #[inline]
1850
100M
    fn deref(&self) -> &[A::Item] {
1851
        unsafe {
1852
100M
            let (ptr, len, _) = self.triple();
1853
100M
            slice::from_raw_parts(ptr.as_ptr(), len)
1854
        }
1855
100M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]> as core::ops::deref::Deref>::deref
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]> as core::ops::deref::Deref>::deref
Line
Count
Source
1850
7.80k
    fn deref(&self) -> &[A::Item] {
1851
        unsafe {
1852
7.80k
            let (ptr, len, _) = self.triple();
1853
7.80k
            slice::from_raw_parts(ptr.as_ptr(), len)
1854
        }
1855
7.80k
    }
<smallvec::SmallVec<[(usize, char); 59]> as core::ops::deref::Deref>::deref
Line
Count
Source
1850
766k
    fn deref(&self) -> &[A::Item] {
1851
        unsafe {
1852
766k
            let (ptr, len, _) = self.triple();
1853
766k
            slice::from_raw_parts(ptr.as_ptr(), len)
1854
        }
1855
766k
    }
<smallvec::SmallVec<[char; 59]> as core::ops::deref::Deref>::deref
Line
Count
Source
1850
766k
    fn deref(&self) -> &[A::Item] {
1851
        unsafe {
1852
766k
            let (ptr, len, _) = self.triple();
1853
766k
            slice::from_raw_parts(ptr.as_ptr(), len)
1854
        }
1855
766k
    }
<smallvec::SmallVec<[char; 253]> as core::ops::deref::Deref>::deref
Line
Count
Source
1850
721k
    fn deref(&self) -> &[A::Item] {
1851
        unsafe {
1852
721k
            let (ptr, len, _) = self.triple();
1853
721k
            slice::from_raw_parts(ptr.as_ptr(), len)
1854
        }
1855
721k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::ops::deref::Deref>::deref
Line
Count
Source
1850
97.8M
    fn deref(&self) -> &[A::Item] {
1851
        unsafe {
1852
97.8M
            let (ptr, len, _) = self.triple();
1853
97.8M
            slice::from_raw_parts(ptr.as_ptr(), len)
1854
        }
1855
97.8M
    }
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::deref::Deref>::deref
1856
}
1857
1858
impl<A: Array> ops::DerefMut for SmallVec<A> {
1859
    #[inline]
1860
75.3M
    fn deref_mut(&mut self) -> &mut [A::Item] {
1861
75.3M
        unsafe {
1862
75.3M
            let (ptr, &mut len, _) = self.triple_mut();
1863
75.3M
            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1864
75.3M
        }
1865
75.3M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]> as core::ops::deref::DerefMut>::deref_mut
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]> as core::ops::deref::DerefMut>::deref_mut
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]> as core::ops::deref::DerefMut>::deref_mut
Line
Count
Source
1860
13.7k
    fn deref_mut(&mut self) -> &mut [A::Item] {
1861
13.7k
        unsafe {
1862
13.7k
            let (ptr, &mut len, _) = self.triple_mut();
1863
13.7k
            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1864
13.7k
        }
1865
13.7k
    }
<smallvec::SmallVec<[(usize, char); 59]> as core::ops::deref::DerefMut>::deref_mut
Line
Count
Source
1860
64.2M
    fn deref_mut(&mut self) -> &mut [A::Item] {
1861
64.2M
        unsafe {
1862
64.2M
            let (ptr, &mut len, _) = self.triple_mut();
1863
64.2M
            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1864
64.2M
        }
1865
64.2M
    }
<smallvec::SmallVec<[char; 59]> as core::ops::deref::DerefMut>::deref_mut
Line
Count
Source
1860
486k
    fn deref_mut(&mut self) -> &mut [A::Item] {
1861
486k
        unsafe {
1862
486k
            let (ptr, &mut len, _) = self.triple_mut();
1863
486k
            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1864
486k
        }
1865
486k
    }
<smallvec::SmallVec<[char; 253]> as core::ops::deref::DerefMut>::deref_mut
Line
Count
Source
1860
2.22M
    fn deref_mut(&mut self) -> &mut [A::Item] {
1861
2.22M
        unsafe {
1862
2.22M
            let (ptr, &mut len, _) = self.triple_mut();
1863
2.22M
            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1864
2.22M
        }
1865
2.22M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::ops::deref::DerefMut>::deref_mut
Line
Count
Source
1860
8.34M
    fn deref_mut(&mut self) -> &mut [A::Item] {
1861
8.34M
        unsafe {
1862
8.34M
            let (ptr, &mut len, _) = self.triple_mut();
1863
8.34M
            slice::from_raw_parts_mut(ptr.as_ptr(), len)
1864
8.34M
        }
1865
8.34M
    }
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::deref::DerefMut>::deref_mut
1866
}
1867
1868
impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1869
    #[inline]
1870
0
    fn as_ref(&self) -> &[A::Item] {
1871
0
        self
1872
0
    }
1873
}
1874
1875
impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1876
    #[inline]
1877
0
    fn as_mut(&mut self) -> &mut [A::Item] {
1878
0
        self
1879
0
    }
1880
}
1881
1882
impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1883
    #[inline]
1884
0
    fn borrow(&self) -> &[A::Item] {
1885
0
        self
1886
0
    }
1887
}
1888
1889
impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1890
    #[inline]
1891
0
    fn borrow_mut(&mut self) -> &mut [A::Item] {
1892
0
        self
1893
0
    }
1894
}
1895
1896
#[cfg(feature = "write")]
1897
#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
1898
impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1899
    #[inline]
1900
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1901
        self.extend_from_slice(buf);
1902
        Ok(buf.len())
1903
    }
1904
1905
    #[inline]
1906
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1907
        self.extend_from_slice(buf);
1908
        Ok(())
1909
    }
1910
1911
    #[inline]
1912
    fn flush(&mut self) -> io::Result<()> {
1913
        Ok(())
1914
    }
1915
}
1916
1917
#[cfg(feature = "serde")]
1918
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1919
impl<A: Array> Serialize for SmallVec<A>
1920
where
1921
    A::Item: Serialize,
1922
{
1923
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1924
        let mut state = serializer.serialize_seq(Some(self.len()))?;
1925
        for item in self {
1926
            state.serialize_element(&item)?;
1927
        }
1928
        state.end()
1929
    }
1930
}
1931
1932
#[cfg(feature = "serde")]
1933
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1934
impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
1935
where
1936
    A::Item: Deserialize<'de>,
1937
{
1938
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1939
        deserializer.deserialize_seq(SmallVecVisitor {
1940
            phantom: PhantomData,
1941
        })
1942
    }
1943
}
1944
1945
#[cfg(feature = "serde")]
1946
struct SmallVecVisitor<A> {
1947
    phantom: PhantomData<A>,
1948
}
1949
1950
#[cfg(feature = "serde")]
1951
impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
1952
where
1953
    A::Item: Deserialize<'de>,
1954
{
1955
    type Value = SmallVec<A>;
1956
1957
    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1958
        formatter.write_str("a sequence")
1959
    }
1960
1961
    fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
1962
    where
1963
        B: SeqAccess<'de>,
1964
    {
1965
        use serde::de::Error;
1966
        let len = seq.size_hint().unwrap_or(0);
1967
        let mut values = SmallVec::new();
1968
        values.try_reserve(len).map_err(B::Error::custom)?;
1969
1970
        while let Some(value) = seq.next_element()? {
1971
            values.push(value);
1972
        }
1973
1974
        Ok(values)
1975
    }
1976
}
1977
1978
#[cfg(feature = "malloc_size_of")]
1979
impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
1980
    fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
1981
        if self.spilled() {
1982
            unsafe { ops.malloc_size_of(self.as_ptr()) }
1983
        } else {
1984
            0
1985
        }
1986
    }
1987
}
1988
1989
#[cfg(feature = "malloc_size_of")]
1990
impl<A> MallocSizeOf for SmallVec<A>
1991
where
1992
    A: Array,
1993
    A::Item: MallocSizeOf,
1994
{
1995
    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
1996
        let mut n = self.shallow_size_of(ops);
1997
        for elem in self.iter() {
1998
            n += elem.size_of(ops);
1999
        }
2000
        n
2001
    }
2002
}
2003
2004
#[cfg(feature = "specialization")]
2005
trait SpecFrom<A: Array, S> {
2006
    fn spec_from(slice: S) -> SmallVec<A>;
2007
}
2008
2009
#[cfg(feature = "specialization")]
2010
mod specialization;
2011
2012
#[cfg(feature = "arbitrary")]
2013
mod arbitrary;
2014
2015
#[cfg(feature = "specialization")]
2016
impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2017
where
2018
    A::Item: Copy,
2019
{
2020
    #[inline]
2021
    fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2022
        SmallVec::from_slice(slice)
2023
    }
2024
}
2025
2026
impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2027
where
2028
    A::Item: Clone,
2029
{
2030
    #[cfg(not(feature = "specialization"))]
2031
    #[inline]
2032
0
    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2033
0
        slice.iter().cloned().collect()
2034
0
    }
2035
2036
    #[cfg(feature = "specialization")]
2037
    #[inline]
2038
    fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2039
        SmallVec::spec_from(slice)
2040
    }
2041
}
2042
2043
impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2044
    #[inline]
2045
0
    fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2046
0
        SmallVec::from_vec(vec)
2047
0
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]> as core::convert::From<alloc::vec::Vec<core::mem::maybe_uninit::MaybeUninit<httparse::Header>>>>::from
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]> as core::convert::From<alloc::vec::Vec<core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>>>>::from
Unexecuted instantiation: <smallvec::SmallVec<_> as core::convert::From<alloc::vec::Vec<<_ as smallvec::Array>::Item>>>::from
2048
}
2049
2050
impl<A: Array> From<A> for SmallVec<A> {
2051
    #[inline]
2052
0
    fn from(array: A) -> SmallVec<A> {
2053
0
        SmallVec::from_buf(array)
2054
0
    }
2055
}
2056
2057
impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2058
    type Output = I::Output;
2059
2060
697k
    fn index(&self, index: I) -> &I::Output {
2061
697k
        &(**self)[index]
2062
697k
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]> as core::ops::index::Index<core::ops::range::RangeTo<usize>>>::index
<smallvec::SmallVec<[char; 253]> as core::ops::index::Index<core::ops::range::RangeFrom<usize>>>::index
Line
Count
Source
2060
690k
    fn index(&self, index: I) -> &I::Output {
2061
690k
        &(**self)[index]
2062
690k
    }
<smallvec::SmallVec<[char; 253]> as core::ops::index::Index<core::ops::range::RangeFull>>::index
Line
Count
Source
2060
6.96k
    fn index(&self, index: I) -> &I::Output {
2061
6.96k
        &(**self)[index]
2062
6.96k
    }
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::index::Index<_>>::index
2063
}
2064
2065
impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2066
11.3M
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
11.3M
        &mut (&mut **self)[index]
2068
11.3M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]> as core::ops::index::IndexMut<core::ops::range::RangeTo<usize>>>::index_mut
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut
Line
Count
Source
2066
13.7k
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
13.7k
        &mut (&mut **self)[index]
2068
13.7k
    }
<smallvec::SmallVec<[(usize, char); 59]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut
Line
Count
Source
2066
487k
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
487k
        &mut (&mut **self)[index]
2068
487k
    }
<smallvec::SmallVec<[char; 59]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut
Line
Count
Source
2066
486k
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
486k
        &mut (&mut **self)[index]
2068
486k
    }
<smallvec::SmallVec<[char; 253]> as core::ops::index::IndexMut<core::ops::range::RangeFrom<usize>>>::index_mut
Line
Count
Source
2066
1.99M
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
1.99M
        &mut (&mut **self)[index]
2068
1.99M
    }
<smallvec::SmallVec<[char; 253]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut
Line
Count
Source
2066
11.8k
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
11.8k
        &mut (&mut **self)[index]
2068
11.8k
    }
Unexecuted instantiation: <smallvec::SmallVec<[char; 253]> as core::ops::index::IndexMut<usize>>::index_mut
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::ops::index::IndexMut<core::ops::range::RangeFrom<usize>>>::index_mut
Line
Count
Source
2066
7.13M
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
7.13M
        &mut (&mut **self)[index]
2068
7.13M
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut
Line
Count
Source
2066
1.21M
    fn index_mut(&mut self, index: I) -> &mut I::Output {
2067
1.21M
        &mut (&mut **self)[index]
2068
1.21M
    }
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::index::IndexMut<_>>::index_mut
2069
}
2070
2071
#[allow(deprecated)]
2072
impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2073
where
2074
    A::Item: Copy,
2075
{
2076
0
    fn extend_from_slice(&mut self, other: &[A::Item]) {
2077
0
        SmallVec::extend_from_slice(self, other)
2078
0
    }
2079
}
2080
2081
impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2082
    #[inline]
2083
0
    fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2084
0
        let mut v = SmallVec::new();
2085
0
        v.extend(iterable);
2086
0
        v
2087
0
    }
2088
}
2089
2090
impl<A: Array> Extend<A::Item> for SmallVec<A> {
2091
793k
    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092
793k
        let mut iter = iterable.into_iter();
2093
793k
        let (lower_size_bound, _) = iter.size_hint();
2094
793k
        self.reserve(lower_size_bound);
2095
2096
        unsafe {
2097
793k
            let (ptr, len_ptr, cap) = self.triple_mut();
2098
793k
            let ptr = ptr.as_ptr();
2099
793k
            let mut len = SetLenOnDrop::new(len_ptr);
2100
64.0M
            while len.get() < cap {
2101
64.0M
                if let Some(out) = iter.next() {
2102
63.2M
                    ptr::write(ptr.add(len.get()), out);
2103
63.2M
                    len.increment_len(1);
2104
63.2M
                } else {
2105
789k
                    return;
2106
                }
2107
            }
2108
        }
2109
2110
3.87k
        for elem in iter {
2111
0
            self.push(elem);
2112
0
        }
2113
793k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::iter::traits::collect::Extend<icu_normalizer::CharacterAndClass>>::extend::<core::iter::adapters::map::Map<zerovec::zerovec::slice::ZeroSliceIter<u16>, <icu_normalizer::Decomposition<core::iter::adapters::copied::Copied<core::slice::iter::Iter<char>>>>::push_decomposition16::{closure#3}>>
Line
Count
Source
2091
17.1k
    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092
17.1k
        let mut iter = iterable.into_iter();
2093
17.1k
        let (lower_size_bound, _) = iter.size_hint();
2094
17.1k
        self.reserve(lower_size_bound);
2095
2096
        unsafe {
2097
17.1k
            let (ptr, len_ptr, cap) = self.triple_mut();
2098
17.1k
            let ptr = ptr.as_ptr();
2099
17.1k
            let mut len = SetLenOnDrop::new(len_ptr);
2100
51.4k
            while len.get() < cap {
2101
51.4k
                if let Some(out) = iter.next() {
2102
34.3k
                    ptr::write(ptr.add(len.get()), out);
2103
34.3k
                    len.increment_len(1);
2104
34.3k
                } else {
2105
17.1k
                    return;
2106
                }
2107
            }
2108
        }
2109
2110
0
        for elem in iter {
2111
0
            self.push(elem);
2112
0
        }
2113
17.1k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::iter::traits::collect::Extend<icu_normalizer::CharacterAndClass>>::extend::<core::iter::adapters::map::Map<zerovec::zerovec::slice::ZeroSliceIter<u16>, <icu_normalizer::Decomposition<utf8_iter::Utf8Chars>>::push_decomposition16::{closure#3}>>
Line
Count
Source
2091
5.42k
    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092
5.42k
        let mut iter = iterable.into_iter();
2093
5.42k
        let (lower_size_bound, _) = iter.size_hint();
2094
5.42k
        self.reserve(lower_size_bound);
2095
2096
        unsafe {
2097
5.42k
            let (ptr, len_ptr, cap) = self.triple_mut();
2098
5.42k
            let ptr = ptr.as_ptr();
2099
5.42k
            let mut len = SetLenOnDrop::new(len_ptr);
2100
16.2k
            while len.get() < cap {
2101
16.2k
                if let Some(out) = iter.next() {
2102
10.8k
                    ptr::write(ptr.add(len.get()), out);
2103
10.8k
                    len.increment_len(1);
2104
10.8k
                } else {
2105
5.42k
                    return;
2106
                }
2107
            }
2108
        }
2109
2110
0
        for elem in iter {
2111
0
            self.push(elem);
2112
0
        }
2113
5.42k
    }
<smallvec::SmallVec<[char; 59]> as core::iter::traits::collect::Extend<char>>::extend::<idna::punycode::Decode<char, idna::punycode::InternalCaller>>
Line
Count
Source
2091
224k
    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092
224k
        let mut iter = iterable.into_iter();
2093
224k
        let (lower_size_bound, _) = iter.size_hint();
2094
224k
        self.reserve(lower_size_bound);
2095
2096
        unsafe {
2097
224k
            let (ptr, len_ptr, cap) = self.triple_mut();
2098
224k
            let ptr = ptr.as_ptr();
2099
224k
            let mut len = SetLenOnDrop::new(len_ptr);
2100
40.7M
            while len.get() < cap {
2101
40.7M
                if let Some(out) = iter.next() {
2102
40.4M
                    ptr::write(ptr.add(len.get()), out);
2103
40.4M
                    len.increment_len(1);
2104
40.4M
                } else {
2105
223k
                    return;
2106
                }
2107
            }
2108
        }
2109
2110
1.68k
        for elem in iter {
2111
0
            self.push(elem);
2112
0
        }
2113
224k
    }
<smallvec::SmallVec<[char; 59]> as core::iter::traits::collect::Extend<char>>::extend::<idna::punycode::Decode<u8, idna::punycode::InternalCaller>>
Line
Count
Source
2091
541k
    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092
541k
        let mut iter = iterable.into_iter();
2093
541k
        let (lower_size_bound, _) = iter.size_hint();
2094
541k
        self.reserve(lower_size_bound);
2095
2096
        unsafe {
2097
541k
            let (ptr, len_ptr, cap) = self.triple_mut();
2098
541k
            let ptr = ptr.as_ptr();
2099
541k
            let mut len = SetLenOnDrop::new(len_ptr);
2100
23.3M
            while len.get() < cap {
2101
23.3M
                if let Some(out) = iter.next() {
2102
22.7M
                    ptr::write(ptr.add(len.get()), out);
2103
22.7M
                    len.increment_len(1);
2104
22.7M
                } else {
2105
539k
                    return;
2106
                }
2107
            }
2108
        }
2109
2110
2.17k
        for elem in iter {
2111
0
            self.push(elem);
2112
0
        }
2113
541k
    }
Unexecuted instantiation: <smallvec::SmallVec<[char; 253]> as core::iter::traits::collect::Extend<char>>::extend::<core::iter::adapters::map::Map<core::slice::iter::Iter<u8>, <idna::uts46::Uts46>::process_innermost::{closure#1}>>
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::iter::traits::collect::Extend<icu_normalizer::CharacterAndClass>>::extend::<[icu_normalizer::CharacterAndClass; 17]>
Line
Count
Source
2091
18
    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092
18
        let mut iter = iterable.into_iter();
2093
18
        let (lower_size_bound, _) = iter.size_hint();
2094
18
        self.reserve(lower_size_bound);
2095
2096
        unsafe {
2097
18
            let (ptr, len_ptr, cap) = self.triple_mut();
2098
18
            let ptr = ptr.as_ptr();
2099
18
            let mut len = SetLenOnDrop::new(len_ptr);
2100
324
            while len.get() < cap {
2101
312
                if let Some(out) = iter.next() {
2102
306
                    ptr::write(ptr.add(len.get()), out);
2103
306
                    len.increment_len(1);
2104
306
                } else {
2105
6
                    return;
2106
                }
2107
            }
2108
        }
2109
2110
12
        for elem in iter {
2111
0
            self.push(elem);
2112
0
        }
2113
18
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::iter::traits::collect::Extend<icu_normalizer::CharacterAndClass>>::extend::<core::iter::adapters::map::Map<zerovec::zerovec::slice::ZeroSliceIter<char>, <icu_normalizer::CharacterAndClass>::new_with_placeholder>>
Line
Count
Source
2091
4.40k
    fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2092
4.40k
        let mut iter = iterable.into_iter();
2093
4.40k
        let (lower_size_bound, _) = iter.size_hint();
2094
4.40k
        self.reserve(lower_size_bound);
2095
2096
        unsafe {
2097
4.40k
            let (ptr, len_ptr, cap) = self.triple_mut();
2098
4.40k
            let ptr = ptr.as_ptr();
2099
4.40k
            let mut len = SetLenOnDrop::new(len_ptr);
2100
9.31k
            while len.get() < cap {
2101
9.31k
                if let Some(out) = iter.next() {
2102
4.91k
                    ptr::write(ptr.add(len.get()), out);
2103
4.91k
                    len.increment_len(1);
2104
4.91k
                } else {
2105
4.40k
                    return;
2106
                }
2107
            }
2108
        }
2109
2110
0
        for elem in iter {
2111
0
            self.push(elem);
2112
0
        }
2113
4.40k
    }
Unexecuted instantiation: <smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::iter::traits::collect::Extend<icu_normalizer::CharacterAndClass>>::extend::<core::iter::adapters::map::Map<zerovec::zerovec::slice::ZeroSliceIter<u16>, <icu_normalizer::Decomposition<core::str::iter::Chars>>::push_decomposition16::{closure#3}>>
Unexecuted instantiation: <smallvec::SmallVec<_> as core::iter::traits::collect::Extend<<_ as smallvec::Array>::Item>>::extend::<_>
2114
}
2115
2116
impl<A: Array> fmt::Debug for SmallVec<A>
2117
where
2118
    A::Item: fmt::Debug,
2119
{
2120
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2121
0
        f.debug_list().entries(self.iter()).finish()
2122
0
    }
2123
}
2124
2125
impl<A: Array> Default for SmallVec<A> {
2126
    #[inline]
2127
766k
    fn default() -> SmallVec<A> {
2128
766k
        SmallVec::new()
2129
766k
    }
<smallvec::SmallVec<[(usize, char); 59]> as core::default::Default>::default
Line
Count
Source
2127
766k
    fn default() -> SmallVec<A> {
2128
766k
        SmallVec::new()
2129
766k
    }
Unexecuted instantiation: <smallvec::SmallVec<_> as core::default::Default>::default
2130
}
2131
2132
#[cfg(feature = "may_dangle")]
2133
unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2134
    fn drop(&mut self) {
2135
        unsafe {
2136
            if self.spilled() {
2137
                let (ptr, &mut len) = self.data.heap_mut();
2138
                Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2139
            } else {
2140
                ptr::drop_in_place(&mut self[..]);
2141
            }
2142
        }
2143
    }
2144
}
2145
2146
#[cfg(not(feature = "may_dangle"))]
2147
impl<A: Array> Drop for SmallVec<A> {
2148
2.79M
    fn drop(&mut self) {
2149
        unsafe {
2150
2.79M
            if self.spilled() {
2151
575k
                let (ptr, &mut len) = self.data.heap_mut();
2152
575k
                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2153
2.21M
            } else {
2154
2.21M
                ptr::drop_in_place(&mut self[..]);
2155
2.21M
            }
2156
        }
2157
2.79M
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]> as core::ops::drop::Drop>::drop
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]> as core::ops::drop::Drop>::drop
<smallvec::SmallVec<[idna::uts46::AlreadyAsciiLabel; 8]> as core::ops::drop::Drop>::drop
Line
Count
Source
2148
17.3k
    fn drop(&mut self) {
2149
        unsafe {
2150
17.3k
            if self.spilled() {
2151
3.59k
                let (ptr, &mut len) = self.data.heap_mut();
2152
3.59k
                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2153
13.7k
            } else {
2154
13.7k
                ptr::drop_in_place(&mut self[..]);
2155
13.7k
            }
2156
        }
2157
17.3k
    }
<smallvec::SmallVec<[(usize, char); 59]> as core::ops::drop::Drop>::drop
Line
Count
Source
2148
766k
    fn drop(&mut self) {
2149
        unsafe {
2150
766k
            if self.spilled() {
2151
279k
                let (ptr, &mut len) = self.data.heap_mut();
2152
279k
                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2153
487k
            } else {
2154
487k
                ptr::drop_in_place(&mut self[..]);
2155
487k
            }
2156
        }
2157
766k
    }
<smallvec::SmallVec<[char; 59]> as core::ops::drop::Drop>::drop
Line
Count
Source
2148
766k
    fn drop(&mut self) {
2149
        unsafe {
2150
766k
            if self.spilled() {
2151
279k
                let (ptr, &mut len) = self.data.heap_mut();
2152
279k
                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2153
486k
            } else {
2154
486k
                ptr::drop_in_place(&mut self[..]);
2155
486k
            }
2156
        }
2157
766k
    }
<smallvec::SmallVec<[char; 253]> as core::ops::drop::Drop>::drop
Line
Count
Source
2148
17.3k
    fn drop(&mut self) {
2149
        unsafe {
2150
17.3k
            if self.spilled() {
2151
5.45k
                let (ptr, &mut len) = self.data.heap_mut();
2152
5.45k
                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2153
11.8k
            } else {
2154
11.8k
                ptr::drop_in_place(&mut self[..]);
2155
11.8k
            }
2156
        }
2157
17.3k
    }
<smallvec::SmallVec<[icu_normalizer::CharacterAndClass; 17]> as core::ops::drop::Drop>::drop
Line
Count
Source
2148
1.22M
    fn drop(&mut self) {
2149
        unsafe {
2150
1.22M
            if self.spilled() {
2151
7.41k
                let (ptr, &mut len) = self.data.heap_mut();
2152
7.41k
                drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2153
1.21M
            } else {
2154
1.21M
                ptr::drop_in_place(&mut self[..]);
2155
1.21M
            }
2156
        }
2157
1.22M
    }
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::drop::Drop>::drop
2158
}
2159
2160
impl<A: Array> Clone for SmallVec<A>
2161
where
2162
    A::Item: Clone,
2163
{
2164
    #[inline]
2165
0
    fn clone(&self) -> SmallVec<A> {
2166
0
        SmallVec::from(self.as_slice())
2167
0
    }
2168
2169
0
    fn clone_from(&mut self, source: &Self) {
2170
        // Inspired from `impl Clone for Vec`.
2171
2172
        // drop anything that will not be overwritten
2173
0
        self.truncate(source.len());
2174
2175
        // self.len <= other.len due to the truncate above, so the
2176
        // slices here are always in-bounds.
2177
0
        let (init, tail) = source.split_at(self.len());
2178
2179
        // reuse the contained values' allocations/resources.
2180
0
        self.clone_from_slice(init);
2181
0
        self.extend(tail.iter().cloned());
2182
0
    }
2183
}
2184
2185
impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2186
where
2187
    A::Item: PartialEq<B::Item>,
2188
{
2189
    #[inline]
2190
0
    fn eq(&self, other: &SmallVec<B>) -> bool {
2191
0
        self[..] == other[..]
2192
0
    }
2193
}
2194
2195
impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2196
2197
impl<A: Array> PartialOrd for SmallVec<A>
2198
where
2199
    A::Item: PartialOrd,
2200
{
2201
    #[inline]
2202
0
    fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2203
0
        PartialOrd::partial_cmp(&**self, &**other)
2204
0
    }
2205
}
2206
2207
impl<A: Array> Ord for SmallVec<A>
2208
where
2209
    A::Item: Ord,
2210
{
2211
    #[inline]
2212
0
    fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2213
0
        Ord::cmp(&**self, &**other)
2214
0
    }
2215
}
2216
2217
impl<A: Array> Hash for SmallVec<A>
2218
where
2219
    A::Item: Hash,
2220
{
2221
0
    fn hash<H: Hasher>(&self, state: &mut H) {
2222
0
        (**self).hash(state)
2223
0
    }
2224
}
2225
2226
unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2227
2228
/// An iterator that consumes a `SmallVec` and yields its items by value.
2229
///
2230
/// Returned from [`SmallVec::into_iter`][1].
2231
///
2232
/// [1]: struct.SmallVec.html#method.into_iter
2233
pub struct IntoIter<A: Array> {
2234
    data: SmallVec<A>,
2235
    current: usize,
2236
    end: usize,
2237
}
2238
2239
impl<A: Array> fmt::Debug for IntoIter<A>
2240
where
2241
    A::Item: fmt::Debug,
2242
{
2243
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2244
0
        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2245
0
    }
2246
}
2247
2248
impl<A: Array + Clone> Clone for IntoIter<A>
2249
where
2250
    A::Item: Clone,
2251
{
2252
0
    fn clone(&self) -> IntoIter<A> {
2253
0
        SmallVec::from(self.as_slice()).into_iter()
2254
0
    }
2255
}
2256
2257
impl<A: Array> Drop for IntoIter<A> {
2258
0
    fn drop(&mut self) {
2259
0
        for _ in self {}
2260
0
    }
2261
}
2262
2263
impl<A: Array> Iterator for IntoIter<A> {
2264
    type Item = A::Item;
2265
2266
    #[inline]
2267
0
    fn next(&mut self) -> Option<A::Item> {
2268
0
        if self.current == self.end {
2269
0
            None
2270
        } else {
2271
            unsafe {
2272
0
                let current = self.current;
2273
0
                self.current += 1;
2274
0
                Some(ptr::read(self.data.as_ptr().add(current)))
2275
            }
2276
        }
2277
0
    }
2278
2279
    #[inline]
2280
0
    fn size_hint(&self) -> (usize, Option<usize>) {
2281
0
        let size = self.end - self.current;
2282
0
        (size, Some(size))
2283
0
    }
2284
}
2285
2286
impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2287
    #[inline]
2288
0
    fn next_back(&mut self) -> Option<A::Item> {
2289
0
        if self.current == self.end {
2290
0
            None
2291
        } else {
2292
            unsafe {
2293
0
                self.end -= 1;
2294
0
                Some(ptr::read(self.data.as_ptr().add(self.end)))
2295
            }
2296
        }
2297
0
    }
2298
}
2299
2300
impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2301
impl<A: Array> FusedIterator for IntoIter<A> {}
2302
2303
impl<A: Array> IntoIter<A> {
2304
    /// Returns the remaining items of this iterator as a slice.
2305
0
    pub fn as_slice(&self) -> &[A::Item] {
2306
0
        let len = self.end - self.current;
2307
0
        unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2308
0
    }
2309
2310
    /// Returns the remaining items of this iterator as a mutable slice.
2311
0
    pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2312
0
        let len = self.end - self.current;
2313
0
        unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2314
0
    }
2315
}
2316
2317
impl<A: Array> IntoIterator for SmallVec<A> {
2318
    type IntoIter = IntoIter<A>;
2319
    type Item = A::Item;
2320
0
    fn into_iter(mut self) -> Self::IntoIter {
2321
        unsafe {
2322
            // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements
2323
0
            let len = self.len();
2324
0
            self.set_len(0);
2325
0
            IntoIter {
2326
0
                data: self,
2327
0
                current: 0,
2328
0
                end: len,
2329
0
            }
2330
        }
2331
0
    }
2332
}
2333
2334
impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2335
    type IntoIter = slice::Iter<'a, A::Item>;
2336
    type Item = &'a A::Item;
2337
0
    fn into_iter(self) -> Self::IntoIter {
2338
0
        self.iter()
2339
0
    }
2340
}
2341
2342
impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2343
    type IntoIter = slice::IterMut<'a, A::Item>;
2344
    type Item = &'a mut A::Item;
2345
62.9M
    fn into_iter(self) -> Self::IntoIter {
2346
62.9M
        self.iter_mut()
2347
62.9M
    }
<&mut smallvec::SmallVec<[(usize, char); 59]> as core::iter::traits::collect::IntoIterator>::into_iter
Line
Count
Source
2345
62.9M
    fn into_iter(self) -> Self::IntoIter {
2346
62.9M
        self.iter_mut()
2347
62.9M
    }
Unexecuted instantiation: <&mut smallvec::SmallVec<_> as core::iter::traits::collect::IntoIterator>::into_iter
2348
}
2349
2350
/// Types that can be used as the backing store for a [`SmallVec`].
2351
pub unsafe trait Array {
2352
    /// The type of the array's elements.
2353
    type Item;
2354
    /// Returns the number of items the array can hold.
2355
    fn size() -> usize;
2356
}
2357
2358
/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
2359
///
2360
/// Copied from <https://github.com/rust-lang/rust/pull/36355>
2361
struct SetLenOnDrop<'a> {
2362
    len: &'a mut usize,
2363
    local_len: usize,
2364
}
2365
2366
impl<'a> SetLenOnDrop<'a> {
2367
    #[inline]
2368
793k
    fn new(len: &'a mut usize) -> Self {
2369
793k
        SetLenOnDrop {
2370
793k
            local_len: *len,
2371
793k
            len,
2372
793k
        }
2373
793k
    }
Unexecuted instantiation: <smallvec::SetLenOnDrop>::new
<smallvec::SetLenOnDrop>::new
Line
Count
Source
2368
788k
    fn new(len: &'a mut usize) -> Self {
2369
788k
        SetLenOnDrop {
2370
788k
            local_len: *len,
2371
788k
            len,
2372
788k
        }
2373
788k
    }
<smallvec::SetLenOnDrop>::new
Line
Count
Source
2368
4.41k
    fn new(len: &'a mut usize) -> Self {
2369
4.41k
        SetLenOnDrop {
2370
4.41k
            local_len: *len,
2371
4.41k
            len,
2372
4.41k
        }
2373
4.41k
    }
Unexecuted instantiation: <smallvec::SetLenOnDrop>::new
2374
2375
    #[inline]
2376
127M
    fn get(&self) -> usize {
2377
127M
        self.local_len
2378
127M
    }
<smallvec::SetLenOnDrop>::get
Line
Count
Source
2376
127M
    fn get(&self) -> usize {
2377
127M
        self.local_len
2378
127M
    }
<smallvec::SetLenOnDrop>::get
Line
Count
Source
2376
14.8k
    fn get(&self) -> usize {
2377
14.8k
        self.local_len
2378
14.8k
    }
Unexecuted instantiation: <smallvec::SetLenOnDrop>::get
2379
2380
    #[inline]
2381
63.2M
    fn increment_len(&mut self, increment: usize) {
2382
63.2M
        self.local_len += increment;
2383
63.2M
    }
Unexecuted instantiation: <smallvec::SetLenOnDrop>::increment_len
<smallvec::SetLenOnDrop>::increment_len
Line
Count
Source
2381
63.2M
    fn increment_len(&mut self, increment: usize) {
2382
63.2M
        self.local_len += increment;
2383
63.2M
    }
<smallvec::SetLenOnDrop>::increment_len
Line
Count
Source
2381
5.22k
    fn increment_len(&mut self, increment: usize) {
2382
5.22k
        self.local_len += increment;
2383
5.22k
    }
Unexecuted instantiation: <smallvec::SetLenOnDrop>::increment_len
2384
}
2385
2386
impl<'a> Drop for SetLenOnDrop<'a> {
2387
    #[inline]
2388
793k
    fn drop(&mut self) {
2389
793k
        *self.len = self.local_len;
2390
793k
    }
Unexecuted instantiation: <smallvec::SetLenOnDrop as core::ops::drop::Drop>::drop
<smallvec::SetLenOnDrop as core::ops::drop::Drop>::drop
Line
Count
Source
2388
793k
    fn drop(&mut self) {
2389
793k
        *self.len = self.local_len;
2390
793k
    }
Unexecuted instantiation: <smallvec::SetLenOnDrop as core::ops::drop::Drop>::drop
2391
}
2392
2393
#[cfg(feature = "const_new")]
2394
impl<T, const N: usize> SmallVec<[T; N]> {
2395
    /// Construct an empty vector.
2396
    ///
2397
    /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays.
2398
    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2399
    #[inline]
2400
0
    pub const fn new_const() -> Self {
2401
0
        SmallVec {
2402
0
            capacity: 0,
2403
0
            data: SmallVecData::from_const(MaybeUninit::uninit()),
2404
0
        }
2405
0
    }
2406
2407
    /// The array passed as an argument is moved to be an inline version of `SmallVec`.
2408
    ///
2409
    /// This is a `const` version of [`SmallVec::from_buf`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays.
2410
    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2411
    #[inline]
2412
0
    pub const fn from_const(items: [T; N]) -> Self {
2413
0
        SmallVec {
2414
0
            capacity: N,
2415
0
            data: SmallVecData::from_const(MaybeUninit::new(items)),
2416
0
        }
2417
0
    }
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100]>>::from_const
Unexecuted instantiation: <smallvec::SmallVec<[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100]>>::from_const
Unexecuted instantiation: <smallvec::SmallVec<[_; _]>>::from_const
2418
2419
    /// Constructs a new `SmallVec` on the stack from an array without
2420
    /// copying elements. Also sets the length. The user is responsible
2421
    /// for ensuring that `len <= N`.
2422
    /// 
2423
    /// This is a `const` version of [`SmallVec::from_buf_and_len_unchecked`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays.
2424
    #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2425
    #[inline]
2426
0
    pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2427
0
        SmallVec {
2428
0
            capacity: len,
2429
0
            data: SmallVecData::from_const(MaybeUninit::new(items)),
2430
0
        }
2431
0
    }
2432
}
2433
2434
#[cfg(feature = "const_generics")]
2435
#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2436
unsafe impl<T, const N: usize> Array for [T; N] {
2437
    type Item = T;
2438
    #[inline]
2439
663M
    fn size() -> usize {
2440
663M
        N
2441
663M
    }
Unexecuted instantiation: <[core::mem::maybe_uninit::MaybeUninit<httparse::Header>; 100] as smallvec::Array>::size
Unexecuted instantiation: <[core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>; 100] as smallvec::Array>::size
<[idna::uts46::AlreadyAsciiLabel; 8] as smallvec::Array>::size
Line
Count
Source
2439
24.8M
    fn size() -> usize {
2440
24.8M
        N
2441
24.8M
    }
<[(usize, char); 59] as smallvec::Array>::size
Line
Count
Source
2439
185M
    fn size() -> usize {
2440
185M
        N
2441
185M
    }
<[char; 59] as smallvec::Array>::size
Line
Count
Source
2439
7.66M
    fn size() -> usize {
2440
7.66M
        N
2441
7.66M
    }
<[char; 253] as smallvec::Array>::size
Line
Count
Source
2439
200M
    fn size() -> usize {
2440
200M
        N
2441
200M
    }
<[icu_normalizer::CharacterAndClass; 17] as smallvec::Array>::size
Line
Count
Source
2439
244M
    fn size() -> usize {
2440
244M
        N
2441
244M
    }
Unexecuted instantiation: <[_; _] as smallvec::Array>::size
2442
}
2443
2444
#[cfg(not(feature = "const_generics"))]
2445
macro_rules! impl_array(
2446
    ($($size:expr),+) => {
2447
        $(
2448
            unsafe impl<T> Array for [T; $size] {
2449
                type Item = T;
2450
                #[inline]
2451
                fn size() -> usize { $size }
2452
            }
2453
        )+
2454
    }
2455
);
2456
2457
#[cfg(not(feature = "const_generics"))]
2458
impl_array!(
2459
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
2460
    26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2461
    0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2462
);
2463
2464
/// Convenience trait for constructing a `SmallVec`
2465
pub trait ToSmallVec<A: Array> {
2466
    /// Construct a new `SmallVec` from a slice.
2467
    fn to_smallvec(&self) -> SmallVec<A>;
2468
}
2469
2470
impl<A: Array> ToSmallVec<A> for [A::Item]
2471
where
2472
    A::Item: Copy,
2473
{
2474
    #[inline]
2475
0
    fn to_smallvec(&self) -> SmallVec<A> {
2476
0
        SmallVec::from_slice(self)
2477
0
    }
2478
}
2479
2480
// Immutable counterpart for `NonNull<T>`.
2481
#[repr(transparent)]
2482
struct ConstNonNull<T>(NonNull<T>);
2483
2484
impl<T> ConstNonNull<T> {
2485
    #[inline]
2486
103M
    fn new(ptr: *const T) -> Option<Self> {
2487
103M
        NonNull::new(ptr as *mut T).map(Self)
2488
103M
    }
Unexecuted instantiation: <smallvec::ConstNonNull<core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>>>::new
<smallvec::ConstNonNull<idna::uts46::AlreadyAsciiLabel>>::new
Line
Count
Source
2486
8.66k
    fn new(ptr: *const T) -> Option<Self> {
2487
8.66k
        NonNull::new(ptr as *mut T).map(Self)
2488
8.66k
    }
<smallvec::ConstNonNull<(usize, char)>>::new
Line
Count
Source
2486
1.25M
    fn new(ptr: *const T) -> Option<Self> {
2487
1.25M
        NonNull::new(ptr as *mut T).map(Self)
2488
1.25M
    }
<smallvec::ConstNonNull<char>>::new
Line
Count
Source
2486
757k
    fn new(ptr: *const T) -> Option<Self> {
2487
757k
        NonNull::new(ptr as *mut T).map(Self)
2488
757k
    }
<smallvec::ConstNonNull<icu_normalizer::CharacterAndClass>>::new
Line
Count
Source
2486
101M
    fn new(ptr: *const T) -> Option<Self> {
2487
101M
        NonNull::new(ptr as *mut T).map(Self)
2488
101M
    }
Unexecuted instantiation: <smallvec::ConstNonNull<_>>::new
2489
    #[inline]
2490
100M
    fn as_ptr(self) -> *const T {
2491
100M
        self.0.as_ptr()
2492
100M
    }
Unexecuted instantiation: <smallvec::ConstNonNull<core::mem::maybe_uninit::MaybeUninit<hyper::proto::h1::role::HeaderIndices>>>::as_ptr
<smallvec::ConstNonNull<idna::uts46::AlreadyAsciiLabel>>::as_ptr
Line
Count
Source
2490
7.80k
    fn as_ptr(self) -> *const T {
2491
7.80k
        self.0.as_ptr()
2492
7.80k
    }
<smallvec::ConstNonNull<(usize, char)>>::as_ptr
Line
Count
Source
2490
766k
    fn as_ptr(self) -> *const T {
2491
766k
        self.0.as_ptr()
2492
766k
    }
<smallvec::ConstNonNull<char>>::as_ptr
Line
Count
Source
2490
1.48M
    fn as_ptr(self) -> *const T {
2491
1.48M
        self.0.as_ptr()
2492
1.48M
    }
<smallvec::ConstNonNull<icu_normalizer::CharacterAndClass>>::as_ptr
Line
Count
Source
2490
98.2M
    fn as_ptr(self) -> *const T {
2491
98.2M
        self.0.as_ptr()
2492
98.2M
    }
Unexecuted instantiation: <smallvec::ConstNonNull<_>>::as_ptr
2493
}
2494
2495
impl<T> Clone for ConstNonNull<T> {
2496
    #[inline]
2497
0
    fn clone(&self) -> Self {
2498
0
        *self
2499
0
    }
2500
}
2501
2502
impl<T> Copy for ConstNonNull<T> {}
2503
2504
#[cfg(feature = "impl_bincode")]
2505
use bincode::{
2506
    de::{BorrowDecoder, Decode, Decoder, read::Reader},
2507
    enc::{Encode, Encoder, write::Writer},
2508
    error::{DecodeError, EncodeError},
2509
    BorrowDecode,
2510
};
2511
2512
#[cfg(feature = "impl_bincode")]
2513
impl<A, Context> Decode<Context> for SmallVec<A>
2514
where
2515
    A: Array,
2516
    A::Item: Decode<Context>,
2517
{
2518
    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2519
        use core::convert::TryInto;
2520
        let len = u64::decode(decoder)?;
2521
        let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2522
        decoder.claim_container_read::<A::Item>(len)?;
2523
2524
        let mut vec = SmallVec::with_capacity(len);
2525
        if unty::type_equal::<A::Item, u8>() {
2526
            // Initialize the smallvec's buffer.  Note that we need to do this through
2527
            // the raw pointer as we cannot name the type [u8; N] even though A::Item is u8.
2528
            let ptr = vec.as_mut_ptr();
2529
            // SAFETY: A::Item is u8 and the smallvec has been allocated with enough capacity
2530
            unsafe {
2531
                core::ptr::write_bytes(ptr, 0, len);
2532
                vec.set_len(len);
2533
            }
2534
            // Read the data into the smallvec's buffer.
2535
            let slice = vec.as_mut_slice();
2536
            // SAFETY: A::Item is u8
2537
            let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2538
            decoder.reader().read(slice)?;
2539
        } else {
2540
            for _ in 0..len {
2541
                decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2542
                vec.push(A::Item::decode(decoder)?);
2543
            }
2544
        }
2545
        Ok(vec)
2546
    }
2547
}
2548
2549
#[cfg(feature = "impl_bincode")]
2550
impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2551
where
2552
    A: Array,
2553
    A::Item: BorrowDecode<'de, Context>,
2554
{
2555
    fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2556
        use core::convert::TryInto;
2557
        let len = u64::decode(decoder)?;
2558
        let len = len.try_into().map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2559
        decoder.claim_container_read::<A::Item>(len)?;
2560
2561
        let mut vec = SmallVec::with_capacity(len);
2562
        if unty::type_equal::<A::Item, u8>() {
2563
            // Initialize the smallvec's buffer.  Note that we need to do this through
2564
            // the raw pointer as we cannot name the type [u8; N] even though A::Item is u8.
2565
            let ptr = vec.as_mut_ptr();
2566
            // SAFETY: A::Item is u8 and the smallvec has been allocated with enough capacity
2567
            unsafe {
2568
                core::ptr::write_bytes(ptr, 0, len);
2569
                vec.set_len(len);
2570
            }
2571
            // Read the data into the smallvec's buffer.
2572
            let slice = vec.as_mut_slice();
2573
            // SAFETY: A::Item is u8
2574
            let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2575
            decoder.reader().read(slice)?;
2576
        } else {
2577
            for _ in 0..len {
2578
                decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2579
                vec.push(A::Item::borrow_decode(decoder)?);
2580
            }
2581
        }
2582
        Ok(vec)
2583
    }
2584
}
2585
2586
#[cfg(feature = "impl_bincode")]
2587
impl<A> Encode for SmallVec<A>
2588
where
2589
    A: Array,
2590
    A::Item: Encode,
2591
{
2592
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2593
        (self.len() as u64).encode(encoder)?;
2594
        if unty::type_equal::<A::Item, u8>() {
2595
            // Safety: A::Item is u8
2596
            let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2597
            encoder.writer().write(slice)?;
2598
        } else {
2599
            for item in self.iter() {
2600
                item.encode(encoder)?;
2601
            }
2602
        }
2603
        Ok(())
2604
    }
2605
}