Coverage Report

Created: 2026-09-02 07:14

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