/rust/registry/src/index.crates.io-1949cf8c6b5b557f/smallvec-1.6.1/src/lib.rs
Line | Count | Source |
1 | | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
2 | | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
3 | | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
4 | | // option. This file may not be copied, modified, or distributed |
5 | | // except according to those terms. |
6 | | |
7 | | //! Small vectors in various sizes. These store a certain number of elements inline, and fall back |
8 | | //! to the heap for larger allocations. This can be a useful optimization for improving cache |
9 | | //! locality and reducing allocator traffic for workloads that fit within the inline buffer. |
10 | | //! |
11 | | //! ## `no_std` support |
12 | | //! |
13 | | //! By default, `smallvec` does not depend on `std`. However, the optional |
14 | | //! `write` feature implements the `std::io::Write` trait for vectors of `u8`. |
15 | | //! When this feature is enabled, `smallvec` depends on `std`. |
16 | | //! |
17 | | //! ## Optional features |
18 | | //! |
19 | | //! ### `serde` |
20 | | //! |
21 | | //! When this optional dependency is enabled, `SmallVec` implements the `serde::Serialize` and |
22 | | //! `serde::Deserialize` traits. |
23 | | //! |
24 | | //! ### `write` |
25 | | //! |
26 | | //! When this feature is enabled, `SmallVec<[u8; _]>` implements the `std::io::Write` trait. |
27 | | //! This feature is not compatible with `#![no_std]` programs. |
28 | | //! |
29 | | //! ### `union` |
30 | | //! |
31 | | //! **This feature requires Rust 1.49.** |
32 | | //! |
33 | | //! When the `union` feature is enabled `smallvec` will track its state (inline or spilled) |
34 | | //! without the use of an enum tag, reducing the size of the `smallvec` by one machine word. |
35 | | //! This means that there is potentially no space overhead compared to `Vec`. |
36 | | //! Note that `smallvec` can still be larger than `Vec` if the inline buffer is larger than two |
37 | | //! machine words. |
38 | | //! |
39 | | //! To use this feature add `features = ["union"]` in the `smallvec` section of Cargo.toml. |
40 | | //! Note that this feature requires Rust 1.49. |
41 | | //! |
42 | | //! Tracking issue: [rust-lang/rust#55149](https://github.com/rust-lang/rust/issues/55149) |
43 | | //! |
44 | | //! ### `const_generics` |
45 | | //! |
46 | | //! **This feature is unstable and requires a nightly build of the Rust toolchain.** |
47 | | //! |
48 | | //! When this feature is enabled, `SmallVec` works with any arrays of any size, not just a fixed |
49 | | //! list of sizes. |
50 | | //! |
51 | | //! Tracking issue: [rust-lang/rust#44580](https://github.com/rust-lang/rust/issues/44580) |
52 | | //! |
53 | | //! ### `specialization` |
54 | | //! |
55 | | //! **This feature is unstable and requires a nightly build of the Rust toolchain.** |
56 | | //! |
57 | | //! When this feature is enabled, `SmallVec::from(slice)` has improved performance for slices |
58 | | //! of `Copy` types. (Without this feature, you can use `SmallVec::from_slice` to get optimal |
59 | | //! performance for `Copy` types.) |
60 | | //! |
61 | | //! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844) |
62 | | //! |
63 | | //! ### `may_dangle` |
64 | | //! |
65 | | //! **This feature is unstable and requires a nightly build of the Rust toolchain.** |
66 | | //! |
67 | | //! This feature makes the Rust compiler less strict about use of vectors that contain borrowed |
68 | | //! references. For details, see the |
69 | | //! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch). |
70 | | //! |
71 | | //! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761) |
72 | | |
73 | | #![no_std] |
74 | | #![cfg_attr(feature = "specialization", allow(incomplete_features))] |
75 | | #![cfg_attr(feature = "specialization", feature(specialization))] |
76 | | #![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))] |
77 | | #![deny(missing_docs)] |
78 | | |
79 | | #[doc(hidden)] |
80 | | pub extern crate alloc; |
81 | | |
82 | | #[cfg(any(test, feature = "write"))] |
83 | | extern crate std; |
84 | | |
85 | | #[cfg(test)] |
86 | | mod tests; |
87 | | |
88 | | #[allow(deprecated)] |
89 | | use alloc::alloc::{Layout, LayoutErr}; |
90 | | use alloc::boxed::Box; |
91 | | use alloc::{vec, vec::Vec}; |
92 | | use core::borrow::{Borrow, BorrowMut}; |
93 | | use core::cmp; |
94 | | use core::fmt; |
95 | | use core::hash::{Hash, Hasher}; |
96 | | use core::hint::unreachable_unchecked; |
97 | | use core::iter::{repeat, FromIterator, FusedIterator, IntoIterator}; |
98 | | use core::mem; |
99 | | use core::mem::MaybeUninit; |
100 | | use core::ops::{self, Range, RangeBounds}; |
101 | | use core::ptr::{self, NonNull}; |
102 | | use core::slice::{self, SliceIndex}; |
103 | | |
104 | | #[cfg(feature = "serde")] |
105 | | use serde::{ |
106 | | de::{Deserialize, Deserializer, SeqAccess, Visitor}, |
107 | | ser::{Serialize, SerializeSeq, Serializer}, |
108 | | }; |
109 | | |
110 | | #[cfg(feature = "serde")] |
111 | | use core::marker::PhantomData; |
112 | | |
113 | | #[cfg(feature = "write")] |
114 | | use std::io; |
115 | | |
116 | | /// Creates a [`SmallVec`] containing the arguments. |
117 | | /// |
118 | | /// `smallvec!` allows `SmallVec`s to be defined with the same syntax as array expressions. |
119 | | /// There are two forms of this macro: |
120 | | /// |
121 | | /// - Create a [`SmallVec`] containing a given list of elements: |
122 | | /// |
123 | | /// ``` |
124 | | /// # #[macro_use] extern crate smallvec; |
125 | | /// # use smallvec::SmallVec; |
126 | | /// # fn main() { |
127 | | /// let v: SmallVec<[_; 128]> = smallvec![1, 2, 3]; |
128 | | /// assert_eq!(v[0], 1); |
129 | | /// assert_eq!(v[1], 2); |
130 | | /// assert_eq!(v[2], 3); |
131 | | /// # } |
132 | | /// ``` |
133 | | /// |
134 | | /// - Create a [`SmallVec`] from a given element and size: |
135 | | /// |
136 | | /// ``` |
137 | | /// # #[macro_use] extern crate smallvec; |
138 | | /// # use smallvec::SmallVec; |
139 | | /// # fn main() { |
140 | | /// let v: SmallVec<[_; 0x8000]> = smallvec![1; 3]; |
141 | | /// assert_eq!(v, SmallVec::from_buf([1, 1, 1])); |
142 | | /// # } |
143 | | /// ``` |
144 | | /// |
145 | | /// Note that unlike array expressions this syntax supports all elements |
146 | | /// which implement [`Clone`] and the number of elements doesn't have to be |
147 | | /// a constant. |
148 | | /// |
149 | | /// This will use `clone` to duplicate an expression, so one should be careful |
150 | | /// using this with types having a nonstandard `Clone` implementation. For |
151 | | /// example, `smallvec![Rc::new(1); 5]` will create a vector of five references |
152 | | /// to the same boxed integer value, not five references pointing to independently |
153 | | /// boxed integers. |
154 | | |
155 | | #[macro_export] |
156 | | macro_rules! smallvec { |
157 | | // count helper: transform any expression into 1 |
158 | | (@one $x:expr) => (1usize); |
159 | | ($elem:expr; $n:expr) => ({ |
160 | | $crate::SmallVec::from_elem($elem, $n) |
161 | | }); |
162 | | ($($x:expr),*$(,)*) => ({ |
163 | | let count = 0usize $(+ $crate::smallvec!(@one $x))*; |
164 | | #[allow(unused_mut)] |
165 | | let mut vec = $crate::SmallVec::new(); |
166 | | if count <= vec.inline_size() { |
167 | | $(vec.push($x);)* |
168 | | vec |
169 | | } else { |
170 | | $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)*]) |
171 | | } |
172 | | }); |
173 | | } |
174 | | |
175 | | /// `panic!()` in debug builds, optimization hint in release. |
176 | | #[cfg(not(feature = "union"))] |
177 | | macro_rules! debug_unreachable { |
178 | | () => { |
179 | | debug_unreachable!("entered unreachable code") |
180 | | }; |
181 | | ($e:expr) => { |
182 | | if cfg!(not(debug_assertions)) { |
183 | | unreachable_unchecked(); |
184 | | } else { |
185 | | panic!($e); |
186 | | } |
187 | | }; |
188 | | } |
189 | | |
190 | | /// Trait to be implemented by a collection that can be extended from a slice |
191 | | /// |
192 | | /// ## Example |
193 | | /// |
194 | | /// ```rust |
195 | | /// use smallvec::{ExtendFromSlice, SmallVec}; |
196 | | /// |
197 | | /// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) { |
198 | | /// v.extend_from_slice(b"Test!"); |
199 | | /// } |
200 | | /// |
201 | | /// let mut vec = Vec::new(); |
202 | | /// initialize(&mut vec); |
203 | | /// assert_eq!(&vec, b"Test!"); |
204 | | /// |
205 | | /// let mut small_vec = SmallVec::<[u8; 8]>::new(); |
206 | | /// initialize(&mut small_vec); |
207 | | /// assert_eq!(&small_vec as &[_], b"Test!"); |
208 | | /// ``` |
209 | | #[doc(hidden)] |
210 | | #[deprecated] |
211 | | pub trait ExtendFromSlice<T> { |
212 | | /// Extends a collection from a slice of its element type |
213 | | fn extend_from_slice(&mut self, other: &[T]); |
214 | | } |
215 | | |
216 | | #[allow(deprecated)] |
217 | | impl<T: Clone> ExtendFromSlice<T> for Vec<T> { |
218 | 0 | fn extend_from_slice(&mut self, other: &[T]) { |
219 | 0 | Vec::extend_from_slice(self, other) |
220 | 0 | } |
221 | | } |
222 | | |
223 | | /// Error type for APIs with fallible heap allocation |
224 | | #[derive(Debug)] |
225 | | pub enum CollectionAllocErr { |
226 | | /// Overflow `usize::MAX` or other error during size computation |
227 | | CapacityOverflow, |
228 | | /// The allocator return an error |
229 | | AllocErr { |
230 | | /// The layout that was passed to the allocator |
231 | | layout: Layout, |
232 | | }, |
233 | | } |
234 | | |
235 | | impl fmt::Display for CollectionAllocErr { |
236 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
237 | 0 | write!(f, "Allocation error: {:?}", self) |
238 | 0 | } |
239 | | } |
240 | | |
241 | | #[allow(deprecated)] |
242 | | impl From<LayoutErr> for CollectionAllocErr { |
243 | 0 | fn from(_: LayoutErr) -> Self { |
244 | 0 | CollectionAllocErr::CapacityOverflow |
245 | 0 | } |
246 | | } |
247 | | |
248 | 615 | fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T { |
249 | 0 | match result { |
250 | 615 | Ok(x) => x, |
251 | 0 | Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), |
252 | 0 | Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), |
253 | | } |
254 | 615 | } smallvec::infallible::<()> Line | Count | Source | 248 | 615 | fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T { | 249 | 0 | match result { | 250 | 615 | Ok(x) => x, | 251 | 0 | Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), | 252 | 0 | Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), | 253 | | } | 254 | 615 | } |
Unexecuted instantiation: smallvec::infallible::<_> |
255 | | |
256 | | /// FIXME: use `Layout::array` when we require a Rust version where it’s stable |
257 | | /// https://github.com/rust-lang/rust/issues/55724 |
258 | 940 | fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> { |
259 | 940 | let size = mem::size_of::<T>() |
260 | 940 | .checked_mul(n) |
261 | 940 | .ok_or(CollectionAllocErr::CapacityOverflow)?; |
262 | 940 | let align = mem::align_of::<T>(); |
263 | 940 | Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow) |
264 | 940 | } smallvec::layout_array::<cssparser::parser::BlockType> Line | Count | Source | 258 | 940 | fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> { | 259 | 940 | let size = mem::size_of::<T>() | 260 | 940 | .checked_mul(n) | 261 | 940 | .ok_or(CollectionAllocErr::CapacityOverflow)?; | 262 | 940 | let align = mem::align_of::<T>(); | 263 | 940 | Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow) | 264 | 940 | } |
Unexecuted instantiation: smallvec::layout_array::<_> |
265 | | |
266 | 0 | unsafe fn deallocate<T>(ptr: *mut T, capacity: usize) { |
267 | | // This unwrap should succeed since the same did when allocating. |
268 | 0 | let layout = layout_array::<T>(capacity).unwrap(); |
269 | 0 | alloc::alloc::dealloc(ptr as *mut u8, layout) |
270 | 0 | } Unexecuted instantiation: smallvec::deallocate::<cssparser::parser::BlockType> Unexecuted instantiation: smallvec::deallocate::<_> |
271 | | |
272 | | /// An iterator that removes the items from a `SmallVec` and yields them by value. |
273 | | /// |
274 | | /// Returned from [`SmallVec::drain`][1]. |
275 | | /// |
276 | | /// [1]: struct.SmallVec.html#method.drain |
277 | | pub struct Drain<'a, T: 'a + Array> { |
278 | | tail_start: usize, |
279 | | tail_len: usize, |
280 | | iter: slice::Iter<'a, T::Item>, |
281 | | vec: NonNull<SmallVec<T>>, |
282 | | } |
283 | | |
284 | | impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T> |
285 | | where |
286 | | T::Item: fmt::Debug, |
287 | | { |
288 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
289 | 0 | f.debug_tuple("Drain").field(&self.iter.as_slice()).finish() |
290 | 0 | } |
291 | | } |
292 | | |
293 | | unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {} |
294 | | unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {} |
295 | | |
296 | | impl<'a, T: 'a + Array> Iterator for Drain<'a, T> { |
297 | | type Item = T::Item; |
298 | | |
299 | | #[inline] |
300 | 0 | fn next(&mut self) -> Option<T::Item> { |
301 | 0 | self.iter |
302 | 0 | .next() |
303 | 0 | .map(|reference| unsafe { ptr::read(reference) }) |
304 | 0 | } |
305 | | |
306 | | #[inline] |
307 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
308 | 0 | self.iter.size_hint() |
309 | 0 | } |
310 | | } |
311 | | |
312 | | impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> { |
313 | | #[inline] |
314 | 0 | fn next_back(&mut self) -> Option<T::Item> { |
315 | 0 | self.iter |
316 | 0 | .next_back() |
317 | 0 | .map(|reference| unsafe { ptr::read(reference) }) |
318 | 0 | } |
319 | | } |
320 | | |
321 | | impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> { |
322 | | #[inline] |
323 | 0 | fn len(&self) -> usize { |
324 | 0 | self.iter.len() |
325 | 0 | } |
326 | | } |
327 | | |
328 | | impl<'a, T: Array> FusedIterator for Drain<'a, T> {} |
329 | | |
330 | | impl<'a, T: 'a + Array> Drop for Drain<'a, T> { |
331 | 0 | fn drop(&mut self) { |
332 | 0 | self.for_each(drop); |
333 | | |
334 | 0 | if self.tail_len > 0 { |
335 | | unsafe { |
336 | 0 | let source_vec = self.vec.as_mut(); |
337 | | |
338 | | // memmove back untouched tail, update to new length |
339 | 0 | let start = source_vec.len(); |
340 | 0 | let tail = self.tail_start; |
341 | 0 | if tail != start { |
342 | 0 | let src = source_vec.as_ptr().add(tail); |
343 | 0 | let dst = source_vec.as_mut_ptr().add(start); |
344 | 0 | ptr::copy(src, dst, self.tail_len); |
345 | 0 | } |
346 | 0 | source_vec.set_len(start + self.tail_len); |
347 | | } |
348 | 0 | } |
349 | 0 | } |
350 | | } |
351 | | |
352 | | #[cfg(feature = "union")] |
353 | | union SmallVecData<A: Array> { |
354 | | inline: core::mem::ManuallyDrop<MaybeUninit<A>>, |
355 | | heap: (*mut A::Item, usize), |
356 | | } |
357 | | |
358 | | #[cfg(feature = "union")] |
359 | | impl<A: Array> SmallVecData<A> { |
360 | | #[inline] |
361 | | unsafe fn inline(&self) -> *const A::Item { |
362 | | self.inline.as_ptr() as *const A::Item |
363 | | } |
364 | | #[inline] |
365 | | unsafe fn inline_mut(&mut self) -> *mut A::Item { |
366 | | self.inline.as_mut_ptr() as *mut A::Item |
367 | | } |
368 | | #[inline] |
369 | | fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> { |
370 | | SmallVecData { |
371 | | inline: core::mem::ManuallyDrop::new(inline), |
372 | | } |
373 | | } |
374 | | #[inline] |
375 | | unsafe fn into_inline(self) -> MaybeUninit<A> { |
376 | | core::mem::ManuallyDrop::into_inner(self.inline) |
377 | | } |
378 | | #[inline] |
379 | | unsafe fn heap(&self) -> (*mut A::Item, usize) { |
380 | | self.heap |
381 | | } |
382 | | #[inline] |
383 | | unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { |
384 | | &mut self.heap |
385 | | } |
386 | | #[inline] |
387 | | fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData<A> { |
388 | | SmallVecData { heap: (ptr, len) } |
389 | | } |
390 | | } |
391 | | |
392 | | #[cfg(not(feature = "union"))] |
393 | | enum SmallVecData<A: Array> { |
394 | | Inline(MaybeUninit<A>), |
395 | | Heap((*mut A::Item, usize)), |
396 | | } |
397 | | |
398 | | #[cfg(not(feature = "union"))] |
399 | | impl<A: Array> SmallVecData<A> { |
400 | | #[inline] |
401 | 701k | unsafe fn inline(&self) -> *const A::Item { |
402 | 701k | match self { |
403 | 701k | SmallVecData::Inline(a) => a.as_ptr() as *const A::Item, |
404 | 0 | _ => debug_unreachable!(), |
405 | | } |
406 | 701k | } <smallvec::SmallVecData<[cssparser::parser::BlockType; 16]>>::inline Line | Count | Source | 401 | 701k | unsafe fn inline(&self) -> *const A::Item { | 402 | 701k | match self { | 403 | 701k | SmallVecData::Inline(a) => a.as_ptr() as *const A::Item, | 404 | 0 | _ => debug_unreachable!(), | 405 | | } | 406 | 701k | } |
Unexecuted instantiation: <smallvec::SmallVecData<_>>::inline |
407 | | #[inline] |
408 | 1.08M | unsafe fn inline_mut(&mut self) -> *mut A::Item { |
409 | 1.08M | match self { |
410 | 1.08M | SmallVecData::Inline(a) => a.as_mut_ptr() as *mut A::Item, |
411 | 0 | _ => debug_unreachable!(), |
412 | | } |
413 | 1.08M | } <smallvec::SmallVecData<[cssparser::parser::BlockType; 16]>>::inline_mut Line | Count | Source | 408 | 1.08M | unsafe fn inline_mut(&mut self) -> *mut A::Item { | 409 | 1.08M | match self { | 410 | 1.08M | SmallVecData::Inline(a) => a.as_mut_ptr() as *mut A::Item, | 411 | 0 | _ => debug_unreachable!(), | 412 | | } | 413 | 1.08M | } |
Unexecuted instantiation: <smallvec::SmallVecData<_>>::inline_mut |
414 | | #[inline] |
415 | 366k | fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> { |
416 | 366k | SmallVecData::Inline(inline) |
417 | 366k | } <smallvec::SmallVecData<[cssparser::parser::BlockType; 16]>>::from_inline Line | Count | Source | 415 | 366k | fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> { | 416 | 366k | SmallVecData::Inline(inline) | 417 | 366k | } |
Unexecuted instantiation: <smallvec::SmallVecData<_>>::from_inline |
418 | | #[inline] |
419 | 0 | unsafe fn into_inline(self) -> MaybeUninit<A> { |
420 | 0 | match self { |
421 | 0 | SmallVecData::Inline(a) => a, |
422 | 0 | _ => debug_unreachable!(), |
423 | | } |
424 | 0 | } |
425 | | #[inline] |
426 | 15.9k | unsafe fn heap(&self) -> (*mut A::Item, usize) { |
427 | 15.9k | match self { |
428 | 15.9k | SmallVecData::Heap(data) => *data, |
429 | 0 | _ => debug_unreachable!(), |
430 | | } |
431 | 15.9k | } <smallvec::SmallVecData<[cssparser::parser::BlockType; 16]>>::heap Line | Count | Source | 426 | 15.9k | unsafe fn heap(&self) -> (*mut A::Item, usize) { | 427 | 15.9k | match self { | 428 | 15.9k | SmallVecData::Heap(data) => *data, | 429 | 0 | _ => debug_unreachable!(), | 430 | | } | 431 | 15.9k | } |
Unexecuted instantiation: <smallvec::SmallVecData<_>>::heap |
432 | | #[inline] |
433 | 1.34M | unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { |
434 | 1.34M | match self { |
435 | 1.34M | SmallVecData::Heap(data) => data, |
436 | 0 | _ => debug_unreachable!(), |
437 | | } |
438 | 1.34M | } <smallvec::SmallVecData<[cssparser::parser::BlockType; 16]>>::heap_mut Line | Count | Source | 433 | 1.34M | unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { | 434 | 1.34M | match self { | 435 | 1.34M | SmallVecData::Heap(data) => data, | 436 | 0 | _ => debug_unreachable!(), | 437 | | } | 438 | 1.34M | } |
Unexecuted instantiation: <smallvec::SmallVecData<_>>::heap_mut |
439 | | #[inline] |
440 | 615 | fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData<A> { |
441 | 615 | SmallVecData::Heap((ptr, len)) |
442 | 615 | } <smallvec::SmallVecData<[cssparser::parser::BlockType; 16]>>::from_heap Line | Count | Source | 440 | 615 | fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData<A> { | 441 | 615 | SmallVecData::Heap((ptr, len)) | 442 | 615 | } |
Unexecuted instantiation: <smallvec::SmallVecData<_>>::from_heap |
443 | | } |
444 | | |
445 | | unsafe impl<A: Array + Send> Send for SmallVecData<A> {} |
446 | | unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {} |
447 | | |
448 | | /// A `Vec`-like container that can store a small number of elements inline. |
449 | | /// |
450 | | /// `SmallVec` acts like a vector, but can store a limited amount of data inline within the |
451 | | /// `SmallVec` struct rather than in a separate allocation. If the data exceeds this limit, the |
452 | | /// `SmallVec` will "spill" its data onto the heap, allocating a new buffer to hold it. |
453 | | /// |
454 | | /// The amount of data that a `SmallVec` can store inline depends on its backing store. The backing |
455 | | /// store can be any type that implements the `Array` trait; usually it is a small fixed-sized |
456 | | /// array. For example a `SmallVec<[u64; 8]>` can hold up to eight 64-bit integers inline. |
457 | | /// |
458 | | /// ## Example |
459 | | /// |
460 | | /// ```rust |
461 | | /// use smallvec::SmallVec; |
462 | | /// let mut v = SmallVec::<[u8; 4]>::new(); // initialize an empty vector |
463 | | /// |
464 | | /// // The vector can hold up to 4 items without spilling onto the heap. |
465 | | /// v.extend(0..4); |
466 | | /// assert_eq!(v.len(), 4); |
467 | | /// assert!(!v.spilled()); |
468 | | /// |
469 | | /// // Pushing another element will force the buffer to spill: |
470 | | /// v.push(4); |
471 | | /// assert_eq!(v.len(), 5); |
472 | | /// assert!(v.spilled()); |
473 | | /// ``` |
474 | | pub struct SmallVec<A: Array> { |
475 | | // The capacity field is used to determine which of the storage variants is active: |
476 | | // If capacity <= Self::inline_capacity() then the inline variant is used and capacity holds the current length of the vector (number of elements actually in use). |
477 | | // If capacity > Self::inline_capacity() then the heap variant is used and capacity holds the size of the memory allocation. |
478 | | capacity: usize, |
479 | | data: SmallVecData<A>, |
480 | | } |
481 | | |
482 | | impl<A: Array> SmallVec<A> { |
483 | | /// Construct an empty vector |
484 | | #[inline] |
485 | 366k | pub fn new() -> SmallVec<A> { |
486 | | // Try to detect invalid custom implementations of `Array`. Hopefuly, |
487 | | // this check should be optimized away entirely for valid ones. |
488 | 366k | assert!( |
489 | 366k | mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>() |
490 | 366k | && mem::align_of::<A>() >= mem::align_of::<A::Item>() |
491 | | ); |
492 | 366k | SmallVec { |
493 | 366k | capacity: 0, |
494 | 366k | data: SmallVecData::from_inline(MaybeUninit::uninit()), |
495 | 366k | } |
496 | 366k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::new Line | Count | Source | 485 | 366k | pub fn new() -> SmallVec<A> { | 486 | | // Try to detect invalid custom implementations of `Array`. Hopefuly, | 487 | | // this check should be optimized away entirely for valid ones. | 488 | 366k | assert!( | 489 | 366k | mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>() | 490 | 366k | && mem::align_of::<A>() >= mem::align_of::<A::Item>() | 491 | | ); | 492 | 366k | SmallVec { | 493 | 366k | capacity: 0, | 494 | 366k | data: SmallVecData::from_inline(MaybeUninit::uninit()), | 495 | 366k | } | 496 | 366k | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::new |
497 | | |
498 | | /// Construct an empty vector with enough capacity pre-allocated to store at least `n` |
499 | | /// elements. |
500 | | /// |
501 | | /// Will create a heap allocation only if `n` is larger than the inline capacity. |
502 | | /// |
503 | | /// ``` |
504 | | /// # use smallvec::SmallVec; |
505 | | /// |
506 | | /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100); |
507 | | /// |
508 | | /// assert!(v.is_empty()); |
509 | | /// assert!(v.capacity() >= 100); |
510 | | /// ``` |
511 | | #[inline] |
512 | 0 | pub fn with_capacity(n: usize) -> Self { |
513 | 0 | let mut v = SmallVec::new(); |
514 | 0 | v.reserve_exact(n); |
515 | 0 | v |
516 | 0 | } |
517 | | |
518 | | /// Construct a new `SmallVec` from a `Vec<A::Item>`. |
519 | | /// |
520 | | /// Elements will be copied to the inline buffer if vec.capacity() <= Self::inline_capacity(). |
521 | | /// |
522 | | /// ```rust |
523 | | /// use smallvec::SmallVec; |
524 | | /// |
525 | | /// let vec = vec![1, 2, 3, 4, 5]; |
526 | | /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec); |
527 | | /// |
528 | | /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); |
529 | | /// ``` |
530 | | #[inline] |
531 | 0 | pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> { |
532 | 0 | if vec.capacity() <= Self::inline_capacity() { |
533 | | unsafe { |
534 | 0 | let mut data = SmallVecData::<A>::from_inline(MaybeUninit::uninit()); |
535 | 0 | let len = vec.len(); |
536 | 0 | vec.set_len(0); |
537 | 0 | ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut(), len); |
538 | | |
539 | 0 | SmallVec { |
540 | 0 | capacity: len, |
541 | 0 | data, |
542 | 0 | } |
543 | | } |
544 | | } else { |
545 | 0 | let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len()); |
546 | 0 | mem::forget(vec); |
547 | | |
548 | 0 | SmallVec { |
549 | 0 | capacity: cap, |
550 | 0 | data: SmallVecData::from_heap(ptr, len), |
551 | 0 | } |
552 | | } |
553 | 0 | } |
554 | | |
555 | | /// Constructs a new `SmallVec` on the stack from an `A` without |
556 | | /// copying elements. |
557 | | /// |
558 | | /// ```rust |
559 | | /// use smallvec::SmallVec; |
560 | | /// |
561 | | /// let buf = [1, 2, 3, 4, 5]; |
562 | | /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf); |
563 | | /// |
564 | | /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); |
565 | | /// ``` |
566 | | #[inline] |
567 | 0 | pub fn from_buf(buf: A) -> SmallVec<A> { |
568 | 0 | SmallVec { |
569 | 0 | capacity: A::size(), |
570 | 0 | data: SmallVecData::from_inline(MaybeUninit::new(buf)), |
571 | 0 | } |
572 | 0 | } |
573 | | |
574 | | /// Constructs a new `SmallVec` on the stack from an `A` without |
575 | | /// copying elements. Also sets the length, which must be less or |
576 | | /// equal to the size of `buf`. |
577 | | /// |
578 | | /// ```rust |
579 | | /// use smallvec::SmallVec; |
580 | | /// |
581 | | /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; |
582 | | /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5); |
583 | | /// |
584 | | /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); |
585 | | /// ``` |
586 | | #[inline] |
587 | 0 | pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> { |
588 | 0 | assert!(len <= A::size()); |
589 | 0 | unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } |
590 | 0 | } |
591 | | |
592 | | /// Constructs a new `SmallVec` on the stack from an `A` without |
593 | | /// copying elements. Also sets the length. The user is responsible |
594 | | /// for ensuring that `len <= A::size()`. |
595 | | /// |
596 | | /// ```rust |
597 | | /// use smallvec::SmallVec; |
598 | | /// use std::mem::MaybeUninit; |
599 | | /// |
600 | | /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; |
601 | | /// let small_vec: SmallVec<_> = unsafe { |
602 | | /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) |
603 | | /// }; |
604 | | /// |
605 | | /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); |
606 | | /// ``` |
607 | | #[inline] |
608 | 0 | pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> { |
609 | 0 | SmallVec { |
610 | 0 | capacity: len, |
611 | 0 | data: SmallVecData::from_inline(buf), |
612 | 0 | } |
613 | 0 | } |
614 | | |
615 | | /// Sets the length of a vector. |
616 | | /// |
617 | | /// This will explicitly set the size of the vector, without actually |
618 | | /// modifying its buffers, so it is up to the caller to ensure that the |
619 | | /// vector is actually the specified size. |
620 | 0 | pub unsafe fn set_len(&mut self, new_len: usize) { |
621 | 0 | let (_, len_ptr, _) = self.triple_mut(); |
622 | 0 | *len_ptr = new_len; |
623 | 0 | } |
624 | | |
625 | | /// The maximum number of elements this vector can hold inline |
626 | | #[inline] |
627 | 5.31M | fn inline_capacity() -> usize { |
628 | 5.31M | if mem::size_of::<A::Item>() > 0 { |
629 | 5.31M | A::size() |
630 | | } else { |
631 | | // For zero-size items code like `ptr.add(offset)` always returns the same pointer. |
632 | | // Therefore all items are at the same address, |
633 | | // and any array size has capacity for infinitely many items. |
634 | | // The capacity is limited by the bit width of the length field. |
635 | | // |
636 | | // `Vec` also does this: |
637 | | // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186 |
638 | | // |
639 | | // In our case, this also ensures that a smallvec of zero-size items never spills, |
640 | | // and we never try to allocate zero bytes which `std::alloc::alloc` disallows. |
641 | 0 | core::usize::MAX |
642 | | } |
643 | 5.31M | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::inline_capacity Line | Count | Source | 627 | 5.31M | fn inline_capacity() -> usize { | 628 | 5.31M | if mem::size_of::<A::Item>() > 0 { | 629 | 5.31M | A::size() | 630 | | } else { | 631 | | // For zero-size items code like `ptr.add(offset)` always returns the same pointer. | 632 | | // Therefore all items are at the same address, | 633 | | // and any array size has capacity for infinitely many items. | 634 | | // The capacity is limited by the bit width of the length field. | 635 | | // | 636 | | // `Vec` also does this: | 637 | | // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186 | 638 | | // | 639 | | // In our case, this also ensures that a smallvec of zero-size items never spills, | 640 | | // and we never try to allocate zero bytes which `std::alloc::alloc` disallows. | 641 | 0 | core::usize::MAX | 642 | | } | 643 | 5.31M | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::inline_capacity |
644 | | |
645 | | /// The maximum number of elements this vector can hold inline |
646 | | #[inline] |
647 | 615 | pub fn inline_size(&self) -> usize { |
648 | 615 | Self::inline_capacity() |
649 | 615 | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::inline_size Line | Count | Source | 647 | 615 | pub fn inline_size(&self) -> usize { | 648 | 615 | Self::inline_capacity() | 649 | 615 | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::inline_size |
650 | | |
651 | | /// The number of elements stored in the vector |
652 | | #[inline] |
653 | 357k | pub fn len(&self) -> usize { |
654 | 357k | self.triple().1 |
655 | 357k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::len Line | Count | Source | 653 | 357k | pub fn len(&self) -> usize { | 654 | 357k | self.triple().1 | 655 | 357k | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::len |
656 | | |
657 | | /// Returns `true` if the vector is empty |
658 | | #[inline] |
659 | 357k | pub fn is_empty(&self) -> bool { |
660 | 357k | self.len() == 0 |
661 | 357k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::is_empty Line | Count | Source | 659 | 357k | pub fn is_empty(&self) -> bool { | 660 | 357k | self.len() == 0 | 661 | 357k | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::is_empty |
662 | | |
663 | | /// The number of items the vector can hold without reallocating |
664 | | #[inline] |
665 | 0 | pub fn capacity(&self) -> usize { |
666 | 0 | self.triple().2 |
667 | 0 | } |
668 | | |
669 | | /// Returns a tuple with (data ptr, len, capacity) |
670 | | /// Useful to get all SmallVec properties with a single check of the current storage variant. |
671 | | #[inline] |
672 | 716k | fn triple(&self) -> (*const A::Item, usize, usize) { |
673 | | unsafe { |
674 | 716k | if self.spilled() { |
675 | 15.6k | let (ptr, len) = self.data.heap(); |
676 | 15.6k | (ptr, len, self.capacity) |
677 | | } else { |
678 | 701k | (self.data.inline(), self.capacity, Self::inline_capacity()) |
679 | | } |
680 | | } |
681 | 716k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::triple Line | Count | Source | 672 | 716k | fn triple(&self) -> (*const A::Item, usize, usize) { | 673 | | unsafe { | 674 | 716k | if self.spilled() { | 675 | 15.6k | let (ptr, len) = self.data.heap(); | 676 | 15.6k | (ptr, len, self.capacity) | 677 | | } else { | 678 | 701k | (self.data.inline(), self.capacity, Self::inline_capacity()) | 679 | | } | 680 | | } | 681 | 716k | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::triple |
682 | | |
683 | | /// Returns a tuple with (data ptr, len ptr, capacity) |
684 | | #[inline] |
685 | 2.43M | fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { |
686 | | unsafe { |
687 | 2.43M | if self.spilled() { |
688 | 1.34M | let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); |
689 | 1.34M | (ptr, len_ptr, self.capacity) |
690 | | } else { |
691 | 1.08M | ( |
692 | 1.08M | self.data.inline_mut(), |
693 | 1.08M | &mut self.capacity, |
694 | 1.08M | Self::inline_capacity(), |
695 | 1.08M | ) |
696 | | } |
697 | | } |
698 | 2.43M | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::triple_mut Line | Count | Source | 685 | 2.43M | fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { | 686 | | unsafe { | 687 | 2.43M | if self.spilled() { | 688 | 1.34M | let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); | 689 | 1.34M | (ptr, len_ptr, self.capacity) | 690 | | } else { | 691 | 1.08M | ( | 692 | 1.08M | self.data.inline_mut(), | 693 | 1.08M | &mut self.capacity, | 694 | 1.08M | Self::inline_capacity(), | 695 | 1.08M | ) | 696 | | } | 697 | | } | 698 | 2.43M | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::triple_mut |
699 | | |
700 | | /// Returns `true` if the data has spilled into a separate heap-allocated buffer. |
701 | | #[inline] |
702 | 3.52M | pub fn spilled(&self) -> bool { |
703 | 3.52M | self.capacity > Self::inline_capacity() |
704 | 3.52M | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::spilled Line | Count | Source | 702 | 3.52M | pub fn spilled(&self) -> bool { | 703 | 3.52M | self.capacity > Self::inline_capacity() | 704 | 3.52M | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::spilled |
705 | | |
706 | | /// Creates a draining iterator that removes the specified range in the vector |
707 | | /// and yields the removed items. |
708 | | /// |
709 | | /// Note 1: The element range is removed even if the iterator is only |
710 | | /// partially consumed or not consumed at all. |
711 | | /// |
712 | | /// Note 2: It is unspecified how many elements are removed from the vector |
713 | | /// if the `Drain` value is leaked. |
714 | | /// |
715 | | /// # Panics |
716 | | /// |
717 | | /// Panics if the starting point is greater than the end point or if |
718 | | /// the end point is greater than the length of the vector. |
719 | 0 | pub fn drain<R>(&mut self, range: R) -> Drain<'_, A> |
720 | 0 | where |
721 | 0 | R: RangeBounds<usize>, |
722 | | { |
723 | | use core::ops::Bound::*; |
724 | | |
725 | 0 | let len = self.len(); |
726 | 0 | let start = match range.start_bound() { |
727 | 0 | Included(&n) => n, |
728 | 0 | Excluded(&n) => n + 1, |
729 | 0 | Unbounded => 0, |
730 | | }; |
731 | 0 | let end = match range.end_bound() { |
732 | 0 | Included(&n) => n + 1, |
733 | 0 | Excluded(&n) => n, |
734 | 0 | Unbounded => len, |
735 | | }; |
736 | | |
737 | 0 | assert!(start <= end); |
738 | 0 | assert!(end <= len); |
739 | | |
740 | | unsafe { |
741 | 0 | self.set_len(start); |
742 | | |
743 | 0 | let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); |
744 | | |
745 | 0 | Drain { |
746 | 0 | tail_start: end, |
747 | 0 | tail_len: len - end, |
748 | 0 | iter: range_slice.iter(), |
749 | 0 | vec: NonNull::from(self), |
750 | 0 | } |
751 | | } |
752 | 0 | } |
753 | | |
754 | | /// Append an item to the vector. |
755 | | #[inline] |
756 | 1.71M | pub fn push(&mut self, value: A::Item) { |
757 | | unsafe { |
758 | 1.71M | let (mut ptr, mut len, cap) = self.triple_mut(); |
759 | 1.71M | if *len == cap { |
760 | 615 | self.reserve(1); |
761 | 615 | let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); |
762 | 615 | ptr = heap_ptr; |
763 | 615 | len = heap_len; |
764 | 1.71M | } |
765 | 1.71M | ptr::write(ptr.add(*len), value); |
766 | 1.71M | *len += 1; |
767 | | } |
768 | 1.71M | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::push Line | Count | Source | 756 | 1.71M | pub fn push(&mut self, value: A::Item) { | 757 | | unsafe { | 758 | 1.71M | let (mut ptr, mut len, cap) = self.triple_mut(); | 759 | 1.71M | if *len == cap { | 760 | 615 | self.reserve(1); | 761 | 615 | let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); | 762 | 615 | ptr = heap_ptr; | 763 | 615 | len = heap_len; | 764 | 1.71M | } | 765 | 1.71M | ptr::write(ptr.add(*len), value); | 766 | 1.71M | *len += 1; | 767 | | } | 768 | 1.71M | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::push |
769 | | |
770 | | /// Remove an item from the end of the vector and return it, or None if empty. |
771 | | #[inline] |
772 | 357k | pub fn pop(&mut self) -> Option<A::Item> { |
773 | | unsafe { |
774 | 357k | let (ptr, len_ptr, _) = self.triple_mut(); |
775 | 357k | if *len_ptr == 0 { |
776 | 0 | return None; |
777 | 357k | } |
778 | 357k | let last_index = *len_ptr - 1; |
779 | 357k | *len_ptr = last_index; |
780 | 357k | Some(ptr::read(ptr.add(last_index))) |
781 | | } |
782 | 357k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::pop Line | Count | Source | 772 | 357k | pub fn pop(&mut self) -> Option<A::Item> { | 773 | | unsafe { | 774 | 357k | let (ptr, len_ptr, _) = self.triple_mut(); | 775 | 357k | if *len_ptr == 0 { | 776 | 0 | return None; | 777 | 357k | } | 778 | 357k | let last_index = *len_ptr - 1; | 779 | 357k | *len_ptr = last_index; | 780 | 357k | Some(ptr::read(ptr.add(last_index))) | 781 | | } | 782 | 357k | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::pop |
783 | | |
784 | | /// Moves all the elements of `other` into `self`, leaving `other` empty. |
785 | | /// |
786 | | /// # Example |
787 | | /// |
788 | | /// ``` |
789 | | /// # use smallvec::{SmallVec, smallvec}; |
790 | | /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3]; |
791 | | /// let mut v1: SmallVec<[u8; 32]> = smallvec![4, 5, 6]; |
792 | | /// v0.append(&mut v1); |
793 | | /// assert_eq!(*v0, [1, 2, 3, 4, 5, 6]); |
794 | | /// assert_eq!(*v1, []); |
795 | | /// ``` |
796 | 0 | pub fn append<B>(&mut self, other: &mut SmallVec<B>) |
797 | 0 | where |
798 | 0 | B: Array<Item = A::Item>, |
799 | | { |
800 | 0 | self.extend(other.drain(..)) |
801 | 0 | } |
802 | | |
803 | | /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. |
804 | | /// |
805 | | /// Panics if `new_cap` is less than the vector's length |
806 | | /// or if the capacity computation overflows `usize`. |
807 | 0 | pub fn grow(&mut self, new_cap: usize) { |
808 | 0 | infallible(self.try_grow(new_cap)) |
809 | 0 | } |
810 | | |
811 | | /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. |
812 | | /// |
813 | | /// Panics if `new_cap` is less than the vector's length |
814 | 615 | pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { |
815 | | unsafe { |
816 | 615 | let (ptr, &mut len, cap) = self.triple_mut(); |
817 | 615 | let unspilled = !self.spilled(); |
818 | 615 | assert!(new_cap >= len); |
819 | 615 | if new_cap <= self.inline_size() { |
820 | 0 | if unspilled { |
821 | 0 | return Ok(()); |
822 | 0 | } |
823 | 0 | self.data = SmallVecData::from_inline(MaybeUninit::uninit()); |
824 | 0 | ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); |
825 | 0 | self.capacity = len; |
826 | 0 | deallocate(ptr, cap); |
827 | 615 | } else if new_cap != cap { |
828 | 615 | let layout = layout_array::<A::Item>(new_cap)?; |
829 | 615 | debug_assert!(layout.size() > 0); |
830 | | let new_alloc; |
831 | 615 | if unspilled { |
832 | 290 | new_alloc = NonNull::new(alloc::alloc::alloc(layout)) |
833 | 290 | .ok_or(CollectionAllocErr::AllocErr { layout })? |
834 | 290 | .cast() |
835 | 290 | .as_ptr(); |
836 | 290 | ptr::copy_nonoverlapping(ptr, new_alloc, len); |
837 | | } else { |
838 | | // This should never fail since the same succeeded |
839 | | // when previously allocating `ptr`. |
840 | 325 | let old_layout = layout_array::<A::Item>(cap)?; |
841 | | |
842 | 325 | let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); |
843 | 325 | new_alloc = NonNull::new(new_ptr) |
844 | 325 | .ok_or(CollectionAllocErr::AllocErr { layout })? |
845 | 325 | .cast() |
846 | 325 | .as_ptr(); |
847 | | } |
848 | 615 | self.data = SmallVecData::from_heap(new_alloc, len); |
849 | 615 | self.capacity = new_cap; |
850 | 0 | } |
851 | 615 | Ok(()) |
852 | | } |
853 | 615 | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::try_grow Line | Count | Source | 814 | 615 | pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { | 815 | | unsafe { | 816 | 615 | let (ptr, &mut len, cap) = self.triple_mut(); | 817 | 615 | let unspilled = !self.spilled(); | 818 | 615 | assert!(new_cap >= len); | 819 | 615 | if new_cap <= self.inline_size() { | 820 | 0 | if unspilled { | 821 | 0 | return Ok(()); | 822 | 0 | } | 823 | 0 | self.data = SmallVecData::from_inline(MaybeUninit::uninit()); | 824 | 0 | ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); | 825 | 0 | self.capacity = len; | 826 | 0 | deallocate(ptr, cap); | 827 | 615 | } else if new_cap != cap { | 828 | 615 | let layout = layout_array::<A::Item>(new_cap)?; | 829 | 615 | debug_assert!(layout.size() > 0); | 830 | | let new_alloc; | 831 | 615 | if unspilled { | 832 | 290 | new_alloc = NonNull::new(alloc::alloc::alloc(layout)) | 833 | 290 | .ok_or(CollectionAllocErr::AllocErr { layout })? | 834 | 290 | .cast() | 835 | 290 | .as_ptr(); | 836 | 290 | ptr::copy_nonoverlapping(ptr, new_alloc, len); | 837 | | } else { | 838 | | // This should never fail since the same succeeded | 839 | | // when previously allocating `ptr`. | 840 | 325 | let old_layout = layout_array::<A::Item>(cap)?; | 841 | | | 842 | 325 | let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); | 843 | 325 | new_alloc = NonNull::new(new_ptr) | 844 | 325 | .ok_or(CollectionAllocErr::AllocErr { layout })? | 845 | 325 | .cast() | 846 | 325 | .as_ptr(); | 847 | | } | 848 | 615 | self.data = SmallVecData::from_heap(new_alloc, len); | 849 | 615 | self.capacity = new_cap; | 850 | 0 | } | 851 | 615 | Ok(()) | 852 | | } | 853 | 615 | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::try_grow |
854 | | |
855 | | /// Reserve capacity for `additional` more elements to be inserted. |
856 | | /// |
857 | | /// May reserve more space to avoid frequent reallocations. |
858 | | /// |
859 | | /// Panics if the capacity computation overflows `usize`. |
860 | | #[inline] |
861 | 615 | pub fn reserve(&mut self, additional: usize) { |
862 | 615 | infallible(self.try_reserve(additional)) |
863 | 615 | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::reserve Line | Count | Source | 861 | 615 | pub fn reserve(&mut self, additional: usize) { | 862 | 615 | infallible(self.try_reserve(additional)) | 863 | 615 | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::reserve |
864 | | |
865 | | /// Reserve capacity for `additional` more elements to be inserted. |
866 | | /// |
867 | | /// May reserve more space to avoid frequent reallocations. |
868 | 615 | pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { |
869 | | // prefer triple_mut() even if triple() would work |
870 | | // so that the optimizer removes duplicated calls to it |
871 | | // from callers like insert() |
872 | 615 | let (_, &mut len, cap) = self.triple_mut(); |
873 | 615 | if cap - len >= additional { |
874 | 0 | return Ok(()); |
875 | 615 | } |
876 | 615 | let new_cap = len |
877 | 615 | .checked_add(additional) |
878 | 615 | .and_then(usize::checked_next_power_of_two) |
879 | 615 | .ok_or(CollectionAllocErr::CapacityOverflow)?; |
880 | 615 | self.try_grow(new_cap) |
881 | 615 | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]>>::try_reserve Line | Count | Source | 868 | 615 | pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { | 869 | | // prefer triple_mut() even if triple() would work | 870 | | // so that the optimizer removes duplicated calls to it | 871 | | // from callers like insert() | 872 | 615 | let (_, &mut len, cap) = self.triple_mut(); | 873 | 615 | if cap - len >= additional { | 874 | 0 | return Ok(()); | 875 | 615 | } | 876 | 615 | let new_cap = len | 877 | 615 | .checked_add(additional) | 878 | 615 | .and_then(usize::checked_next_power_of_two) | 879 | 615 | .ok_or(CollectionAllocErr::CapacityOverflow)?; | 880 | 615 | self.try_grow(new_cap) | 881 | 615 | } |
Unexecuted instantiation: <smallvec::SmallVec<_>>::try_reserve |
882 | | |
883 | | /// Reserve the minimum capacity for `additional` more elements to be inserted. |
884 | | /// |
885 | | /// Panics if the new capacity overflows `usize`. |
886 | 0 | pub fn reserve_exact(&mut self, additional: usize) { |
887 | 0 | infallible(self.try_reserve_exact(additional)) |
888 | 0 | } |
889 | | |
890 | | /// Reserve the minimum capacity for `additional` more elements to be inserted. |
891 | 0 | pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { |
892 | 0 | let (_, &mut len, cap) = self.triple_mut(); |
893 | 0 | if cap - len >= additional { |
894 | 0 | return Ok(()); |
895 | 0 | } |
896 | 0 | let new_cap = len |
897 | 0 | .checked_add(additional) |
898 | 0 | .ok_or(CollectionAllocErr::CapacityOverflow)?; |
899 | 0 | self.try_grow(new_cap) |
900 | 0 | } |
901 | | |
902 | | /// Shrink the capacity of the vector as much as possible. |
903 | | /// |
904 | | /// When possible, this will move data from an external heap buffer to the vector's inline |
905 | | /// storage. |
906 | 0 | pub fn shrink_to_fit(&mut self) { |
907 | 0 | if !self.spilled() { |
908 | 0 | return; |
909 | 0 | } |
910 | 0 | let len = self.len(); |
911 | 0 | if self.inline_size() >= len { |
912 | 0 | unsafe { |
913 | 0 | let (ptr, len) = self.data.heap(); |
914 | 0 | self.data = SmallVecData::from_inline(MaybeUninit::uninit()); |
915 | 0 | ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); |
916 | 0 | deallocate(ptr, self.capacity); |
917 | 0 | self.capacity = len; |
918 | 0 | } |
919 | 0 | } else if self.capacity() > len { |
920 | 0 | self.grow(len); |
921 | 0 | } |
922 | 0 | } |
923 | | |
924 | | /// Shorten the vector, keeping the first `len` elements and dropping the rest. |
925 | | /// |
926 | | /// If `len` is greater than or equal to the vector's current length, this has no |
927 | | /// effect. |
928 | | /// |
929 | | /// This does not re-allocate. If you want the vector's capacity to shrink, call |
930 | | /// `shrink_to_fit` after truncating. |
931 | 0 | pub fn truncate(&mut self, len: usize) { |
932 | | unsafe { |
933 | 0 | let (ptr, len_ptr, _) = self.triple_mut(); |
934 | 0 | while len < *len_ptr { |
935 | 0 | let last_index = *len_ptr - 1; |
936 | 0 | *len_ptr = last_index; |
937 | 0 | ptr::drop_in_place(ptr.add(last_index)); |
938 | 0 | } |
939 | | } |
940 | 0 | } |
941 | | |
942 | | /// Extracts a slice containing the entire vector. |
943 | | /// |
944 | | /// Equivalent to `&s[..]`. |
945 | 0 | pub fn as_slice(&self) -> &[A::Item] { |
946 | 0 | self |
947 | 0 | } |
948 | | |
949 | | /// Extracts a mutable slice of the entire vector. |
950 | | /// |
951 | | /// Equivalent to `&mut s[..]`. |
952 | 0 | pub fn as_mut_slice(&mut self) -> &mut [A::Item] { |
953 | 0 | self |
954 | 0 | } |
955 | | |
956 | | /// Remove the element at position `index`, replacing it with the last element. |
957 | | /// |
958 | | /// This does not preserve ordering, but is O(1). |
959 | | /// |
960 | | /// Panics if `index` is out of bounds. |
961 | | #[inline] |
962 | 0 | pub fn swap_remove(&mut self, index: usize) -> A::Item { |
963 | 0 | let len = self.len(); |
964 | 0 | self.swap(len - 1, index); |
965 | 0 | self.pop() |
966 | 0 | .unwrap_or_else(|| unsafe { unreachable_unchecked() }) |
967 | 0 | } |
968 | | |
969 | | /// Remove all elements from the vector. |
970 | | #[inline] |
971 | 0 | pub fn clear(&mut self) { |
972 | 0 | self.truncate(0); |
973 | 0 | } |
974 | | |
975 | | /// Remove and return the element at position `index`, shifting all elements after it to the |
976 | | /// left. |
977 | | /// |
978 | | /// Panics if `index` is out of bounds. |
979 | 0 | pub fn remove(&mut self, index: usize) -> A::Item { |
980 | | unsafe { |
981 | 0 | let (mut ptr, len_ptr, _) = self.triple_mut(); |
982 | 0 | let len = *len_ptr; |
983 | 0 | assert!(index < len); |
984 | 0 | *len_ptr = len - 1; |
985 | 0 | ptr = ptr.add(index); |
986 | 0 | let item = ptr::read(ptr); |
987 | 0 | ptr::copy(ptr.add(1), ptr, len - index - 1); |
988 | 0 | item |
989 | | } |
990 | 0 | } |
991 | | |
992 | | /// Insert an element at position `index`, shifting all elements after it to the right. |
993 | | /// |
994 | | /// Panics if `index` is out of bounds. |
995 | 0 | pub fn insert(&mut self, index: usize, element: A::Item) { |
996 | 0 | self.reserve(1); |
997 | | |
998 | | unsafe { |
999 | 0 | let (mut ptr, len_ptr, _) = self.triple_mut(); |
1000 | 0 | let len = *len_ptr; |
1001 | 0 | assert!(index <= len); |
1002 | 0 | *len_ptr = len + 1; |
1003 | 0 | ptr = ptr.add(index); |
1004 | 0 | ptr::copy(ptr, ptr.add(1), len - index); |
1005 | 0 | ptr::write(ptr, element); |
1006 | | } |
1007 | 0 | } |
1008 | | |
1009 | | /// Insert multiple elements at position `index`, shifting all following elements toward the |
1010 | | /// back. |
1011 | 0 | pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) { |
1012 | 0 | let mut iter = iterable.into_iter(); |
1013 | 0 | if index == self.len() { |
1014 | 0 | return self.extend(iter); |
1015 | 0 | } |
1016 | | |
1017 | 0 | let (lower_size_bound, _) = iter.size_hint(); |
1018 | 0 | assert!(lower_size_bound <= core::isize::MAX as usize); // Ensure offset is indexable |
1019 | 0 | assert!(index + lower_size_bound >= index); // Protect against overflow |
1020 | | |
1021 | 0 | let mut num_added = 0; |
1022 | 0 | let old_len = self.len(); |
1023 | 0 | assert!(index <= old_len); |
1024 | | |
1025 | | unsafe { |
1026 | | // Reserve space for `lower_size_bound` elements. |
1027 | 0 | self.reserve(lower_size_bound); |
1028 | 0 | let start = self.as_mut_ptr(); |
1029 | 0 | let ptr = start.add(index); |
1030 | | |
1031 | | // Move the trailing elements. |
1032 | 0 | ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index); |
1033 | | |
1034 | | // In case the iterator panics, don't double-drop the items we just copied above. |
1035 | 0 | self.set_len(0); |
1036 | 0 | let mut guard = DropOnPanic { |
1037 | 0 | start, |
1038 | 0 | skip: index..(index + lower_size_bound), |
1039 | 0 | len: old_len + lower_size_bound, |
1040 | 0 | }; |
1041 | | |
1042 | 0 | while num_added < lower_size_bound { |
1043 | 0 | let element = match iter.next() { |
1044 | 0 | Some(x) => x, |
1045 | 0 | None => break, |
1046 | | }; |
1047 | 0 | let cur = ptr.add(num_added); |
1048 | 0 | ptr::write(cur, element); |
1049 | 0 | guard.skip.start += 1; |
1050 | 0 | num_added += 1; |
1051 | | } |
1052 | | |
1053 | 0 | if num_added < lower_size_bound { |
1054 | 0 | // Iterator provided fewer elements than the hint. Move the tail backward. |
1055 | 0 | ptr::copy( |
1056 | 0 | ptr.add(lower_size_bound), |
1057 | 0 | ptr.add(num_added), |
1058 | 0 | old_len - index, |
1059 | 0 | ); |
1060 | 0 | } |
1061 | | // There are no more duplicate or uninitialized slots, so the guard is not needed. |
1062 | 0 | self.set_len(old_len + num_added); |
1063 | 0 | mem::forget(guard); |
1064 | | } |
1065 | | |
1066 | | // Insert any remaining elements one-by-one. |
1067 | 0 | for element in iter { |
1068 | 0 | self.insert(index + num_added, element); |
1069 | 0 | num_added += 1; |
1070 | 0 | } |
1071 | | |
1072 | | struct DropOnPanic<T> { |
1073 | | start: *mut T, |
1074 | | skip: Range<usize>, // Space we copied-out-of, but haven't written-to yet. |
1075 | | len: usize, |
1076 | | } |
1077 | | |
1078 | | impl<T> Drop for DropOnPanic<T> { |
1079 | 0 | fn drop(&mut self) { |
1080 | 0 | for i in 0..self.len { |
1081 | 0 | if !self.skip.contains(&i) { |
1082 | 0 | unsafe { |
1083 | 0 | ptr::drop_in_place(self.start.add(i)); |
1084 | 0 | } |
1085 | 0 | } |
1086 | | } |
1087 | 0 | } |
1088 | | } |
1089 | 0 | } |
1090 | | |
1091 | | /// Convert a SmallVec to a Vec, without reallocating if the SmallVec has already spilled onto |
1092 | | /// the heap. |
1093 | 0 | pub fn into_vec(self) -> Vec<A::Item> { |
1094 | 0 | if self.spilled() { |
1095 | | unsafe { |
1096 | 0 | let (ptr, len) = self.data.heap(); |
1097 | 0 | let v = Vec::from_raw_parts(ptr, len, self.capacity); |
1098 | 0 | mem::forget(self); |
1099 | 0 | v |
1100 | | } |
1101 | | } else { |
1102 | 0 | self.into_iter().collect() |
1103 | | } |
1104 | 0 | } |
1105 | | |
1106 | | /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the `SmallVec` has already spilled |
1107 | | /// onto the heap. |
1108 | | /// |
1109 | | /// Note that this will drop any excess capacity. |
1110 | 0 | pub fn into_boxed_slice(self) -> Box<[A::Item]> { |
1111 | 0 | self.into_vec().into_boxed_slice() |
1112 | 0 | } |
1113 | | |
1114 | | /// Convert the SmallVec into an `A` if possible. Otherwise return `Err(Self)`. |
1115 | | /// |
1116 | | /// This method returns `Err(Self)` if the SmallVec is too short (and the `A` contains uninitialized elements), |
1117 | | /// or if the SmallVec is too long (and all the elements were spilled to the heap). |
1118 | 0 | pub fn into_inner(self) -> Result<A, Self> { |
1119 | 0 | if self.spilled() || self.len() != A::size() { |
1120 | | // Note: A::size, not Self::inline_capacity |
1121 | 0 | Err(self) |
1122 | | } else { |
1123 | | unsafe { |
1124 | 0 | let data = ptr::read(&self.data); |
1125 | 0 | mem::forget(self); |
1126 | 0 | Ok(data.into_inline().assume_init()) |
1127 | | } |
1128 | | } |
1129 | 0 | } |
1130 | | |
1131 | | /// Retains only the elements specified by the predicate. |
1132 | | /// |
1133 | | /// In other words, remove all elements `e` such that `f(&e)` returns `false`. |
1134 | | /// This method operates in place and preserves the order of the retained |
1135 | | /// elements. |
1136 | 0 | pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) { |
1137 | 0 | let mut del = 0; |
1138 | 0 | let len = self.len(); |
1139 | 0 | for i in 0..len { |
1140 | 0 | if !f(&mut self[i]) { |
1141 | 0 | del += 1; |
1142 | 0 | } else if del > 0 { |
1143 | 0 | self.swap(i - del, i); |
1144 | 0 | } |
1145 | | } |
1146 | 0 | self.truncate(len - del); |
1147 | 0 | } |
1148 | | |
1149 | | /// Removes consecutive duplicate elements. |
1150 | 0 | pub fn dedup(&mut self) |
1151 | 0 | where |
1152 | 0 | A::Item: PartialEq<A::Item>, |
1153 | | { |
1154 | 0 | self.dedup_by(|a, b| a == b); |
1155 | 0 | } |
1156 | | |
1157 | | /// Removes consecutive duplicate elements using the given equality relation. |
1158 | 0 | pub fn dedup_by<F>(&mut self, mut same_bucket: F) |
1159 | 0 | where |
1160 | 0 | F: FnMut(&mut A::Item, &mut A::Item) -> bool, |
1161 | | { |
1162 | | // See the implementation of Vec::dedup_by in the |
1163 | | // standard library for an explanation of this algorithm. |
1164 | 0 | let len = self.len(); |
1165 | 0 | if len <= 1 { |
1166 | 0 | return; |
1167 | 0 | } |
1168 | | |
1169 | 0 | let ptr = self.as_mut_ptr(); |
1170 | 0 | let mut w: usize = 1; |
1171 | | |
1172 | | unsafe { |
1173 | 0 | for r in 1..len { |
1174 | 0 | let p_r = ptr.add(r); |
1175 | 0 | let p_wm1 = ptr.add(w - 1); |
1176 | 0 | if !same_bucket(&mut *p_r, &mut *p_wm1) { |
1177 | 0 | if r != w { |
1178 | 0 | let p_w = p_wm1.add(1); |
1179 | 0 | mem::swap(&mut *p_r, &mut *p_w); |
1180 | 0 | } |
1181 | 0 | w += 1; |
1182 | 0 | } |
1183 | | } |
1184 | | } |
1185 | | |
1186 | 0 | self.truncate(w); |
1187 | 0 | } |
1188 | | |
1189 | | /// Removes consecutive elements that map to the same key. |
1190 | 0 | pub fn dedup_by_key<F, K>(&mut self, mut key: F) |
1191 | 0 | where |
1192 | 0 | F: FnMut(&mut A::Item) -> K, |
1193 | 0 | K: PartialEq<K>, |
1194 | | { |
1195 | 0 | self.dedup_by(|a, b| key(a) == key(b)); |
1196 | 0 | } |
1197 | | |
1198 | | /// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`. |
1199 | | /// |
1200 | | /// If `new_len` is greater than `len`, the `SmallVec` is extended by the difference, with each |
1201 | | /// additional slot filled with the result of calling the closure `f`. The return values from `f` |
1202 | | //// will end up in the `SmallVec` in the order they have been generated. |
1203 | | /// |
1204 | | /// If `new_len` is less than `len`, the `SmallVec` is simply truncated. |
1205 | | /// |
1206 | | /// This method uses a closure to create new values on every push. If you'd rather `Clone` a given |
1207 | | /// value, use `resize`. If you want to use the `Default` trait to generate values, you can pass |
1208 | | /// `Default::default()` as the second argument. |
1209 | | /// |
1210 | | /// Added for std::vec::Vec compatibility (added in Rust 1.33.0) |
1211 | | /// |
1212 | | /// ``` |
1213 | | /// # use smallvec::{smallvec, SmallVec}; |
1214 | | /// let mut vec : SmallVec<[_; 4]> = smallvec![1, 2, 3]; |
1215 | | /// vec.resize_with(5, Default::default); |
1216 | | /// assert_eq!(&*vec, &[1, 2, 3, 0, 0]); |
1217 | | /// |
1218 | | /// let mut vec : SmallVec<[_; 4]> = smallvec![]; |
1219 | | /// let mut p = 1; |
1220 | | /// vec.resize_with(4, || { p *= 2; p }); |
1221 | | /// assert_eq!(&*vec, &[2, 4, 8, 16]); |
1222 | | /// ``` |
1223 | 0 | pub fn resize_with<F>(&mut self, new_len: usize, f: F) |
1224 | 0 | where |
1225 | 0 | F: FnMut() -> A::Item, |
1226 | | { |
1227 | 0 | let old_len = self.len(); |
1228 | 0 | if old_len < new_len { |
1229 | 0 | let mut f = f; |
1230 | 0 | let additional = new_len - old_len; |
1231 | 0 | self.reserve(additional); |
1232 | 0 | for _ in 0..additional { |
1233 | 0 | self.push(f()); |
1234 | 0 | } |
1235 | 0 | } else if old_len > new_len { |
1236 | 0 | self.truncate(new_len); |
1237 | 0 | } |
1238 | 0 | } |
1239 | | |
1240 | | /// Creates a `SmallVec` directly from the raw components of another |
1241 | | /// `SmallVec`. |
1242 | | /// |
1243 | | /// # Safety |
1244 | | /// |
1245 | | /// This is highly unsafe, due to the number of invariants that aren't |
1246 | | /// checked: |
1247 | | /// |
1248 | | /// * `ptr` needs to have been previously allocated via `SmallVec` for its |
1249 | | /// spilled storage (at least, it's highly likely to be incorrect if it |
1250 | | /// wasn't). |
1251 | | /// * `ptr`'s `A::Item` type needs to be the same size and alignment that |
1252 | | /// it was allocated with |
1253 | | /// * `length` needs to be less than or equal to `capacity`. |
1254 | | /// * `capacity` needs to be the capacity that the pointer was allocated |
1255 | | /// with. |
1256 | | /// |
1257 | | /// Violating these may cause problems like corrupting the allocator's |
1258 | | /// internal data structures. |
1259 | | /// |
1260 | | /// Additionally, `capacity` must be greater than the amount of inline |
1261 | | /// storage `A` has; that is, the new `SmallVec` must need to spill over |
1262 | | /// into heap allocated storage. This condition is asserted against. |
1263 | | /// |
1264 | | /// The ownership of `ptr` is effectively transferred to the |
1265 | | /// `SmallVec` which may then deallocate, reallocate or change the |
1266 | | /// contents of memory pointed to by the pointer at will. Ensure |
1267 | | /// that nothing else uses the pointer after calling this |
1268 | | /// function. |
1269 | | /// |
1270 | | /// # Examples |
1271 | | /// |
1272 | | /// ``` |
1273 | | /// # #[macro_use] extern crate smallvec; |
1274 | | /// # use smallvec::SmallVec; |
1275 | | /// use std::mem; |
1276 | | /// use std::ptr; |
1277 | | /// |
1278 | | /// fn main() { |
1279 | | /// let mut v: SmallVec<[_; 1]> = smallvec![1, 2, 3]; |
1280 | | /// |
1281 | | /// // Pull out the important parts of `v`. |
1282 | | /// let p = v.as_mut_ptr(); |
1283 | | /// let len = v.len(); |
1284 | | /// let cap = v.capacity(); |
1285 | | /// let spilled = v.spilled(); |
1286 | | /// |
1287 | | /// unsafe { |
1288 | | /// // Forget all about `v`. The heap allocation that stored the |
1289 | | /// // three values won't be deallocated. |
1290 | | /// mem::forget(v); |
1291 | | /// |
1292 | | /// // Overwrite memory with [4, 5, 6]. |
1293 | | /// // |
1294 | | /// // This is only safe if `spilled` is true! Otherwise, we are |
1295 | | /// // writing into the old `SmallVec`'s inline storage on the |
1296 | | /// // stack. |
1297 | | /// assert!(spilled); |
1298 | | /// for i in 0..len { |
1299 | | /// ptr::write(p.add(i), 4 + i); |
1300 | | /// } |
1301 | | /// |
1302 | | /// // Put everything back together into a SmallVec with a different |
1303 | | /// // amount of inline storage, but which is still less than `cap`. |
1304 | | /// let rebuilt = SmallVec::<[_; 2]>::from_raw_parts(p, len, cap); |
1305 | | /// assert_eq!(&*rebuilt, &[4, 5, 6]); |
1306 | | /// } |
1307 | | /// } |
1308 | | #[inline] |
1309 | 0 | pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> { |
1310 | 0 | assert!(capacity > Self::inline_capacity()); |
1311 | 0 | SmallVec { |
1312 | 0 | capacity, |
1313 | 0 | data: SmallVecData::from_heap(ptr, length), |
1314 | 0 | } |
1315 | 0 | } |
1316 | | |
1317 | | /// Returns a raw pointer to the vector's buffer. |
1318 | 0 | pub fn as_ptr(&self) -> *const A::Item { |
1319 | | // We shadow the slice method of the same name to avoid going through |
1320 | | // `deref`, which creates an intermediate reference that may place |
1321 | | // additional safety constraints on the contents of the slice. |
1322 | 0 | self.triple().0 |
1323 | 0 | } |
1324 | | |
1325 | | /// Returns a raw mutable pointer to the vector's buffer. |
1326 | 0 | pub fn as_mut_ptr(&mut self) -> *mut A::Item { |
1327 | | // We shadow the slice method of the same name to avoid going through |
1328 | | // `deref_mut`, which creates an intermediate reference that may place |
1329 | | // additional safety constraints on the contents of the slice. |
1330 | 0 | self.triple_mut().0 |
1331 | 0 | } |
1332 | | } |
1333 | | |
1334 | | impl<A: Array> SmallVec<A> |
1335 | | where |
1336 | | A::Item: Copy, |
1337 | | { |
1338 | | /// Copy the elements from a slice into a new `SmallVec`. |
1339 | | /// |
1340 | | /// For slices of `Copy` types, this is more efficient than `SmallVec::from(slice)`. |
1341 | 0 | pub fn from_slice(slice: &[A::Item]) -> Self { |
1342 | 0 | let len = slice.len(); |
1343 | 0 | if len <= Self::inline_capacity() { |
1344 | 0 | SmallVec { |
1345 | 0 | capacity: len, |
1346 | 0 | data: SmallVecData::from_inline(unsafe { |
1347 | 0 | let mut data: MaybeUninit<A> = MaybeUninit::uninit(); |
1348 | 0 | ptr::copy_nonoverlapping( |
1349 | 0 | slice.as_ptr(), |
1350 | 0 | data.as_mut_ptr() as *mut A::Item, |
1351 | 0 | len, |
1352 | 0 | ); |
1353 | 0 | data |
1354 | 0 | }), |
1355 | 0 | } |
1356 | | } else { |
1357 | 0 | let mut b = slice.to_vec(); |
1358 | 0 | let (ptr, cap) = (b.as_mut_ptr(), b.capacity()); |
1359 | 0 | mem::forget(b); |
1360 | 0 | SmallVec { |
1361 | 0 | capacity: cap, |
1362 | 0 | data: SmallVecData::from_heap(ptr, len), |
1363 | 0 | } |
1364 | | } |
1365 | 0 | } |
1366 | | |
1367 | | /// Copy elements from a slice into the vector at position `index`, shifting any following |
1368 | | /// elements toward the back. |
1369 | | /// |
1370 | | /// For slices of `Copy` types, this is more efficient than `insert`. |
1371 | 0 | pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { |
1372 | 0 | self.reserve(slice.len()); |
1373 | | |
1374 | 0 | let len = self.len(); |
1375 | 0 | assert!(index <= len); |
1376 | | |
1377 | 0 | unsafe { |
1378 | 0 | let slice_ptr = slice.as_ptr(); |
1379 | 0 | let ptr = self.as_mut_ptr().add(index); |
1380 | 0 | ptr::copy(ptr, ptr.add(slice.len()), len - index); |
1381 | 0 | ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); |
1382 | 0 | self.set_len(len + slice.len()); |
1383 | 0 | } |
1384 | 0 | } |
1385 | | |
1386 | | /// Copy elements from a slice and append them to the vector. |
1387 | | /// |
1388 | | /// For slices of `Copy` types, this is more efficient than `extend`. |
1389 | | #[inline] |
1390 | 0 | pub fn extend_from_slice(&mut self, slice: &[A::Item]) { |
1391 | 0 | let len = self.len(); |
1392 | 0 | self.insert_from_slice(len, slice); |
1393 | 0 | } |
1394 | | } |
1395 | | |
1396 | | impl<A: Array> SmallVec<A> |
1397 | | where |
1398 | | A::Item: Clone, |
1399 | | { |
1400 | | /// Resizes the vector so that its length is equal to `len`. |
1401 | | /// |
1402 | | /// If `len` is less than the current length, the vector simply truncated. |
1403 | | /// |
1404 | | /// If `len` is greater than the current length, `value` is appended to the |
1405 | | /// vector until its length equals `len`. |
1406 | 0 | pub fn resize(&mut self, len: usize, value: A::Item) { |
1407 | 0 | let old_len = self.len(); |
1408 | | |
1409 | 0 | if len > old_len { |
1410 | 0 | self.extend(repeat(value).take(len - old_len)); |
1411 | 0 | } else { |
1412 | 0 | self.truncate(len); |
1413 | 0 | } |
1414 | 0 | } |
1415 | | |
1416 | | /// Creates a `SmallVec` with `n` copies of `elem`. |
1417 | | /// ``` |
1418 | | /// use smallvec::SmallVec; |
1419 | | /// |
1420 | | /// let v = SmallVec::<[char; 128]>::from_elem('d', 2); |
1421 | | /// assert_eq!(v, SmallVec::from_buf(['d', 'd'])); |
1422 | | /// ``` |
1423 | 0 | pub fn from_elem(elem: A::Item, n: usize) -> Self { |
1424 | 0 | if n > Self::inline_capacity() { |
1425 | 0 | vec![elem; n].into() |
1426 | | } else { |
1427 | 0 | let mut v = SmallVec::<A>::new(); |
1428 | | unsafe { |
1429 | 0 | let (ptr, len_ptr, _) = v.triple_mut(); |
1430 | 0 | let mut local_len = SetLenOnDrop::new(len_ptr); |
1431 | | |
1432 | 0 | for i in 0..n { |
1433 | 0 | ::core::ptr::write(ptr.add(i), elem.clone()); |
1434 | 0 | local_len.increment_len(1); |
1435 | 0 | } |
1436 | | } |
1437 | 0 | v |
1438 | | } |
1439 | 0 | } |
1440 | | } |
1441 | | |
1442 | | impl<A: Array> ops::Deref for SmallVec<A> { |
1443 | | type Target = [A::Item]; |
1444 | | #[inline] |
1445 | 359k | fn deref(&self) -> &[A::Item] { |
1446 | | unsafe { |
1447 | 359k | let (ptr, len, _) = self.triple(); |
1448 | 359k | slice::from_raw_parts(ptr, len) |
1449 | | } |
1450 | 359k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]> as core::ops::deref::Deref>::deref Line | Count | Source | 1445 | 359k | fn deref(&self) -> &[A::Item] { | 1446 | | unsafe { | 1447 | 359k | let (ptr, len, _) = self.triple(); | 1448 | 359k | slice::from_raw_parts(ptr, len) | 1449 | | } | 1450 | 359k | } |
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::deref::Deref>::deref |
1451 | | } |
1452 | | |
1453 | | impl<A: Array> ops::DerefMut for SmallVec<A> { |
1454 | | #[inline] |
1455 | 366k | fn deref_mut(&mut self) -> &mut [A::Item] { |
1456 | 366k | unsafe { |
1457 | 366k | let (ptr, &mut len, _) = self.triple_mut(); |
1458 | 366k | slice::from_raw_parts_mut(ptr, len) |
1459 | 366k | } |
1460 | 366k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]> as core::ops::deref::DerefMut>::deref_mut Line | Count | Source | 1455 | 366k | fn deref_mut(&mut self) -> &mut [A::Item] { | 1456 | 366k | unsafe { | 1457 | 366k | let (ptr, &mut len, _) = self.triple_mut(); | 1458 | 366k | slice::from_raw_parts_mut(ptr, len) | 1459 | 366k | } | 1460 | 366k | } |
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::deref::DerefMut>::deref_mut |
1461 | | } |
1462 | | |
1463 | | impl<A: Array> AsRef<[A::Item]> for SmallVec<A> { |
1464 | | #[inline] |
1465 | 0 | fn as_ref(&self) -> &[A::Item] { |
1466 | 0 | self |
1467 | 0 | } |
1468 | | } |
1469 | | |
1470 | | impl<A: Array> AsMut<[A::Item]> for SmallVec<A> { |
1471 | | #[inline] |
1472 | 0 | fn as_mut(&mut self) -> &mut [A::Item] { |
1473 | 0 | self |
1474 | 0 | } |
1475 | | } |
1476 | | |
1477 | | impl<A: Array> Borrow<[A::Item]> for SmallVec<A> { |
1478 | | #[inline] |
1479 | 0 | fn borrow(&self) -> &[A::Item] { |
1480 | 0 | self |
1481 | 0 | } |
1482 | | } |
1483 | | |
1484 | | impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> { |
1485 | | #[inline] |
1486 | 0 | fn borrow_mut(&mut self) -> &mut [A::Item] { |
1487 | 0 | self |
1488 | 0 | } |
1489 | | } |
1490 | | |
1491 | | #[cfg(feature = "write")] |
1492 | | impl<A: Array<Item = u8>> io::Write for SmallVec<A> { |
1493 | | #[inline] |
1494 | | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
1495 | | self.extend_from_slice(buf); |
1496 | | Ok(buf.len()) |
1497 | | } |
1498 | | |
1499 | | #[inline] |
1500 | | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { |
1501 | | self.extend_from_slice(buf); |
1502 | | Ok(()) |
1503 | | } |
1504 | | |
1505 | | #[inline] |
1506 | | fn flush(&mut self) -> io::Result<()> { |
1507 | | Ok(()) |
1508 | | } |
1509 | | } |
1510 | | |
1511 | | #[cfg(feature = "serde")] |
1512 | | impl<A: Array> Serialize for SmallVec<A> |
1513 | | where |
1514 | | A::Item: Serialize, |
1515 | | { |
1516 | | fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { |
1517 | | let mut state = serializer.serialize_seq(Some(self.len()))?; |
1518 | | for item in self { |
1519 | | state.serialize_element(&item)?; |
1520 | | } |
1521 | | state.end() |
1522 | | } |
1523 | | } |
1524 | | |
1525 | | #[cfg(feature = "serde")] |
1526 | | impl<'de, A: Array> Deserialize<'de> for SmallVec<A> |
1527 | | where |
1528 | | A::Item: Deserialize<'de>, |
1529 | | { |
1530 | | fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { |
1531 | | deserializer.deserialize_seq(SmallVecVisitor { |
1532 | | phantom: PhantomData, |
1533 | | }) |
1534 | | } |
1535 | | } |
1536 | | |
1537 | | #[cfg(feature = "serde")] |
1538 | | struct SmallVecVisitor<A> { |
1539 | | phantom: PhantomData<A>, |
1540 | | } |
1541 | | |
1542 | | #[cfg(feature = "serde")] |
1543 | | impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A> |
1544 | | where |
1545 | | A::Item: Deserialize<'de>, |
1546 | | { |
1547 | | type Value = SmallVec<A>; |
1548 | | |
1549 | | fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
1550 | | formatter.write_str("a sequence") |
1551 | | } |
1552 | | |
1553 | | fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error> |
1554 | | where |
1555 | | B: SeqAccess<'de>, |
1556 | | { |
1557 | | use serde::de::Error; |
1558 | | let len = seq.size_hint().unwrap_or(0); |
1559 | | let mut values = SmallVec::new(); |
1560 | | values.try_reserve(len).map_err(B::Error::custom)?; |
1561 | | |
1562 | | while let Some(value) = seq.next_element()? { |
1563 | | values.push(value); |
1564 | | } |
1565 | | |
1566 | | Ok(values) |
1567 | | } |
1568 | | } |
1569 | | |
1570 | | #[cfg(feature = "specialization")] |
1571 | | trait SpecFrom<A: Array, S> { |
1572 | | fn spec_from(slice: S) -> SmallVec<A>; |
1573 | | } |
1574 | | |
1575 | | #[cfg(feature = "specialization")] |
1576 | | mod specialization; |
1577 | | |
1578 | | #[cfg(feature = "specialization")] |
1579 | | impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A> |
1580 | | where |
1581 | | A::Item: Copy, |
1582 | | { |
1583 | | #[inline] |
1584 | | fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> { |
1585 | | SmallVec::from_slice(slice) |
1586 | | } |
1587 | | } |
1588 | | |
1589 | | impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A> |
1590 | | where |
1591 | | A::Item: Clone, |
1592 | | { |
1593 | | #[cfg(not(feature = "specialization"))] |
1594 | | #[inline] |
1595 | 0 | fn from(slice: &'a [A::Item]) -> SmallVec<A> { |
1596 | 0 | slice.iter().cloned().collect() |
1597 | 0 | } |
1598 | | |
1599 | | #[cfg(feature = "specialization")] |
1600 | | #[inline] |
1601 | | fn from(slice: &'a [A::Item]) -> SmallVec<A> { |
1602 | | SmallVec::spec_from(slice) |
1603 | | } |
1604 | | } |
1605 | | |
1606 | | impl<A: Array> From<Vec<A::Item>> for SmallVec<A> { |
1607 | | #[inline] |
1608 | 0 | fn from(vec: Vec<A::Item>) -> SmallVec<A> { |
1609 | 0 | SmallVec::from_vec(vec) |
1610 | 0 | } |
1611 | | } |
1612 | | |
1613 | | impl<A: Array> From<A> for SmallVec<A> { |
1614 | | #[inline] |
1615 | 0 | fn from(array: A) -> SmallVec<A> { |
1616 | 0 | SmallVec::from_buf(array) |
1617 | 0 | } |
1618 | | } |
1619 | | |
1620 | | impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> { |
1621 | | type Output = I::Output; |
1622 | | |
1623 | 0 | fn index(&self, index: I) -> &I::Output { |
1624 | 0 | &(**self)[index] |
1625 | 0 | } |
1626 | | } |
1627 | | |
1628 | | impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> { |
1629 | 366k | fn index_mut(&mut self, index: I) -> &mut I::Output { |
1630 | 366k | &mut (&mut **self)[index] |
1631 | 366k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]> as core::ops::index::IndexMut<core::ops::range::RangeFull>>::index_mut Line | Count | Source | 1629 | 366k | fn index_mut(&mut self, index: I) -> &mut I::Output { | 1630 | 366k | &mut (&mut **self)[index] | 1631 | 366k | } |
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::index::IndexMut<_>>::index_mut |
1632 | | } |
1633 | | |
1634 | | #[allow(deprecated)] |
1635 | | impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A> |
1636 | | where |
1637 | | A::Item: Copy, |
1638 | | { |
1639 | 0 | fn extend_from_slice(&mut self, other: &[A::Item]) { |
1640 | 0 | SmallVec::extend_from_slice(self, other) |
1641 | 0 | } |
1642 | | } |
1643 | | |
1644 | | impl<A: Array> FromIterator<A::Item> for SmallVec<A> { |
1645 | | #[inline] |
1646 | 0 | fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> { |
1647 | 0 | let mut v = SmallVec::new(); |
1648 | 0 | v.extend(iterable); |
1649 | 0 | v |
1650 | 0 | } |
1651 | | } |
1652 | | |
1653 | | impl<A: Array> Extend<A::Item> for SmallVec<A> { |
1654 | 0 | fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) { |
1655 | 0 | let mut iter = iterable.into_iter(); |
1656 | 0 | let (lower_size_bound, _) = iter.size_hint(); |
1657 | 0 | self.reserve(lower_size_bound); |
1658 | | |
1659 | | unsafe { |
1660 | 0 | let (ptr, len_ptr, cap) = self.triple_mut(); |
1661 | 0 | let mut len = SetLenOnDrop::new(len_ptr); |
1662 | 0 | while len.get() < cap { |
1663 | 0 | if let Some(out) = iter.next() { |
1664 | 0 | ptr::write(ptr.add(len.get()), out); |
1665 | 0 | len.increment_len(1); |
1666 | 0 | } else { |
1667 | 0 | return; |
1668 | | } |
1669 | | } |
1670 | | } |
1671 | | |
1672 | 0 | for elem in iter { |
1673 | 0 | self.push(elem); |
1674 | 0 | } |
1675 | 0 | } |
1676 | | } |
1677 | | |
1678 | | impl<A: Array> fmt::Debug for SmallVec<A> |
1679 | | where |
1680 | | A::Item: fmt::Debug, |
1681 | | { |
1682 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1683 | 0 | f.debug_list().entries(self.iter()).finish() |
1684 | 0 | } |
1685 | | } |
1686 | | |
1687 | | impl<A: Array> Default for SmallVec<A> { |
1688 | | #[inline] |
1689 | 0 | fn default() -> SmallVec<A> { |
1690 | 0 | SmallVec::new() |
1691 | 0 | } |
1692 | | } |
1693 | | |
1694 | | #[cfg(feature = "may_dangle")] |
1695 | | unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> { |
1696 | | fn drop(&mut self) { |
1697 | | unsafe { |
1698 | | if self.spilled() { |
1699 | | let (ptr, len) = self.data.heap(); |
1700 | | Vec::from_raw_parts(ptr, len, self.capacity); |
1701 | | } else { |
1702 | | ptr::drop_in_place(&mut self[..]); |
1703 | | } |
1704 | | } |
1705 | | } |
1706 | | } |
1707 | | |
1708 | | #[cfg(not(feature = "may_dangle"))] |
1709 | | impl<A: Array> Drop for SmallVec<A> { |
1710 | 366k | fn drop(&mut self) { |
1711 | | unsafe { |
1712 | 366k | if self.spilled() { |
1713 | 290 | let (ptr, len) = self.data.heap(); |
1714 | 290 | Vec::from_raw_parts(ptr, len, self.capacity); |
1715 | 366k | } else { |
1716 | 366k | ptr::drop_in_place(&mut self[..]); |
1717 | 366k | } |
1718 | | } |
1719 | 366k | } <smallvec::SmallVec<[cssparser::parser::BlockType; 16]> as core::ops::drop::Drop>::drop Line | Count | Source | 1710 | 366k | fn drop(&mut self) { | 1711 | | unsafe { | 1712 | 366k | if self.spilled() { | 1713 | 290 | let (ptr, len) = self.data.heap(); | 1714 | 290 | Vec::from_raw_parts(ptr, len, self.capacity); | 1715 | 366k | } else { | 1716 | 366k | ptr::drop_in_place(&mut self[..]); | 1717 | 366k | } | 1718 | | } | 1719 | 366k | } |
Unexecuted instantiation: <smallvec::SmallVec<_> as core::ops::drop::Drop>::drop |
1720 | | } |
1721 | | |
1722 | | impl<A: Array> Clone for SmallVec<A> |
1723 | | where |
1724 | | A::Item: Clone, |
1725 | | { |
1726 | | #[inline] |
1727 | 0 | fn clone(&self) -> SmallVec<A> { |
1728 | 0 | SmallVec::from(self.as_slice()) |
1729 | 0 | } |
1730 | | } |
1731 | | |
1732 | | impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A> |
1733 | | where |
1734 | | A::Item: PartialEq<B::Item>, |
1735 | | { |
1736 | | #[inline] |
1737 | 0 | fn eq(&self, other: &SmallVec<B>) -> bool { |
1738 | 0 | self[..] == other[..] |
1739 | 0 | } |
1740 | | } |
1741 | | |
1742 | | impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {} |
1743 | | |
1744 | | impl<A: Array> PartialOrd for SmallVec<A> |
1745 | | where |
1746 | | A::Item: PartialOrd, |
1747 | | { |
1748 | | #[inline] |
1749 | 0 | fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> { |
1750 | 0 | PartialOrd::partial_cmp(&**self, &**other) |
1751 | 0 | } |
1752 | | } |
1753 | | |
1754 | | impl<A: Array> Ord for SmallVec<A> |
1755 | | where |
1756 | | A::Item: Ord, |
1757 | | { |
1758 | | #[inline] |
1759 | 0 | fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering { |
1760 | 0 | Ord::cmp(&**self, &**other) |
1761 | 0 | } |
1762 | | } |
1763 | | |
1764 | | impl<A: Array> Hash for SmallVec<A> |
1765 | | where |
1766 | | A::Item: Hash, |
1767 | | { |
1768 | 0 | fn hash<H: Hasher>(&self, state: &mut H) { |
1769 | 0 | (**self).hash(state) |
1770 | 0 | } |
1771 | | } |
1772 | | |
1773 | | unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {} |
1774 | | |
1775 | | /// An iterator that consumes a `SmallVec` and yields its items by value. |
1776 | | /// |
1777 | | /// Returned from [`SmallVec::into_iter`][1]. |
1778 | | /// |
1779 | | /// [1]: struct.SmallVec.html#method.into_iter |
1780 | | pub struct IntoIter<A: Array> { |
1781 | | data: SmallVec<A>, |
1782 | | current: usize, |
1783 | | end: usize, |
1784 | | } |
1785 | | |
1786 | | impl<A: Array> fmt::Debug for IntoIter<A> |
1787 | | where |
1788 | | A::Item: fmt::Debug, |
1789 | | { |
1790 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
1791 | 0 | f.debug_tuple("IntoIter").field(&self.as_slice()).finish() |
1792 | 0 | } |
1793 | | } |
1794 | | |
1795 | | impl<A: Array + Clone> Clone for IntoIter<A> |
1796 | | where |
1797 | | A::Item: Clone, |
1798 | | { |
1799 | 0 | fn clone(&self) -> IntoIter<A> { |
1800 | 0 | SmallVec::from(self.as_slice()).into_iter() |
1801 | 0 | } |
1802 | | } |
1803 | | |
1804 | | impl<A: Array> Drop for IntoIter<A> { |
1805 | 0 | fn drop(&mut self) { |
1806 | 0 | for _ in self {} |
1807 | 0 | } |
1808 | | } |
1809 | | |
1810 | | impl<A: Array> Iterator for IntoIter<A> { |
1811 | | type Item = A::Item; |
1812 | | |
1813 | | #[inline] |
1814 | 0 | fn next(&mut self) -> Option<A::Item> { |
1815 | 0 | if self.current == self.end { |
1816 | 0 | None |
1817 | | } else { |
1818 | | unsafe { |
1819 | 0 | let current = self.current; |
1820 | 0 | self.current += 1; |
1821 | 0 | Some(ptr::read(self.data.as_ptr().add(current))) |
1822 | | } |
1823 | | } |
1824 | 0 | } |
1825 | | |
1826 | | #[inline] |
1827 | 0 | fn size_hint(&self) -> (usize, Option<usize>) { |
1828 | 0 | let size = self.end - self.current; |
1829 | 0 | (size, Some(size)) |
1830 | 0 | } |
1831 | | } |
1832 | | |
1833 | | impl<A: Array> DoubleEndedIterator for IntoIter<A> { |
1834 | | #[inline] |
1835 | 0 | fn next_back(&mut self) -> Option<A::Item> { |
1836 | 0 | if self.current == self.end { |
1837 | 0 | None |
1838 | | } else { |
1839 | | unsafe { |
1840 | 0 | self.end -= 1; |
1841 | 0 | Some(ptr::read(self.data.as_ptr().add(self.end))) |
1842 | | } |
1843 | | } |
1844 | 0 | } |
1845 | | } |
1846 | | |
1847 | | impl<A: Array> ExactSizeIterator for IntoIter<A> {} |
1848 | | impl<A: Array> FusedIterator for IntoIter<A> {} |
1849 | | |
1850 | | impl<A: Array> IntoIter<A> { |
1851 | | /// Returns the remaining items of this iterator as a slice. |
1852 | 0 | pub fn as_slice(&self) -> &[A::Item] { |
1853 | 0 | let len = self.end - self.current; |
1854 | 0 | unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) } |
1855 | 0 | } |
1856 | | |
1857 | | /// Returns the remaining items of this iterator as a mutable slice. |
1858 | 0 | pub fn as_mut_slice(&mut self) -> &mut [A::Item] { |
1859 | 0 | let len = self.end - self.current; |
1860 | 0 | unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) } |
1861 | 0 | } |
1862 | | } |
1863 | | |
1864 | | impl<A: Array> IntoIterator for SmallVec<A> { |
1865 | | type IntoIter = IntoIter<A>; |
1866 | | type Item = A::Item; |
1867 | 0 | fn into_iter(mut self) -> Self::IntoIter { |
1868 | | unsafe { |
1869 | | // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements |
1870 | 0 | let len = self.len(); |
1871 | 0 | self.set_len(0); |
1872 | 0 | IntoIter { |
1873 | 0 | data: self, |
1874 | 0 | current: 0, |
1875 | 0 | end: len, |
1876 | 0 | } |
1877 | | } |
1878 | 0 | } |
1879 | | } |
1880 | | |
1881 | | impl<'a, A: Array> IntoIterator for &'a SmallVec<A> { |
1882 | | type IntoIter = slice::Iter<'a, A::Item>; |
1883 | | type Item = &'a A::Item; |
1884 | 0 | fn into_iter(self) -> Self::IntoIter { |
1885 | 0 | self.iter() |
1886 | 0 | } |
1887 | | } |
1888 | | |
1889 | | impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> { |
1890 | | type IntoIter = slice::IterMut<'a, A::Item>; |
1891 | | type Item = &'a mut A::Item; |
1892 | 0 | fn into_iter(self) -> Self::IntoIter { |
1893 | 0 | self.iter_mut() |
1894 | 0 | } |
1895 | | } |
1896 | | |
1897 | | /// Types that can be used as the backing store for a SmallVec |
1898 | | pub unsafe trait Array { |
1899 | | /// The type of the array's elements. |
1900 | | type Item; |
1901 | | /// Returns the number of items the array can hold. |
1902 | | fn size() -> usize; |
1903 | | } |
1904 | | |
1905 | | /// Set the length of the vec when the `SetLenOnDrop` value goes out of scope. |
1906 | | /// |
1907 | | /// Copied from https://github.com/rust-lang/rust/pull/36355 |
1908 | | struct SetLenOnDrop<'a> { |
1909 | | len: &'a mut usize, |
1910 | | local_len: usize, |
1911 | | } |
1912 | | |
1913 | | impl<'a> SetLenOnDrop<'a> { |
1914 | | #[inline] |
1915 | 0 | fn new(len: &'a mut usize) -> Self { |
1916 | 0 | SetLenOnDrop { |
1917 | 0 | local_len: *len, |
1918 | 0 | len, |
1919 | 0 | } |
1920 | 0 | } |
1921 | | |
1922 | | #[inline] |
1923 | 0 | fn get(&self) -> usize { |
1924 | 0 | self.local_len |
1925 | 0 | } |
1926 | | |
1927 | | #[inline] |
1928 | 0 | fn increment_len(&mut self, increment: usize) { |
1929 | 0 | self.local_len += increment; |
1930 | 0 | } |
1931 | | } |
1932 | | |
1933 | | impl<'a> Drop for SetLenOnDrop<'a> { |
1934 | | #[inline] |
1935 | 0 | fn drop(&mut self) { |
1936 | 0 | *self.len = self.local_len; |
1937 | 0 | } |
1938 | | } |
1939 | | |
1940 | | #[cfg(feature = "const_generics")] |
1941 | | unsafe impl<T, const N: usize> Array for [T; N] { |
1942 | | type Item = T; |
1943 | | fn size() -> usize { |
1944 | | N |
1945 | | } |
1946 | | } |
1947 | | |
1948 | | #[cfg(not(feature = "const_generics"))] |
1949 | | macro_rules! impl_array( |
1950 | | ($($size:expr),+) => { |
1951 | | $( |
1952 | | unsafe impl<T> Array for [T; $size] { |
1953 | | type Item = T; |
1954 | 5.68M | fn size() -> usize { $size }<[cssparser::parser::BlockType; 16] as smallvec::Array>::size Line | Count | Source | 1954 | 5.68M | fn size() -> usize { $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: <[_; 15] as smallvec::Array>::size Unexecuted instantiation: <[_; 16] as smallvec::Array>::size Unexecuted instantiation: <[_; 17] 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: <[_; 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: <[_; 2048] as smallvec::Array>::size Unexecuted instantiation: <[_; 4096] as smallvec::Array>::size Unexecuted instantiation: <[_; 8192] 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 Unexecuted instantiation: <[_; 5] as smallvec::Array>::size Unexecuted instantiation: <[_; 6] as smallvec::Array>::size Unexecuted instantiation: <[_; 7] as smallvec::Array>::size |
1955 | | } |
1956 | | )+ |
1957 | | } |
1958 | | ); |
1959 | | |
1960 | | #[cfg(not(feature = "const_generics"))] |
1961 | | impl_array!( |
1962 | | 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, |
1963 | | 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000, |
1964 | | 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000 |
1965 | | ); |
1966 | | |
1967 | | /// Convenience trait for constructing a `SmallVec` |
1968 | | pub trait ToSmallVec<A: Array> { |
1969 | | /// Construct a new `SmallVec` from a slice. |
1970 | | fn to_smallvec(&self) -> SmallVec<A>; |
1971 | | } |
1972 | | |
1973 | | impl<A: Array> ToSmallVec<A> for [A::Item] |
1974 | | where |
1975 | | A::Item: Copy, |
1976 | | { |
1977 | | #[inline] |
1978 | 0 | fn to_smallvec(&self) -> SmallVec<A> { |
1979 | 0 | SmallVec::from_slice(self) |
1980 | 0 | } |
1981 | | } |