| 1 |
#![deny(missing_docs)] |
| 2 |
|
| 3 |
//! `ThinVec` is exactly the same as `Vec`, except that it stores its `len` and `capacity` in the buffer |
| 4 |
//! it allocates. |
| 5 |
//! |
| 6 |
//! This makes the memory footprint of ThinVecs lower; notably in cases where space is reserved for |
| 7 |
//! a non-existence `ThinVec<T>`. So `Vec<ThinVec<T>>` and `Option<ThinVec<T>>::None` will waste less |
| 8 |
//! space. Being pointer-sized also means it can be passed/stored in registers. |
| 9 |
//! |
| 10 |
//! Of course, any actually constructed `ThinVec` will theoretically have a bigger allocation, but |
| 11 |
//! the fuzzy nature of allocators means that might not actually be the case. |
| 12 |
//! |
| 13 |
//! Properties of `Vec` that are preserved: |
| 14 |
//! * `ThinVec::new()` doesn't allocate (it points to a statically allocated singleton) |
| 15 |
//! * reallocation can be done in place |
| 16 |
//! * `size_of::<ThinVec<T>>()` == `size_of::<Option<ThinVec<T>>>()` |
| 17 |
//! |
| 18 |
//! Properties of `Vec` that aren't preserved: |
| 19 |
//! * `ThinVec<T>` can't ever be zero-cost roundtripped to a `Box<[T]>`, `String`, or `*mut T` |
| 20 |
//! * `from_raw_parts` doesn't exist |
| 21 |
//! * `ThinVec` currently doesn't bother to not-allocate for Zero Sized Types (e.g. `ThinVec<()>`), |
| 22 |
//! but it could be done if someone cared enough to implement it. |
| 23 |
//! |
| 24 |
//! |
| 25 |
//! |
| 26 |
//! # Gecko FFI |
| 27 |
//! |
| 28 |
//! If you enable the gecko-ffi feature, `ThinVec` will verbatim bridge with the nsTArray type in |
| 29 |
//! Gecko (Firefox). That is, `ThinVec` and nsTArray have identical layouts *but not ABIs*, |
| 30 |
//! so nsTArrays/ThinVecs an be natively manipulated by C++ and Rust, and ownership can be |
| 31 |
//! transferred across the FFI boundary (**IF YOU ARE CAREFUL, SEE BELOW!!**). |
| 32 |
//! |
| 33 |
//! While this feature is handy, it is also inherently dangerous to use because Rust and C++ do not |
| 34 |
//! know about each other. Specifically, this can be an issue with non-POD types (types which |
| 35 |
//! have destructors, move constructors, or are `!Copy`). |
| 36 |
//! |
| 37 |
//! ## Do Not Pass By Value |
| 38 |
//! |
| 39 |
//! The biggest thing to keep in mind is that **FFI functions cannot pass ThinVec/nsTArray |
| 40 |
//! by-value**. That is, these are busted APIs: |
| 41 |
//! |
| 42 |
//! ```rust,ignore |
| 43 |
//! // BAD WRONG |
| 44 |
//! extern fn process_data(data: ThinVec<u32>) { ... } |
| 45 |
//! // BAD WRONG |
| 46 |
//! extern fn get_data() -> ThinVec<u32> { ... } |
| 47 |
//! ``` |
| 48 |
//! |
| 49 |
//! You must instead pass by-reference: |
| 50 |
//! |
| 51 |
//! ```rust |
| 52 |
//! # use thin_vec::*; |
| 53 |
//! # use std::mem; |
| 54 |
//! |
| 55 |
//! // Read-only access, ok! |
| 56 |
//! extern fn process_data(data: &ThinVec<u32>) { |
| 57 |
//! for val in data { |
| 58 |
//! println!("{}", val); |
| 59 |
//! } |
| 60 |
//! } |
| 61 |
//! |
| 62 |
//! // Replace with empty instance to take ownership, ok! |
| 63 |
//! extern fn consume_data(data: &mut ThinVec<u32>) { |
| 64 |
//! let owned = mem::replace(data, ThinVec::new()); |
| 65 |
//! mem::drop(owned); |
| 66 |
//! } |
| 67 |
//! |
| 68 |
//! // Mutate input, ok! |
| 69 |
//! extern fn add_data(dataset: &mut ThinVec<u32>) { |
| 70 |
//! dataset.push(37); |
| 71 |
//! dataset.push(12); |
| 72 |
//! } |
| 73 |
//! |
| 74 |
//! // Return via out-param, usually ok! |
| 75 |
//! // |
| 76 |
//! // WARNING: output must be initialized! (Empty nsTArrays are free, so just do it!) |
| 77 |
//! extern fn get_data(output: &mut ThinVec<u32>) { |
| 78 |
//! *output = thin_vec![1, 2, 3, 4, 5]; |
| 79 |
//! } |
| 80 |
//! ``` |
| 81 |
//! |
| 82 |
//! Ignorable Explanation For Those Who Really Want To Know Why: |
| 83 |
//! |
| 84 |
//! > The fundamental issue is that Rust and C++ can't currently communicate about destructors, and |
| 85 |
//! > the semantics of C++ require destructors of function arguments to be run when the function |
| 86 |
//! > returns. Whether the callee or caller is responsible for this is also platform-specific, so |
| 87 |
//! > trying to hack around it manually would be messy. |
| 88 |
//! > |
| 89 |
//! > Also a type having a destructor changes its C++ ABI, because that type must actually exist |
| 90 |
//! > in memory (unlike a trivial struct, which is often passed in registers). We don't currently |
| 91 |
//! > have a way to communicate to Rust that this is happening, so even if we worked out the |
| 92 |
//! > destructor issue with say, MaybeUninit, it would still be a non-starter without some RFCs |
| 93 |
//! > to add explicit rustc support. |
| 94 |
//! > |
| 95 |
//! > Realistically, the best answer here is to have a "heavier" bindgen that can secretly |
| 96 |
//! > generate FFI glue so we can pass things "by value" and have it generate by-reference code |
| 97 |
//! > behind our back (like the cxx crate does). This would muddy up debugging/searchfox though. |
| 98 |
//! |
| 99 |
//! ## Types Should Be Trivially Relocatable |
| 100 |
//! |
| 101 |
//! Types in Rust are always trivially relocatable (unless suitably borrowed/[pinned][]/hidden). |
| 102 |
//! This means all Rust types are legal to relocate with a bitwise copy, you cannot provide |
| 103 |
//! copy or move constructors to execute when this happens, and the old location won't have its |
| 104 |
//! destructor run. This will cause problems for types which have a significant location |
| 105 |
//! (types that intrusively point into themselves or have their location registered with a service). |
| 106 |
//! |
| 107 |
//! While relocations are generally predictable if you're very careful, **you should avoid using |
| 108 |
//! types with significant locations with Rust FFI**. |
| 109 |
//! |
| 110 |
//! Specifically, `ThinVec` will trivially relocate its contents whenever it needs to reallocate its |
| 111 |
//! buffer to change its capacity. This is the default reallocation strategy for nsTArray, and is |
| 112 |
//! suitable for the vast majority of types. Just be aware of this limitation! |
| 113 |
//! |
| 114 |
//! ## Auto Arrays Are Dangerous |
| 115 |
//! |
| 116 |
//! `ThinVec` has *some* support for handling auto arrays which store their buffer on the stack, |
| 117 |
//! but this isn't well tested. |
| 118 |
//! |
| 119 |
//! Regardless of how much support we provide, Rust won't be aware of the buffer's limited lifetime, |
| 120 |
//! so standard auto array safety caveats apply about returning/storing them! `ThinVec` won't ever |
| 121 |
//! produce an auto array on its own, so this is only an issue for transferring an nsTArray into |
| 122 |
//! Rust. |
| 123 |
//! |
| 124 |
//! ## Other Issues |
| 125 |
//! |
| 126 |
//! Standard FFI caveats also apply: |
| 127 |
//! |
| 128 |
//! * Rust is more strict about POD types being initialized (use MaybeUninit if you must) |
| 129 |
//! * `ThinVec<T>` has no idea if the C++ version of `T` has move/copy/assign/delete overloads |
| 130 |
//! * `nsTArray<T>` has no idea if the Rust version of `T` has a Drop/Clone impl |
| 131 |
//! * C++ can do all sorts of unsound things that Rust can't catch |
| 132 |
//! * C++ and Rust don't agree on how zero-sized/empty types should be handled |
| 133 |
//! |
| 134 |
//! The gecko-ffi feature will not work if you aren't linking with code that has nsTArray |
| 135 |
//! defined. Specifically, we must share the symbol for nsTArray's empty singleton. You will get |
| 136 |
//! linking errors if that isn't defined. |
| 137 |
//! |
| 138 |
//! The gecko-ffi feature also limits `ThinVec` to the legacy behaviors of nsTArray. Most notably, |
| 139 |
//! nsTArray has a maximum capacity of i32::MAX (~2.1 billion items). Probably not an issue. |
| 140 |
//! Probably. |
| 141 |
//! |
| 142 |
//! [pinned]: https://doc.rust-lang.org/std/pin/index.html |
| 143 |
|
| 144 |
#![allow(clippy::comparison_chain, clippy::missing_safety_doc)] |
| 145 |
|
| 146 |
use std::alloc::*; |
| 147 |
use std::borrow::*; |
| 148 |
use std::cmp::*; |
| 149 |
use std::convert::TryFrom; |
| 150 |
use std::convert::TryInto; |
| 151 |
use std::hash::*; |
| 152 |
use std::iter::FromIterator; |
| 153 |
use std::marker::PhantomData; |
| 154 |
use std::ops::Bound; |
| 155 |
use std::ops::{Deref, DerefMut, RangeBounds}; |
| 156 |
use std::ptr::NonNull; |
| 157 |
use std::slice::IterMut; |
| 158 |
use std::{fmt, io, mem, ptr, slice}; |
| 159 |
|
| 160 |
use impl_details::*; |
| 161 |
|
| 162 |
// modules: a simple way to cfg a whole bunch of impl details at once |
| 163 |
|
| 164 |
#[cfg(not(feature = "gecko-ffi"))] |
| 165 |
mod impl_details { |
| 166 |
pub type SizeType = usize; |
| 167 |
pub const MAX_CAP: usize = !0; |
| 168 |
|
| 169 |
#[inline(always)] |
| 170 |
pub fn assert_size(x: usize) -> SizeType { |
| 171 |
x |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
#[cfg(feature = "gecko-ffi")] |
| 176 |
mod impl_details { |
| 177 |
// Support for briding a gecko nsTArray verbatim into a ThinVec. |
| 178 |
// |
| 179 |
// `ThinVec` can't see copy/move/delete implementations |
| 180 |
// from C++ |
| 181 |
// |
| 182 |
// The actual layout of an nsTArray is: |
| 183 |
// |
| 184 |
// ```cpp |
| 185 |
// struct { |
| 186 |
// uint32_t mLength; |
| 187 |
// uint32_t mCapacity: 31; |
| 188 |
// uint32_t mIsAutoArray: 1; |
| 189 |
// } |
| 190 |
// ``` |
| 191 |
// |
| 192 |
// Rust doesn't natively support bit-fields, so we manually mask |
| 193 |
// and shift the bit. When the "auto" bit is set, the header and buffer |
| 194 |
// are actually on the stack, meaning the `ThinVec` pointer-to-header |
| 195 |
// is essentially an "owned borrow", and therefore dangerous to handle. |
| 196 |
// There are no safety guards for this situation. |
| 197 |
// |
| 198 |
// On little-endian platforms, the auto bit will be the high-bit of |
| 199 |
// our capacity u32. On big-endian platforms, it will be the low bit. |
| 200 |
// Hence we need some platform-specific CFGs for the necessary masking/shifting. |
| 201 |
// |
| 202 |
// `ThinVec` won't ever construct an auto array. They only happen when |
| 203 |
// bridging from C++. This means we don't need to ever set/preserve the bit. |
| 204 |
// We just need to be able to read and handle it if it happens to be there. |
| 205 |
// |
| 206 |
// Handling the auto bit mostly just means not freeing/reallocating the buffer. |
| 207 |
|
| 208 |
pub type SizeType = u32; |
| 209 |
|
| 210 |
pub const MAX_CAP: usize = i32::max_value() as usize; |
| 211 |
|
| 212 |
// Little endian: the auto bit is the high bit, and the capacity is |
| 213 |
// verbatim. So we just need to mask off the high bit. Note that |
| 214 |
// this masking is unnecessary when packing, because assert_size |
| 215 |
// guards against the high bit being set. |
| 216 |
#[cfg(target_endian = "little")] |
| 217 |
pub fn pack_capacity(cap: SizeType) -> SizeType { |
| 218 |
cap as SizeType |
| 219 |
} |
| 220 |
#[cfg(target_endian = "little")] |
| 221 |
pub fn unpack_capacity(cap: SizeType) -> usize { |
| 222 |
(cap as usize) & !(1 << 31) |
| 223 |
} |
| 224 |
#[cfg(target_endian = "little")] |
| 225 |
pub fn is_auto(cap: SizeType) -> bool { |
| 226 |
(cap & (1 << 31)) != 0 |
| 227 |
} |
| 228 |
|
| 229 |
// Big endian: the auto bit is the low bit, and the capacity is |
| 230 |
// shifted up one bit. Masking out the auto bit is unnecessary, |
| 231 |
// as rust shifts always shift in 0's for unsigned integers. |
| 232 |
#[cfg(target_endian = "big")] |
| 233 |
pub fn pack_capacity(cap: SizeType) -> SizeType { |
| 234 |
(cap as SizeType) << 1 |
| 235 |
} |
| 236 |
#[cfg(target_endian = "big")] |
| 237 |
pub fn unpack_capacity(cap: SizeType) -> usize { |
| 238 |
(cap >> 1) as usize |
| 239 |
} |
| 240 |
#[cfg(target_endian = "big")] |
| 241 |
pub fn is_auto(cap: SizeType) -> bool { |
| 242 |
(cap & 1) != 0 |
| 243 |
} |
| 244 |
|
| 245 |
#[inline] |
| 246 |
pub fn assert_size(x: usize) -> SizeType { |
| 247 |
if x > MAX_CAP as usize { |
| 248 |
panic!("nsTArray size may not exceed the capacity of a 32-bit sized int"); |
| 249 |
} |
| 250 |
x as SizeType |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
// The header of a ThinVec. |
| 255 |
// |
| 256 |
// The _cap can be a bitfield, so use accessors to avoid trouble. |
| 257 |
// |
| 258 |
// In "real" gecko-ffi mode, the empty singleton will be aligned |
| 259 |
// to 8 by gecko. But in tests we have to provide the singleton |
| 260 |
// ourselves, and Rust makes it hard to "just" align a static. |
| 261 |
// To avoid messing around with a wrapper type around the |
| 262 |
// singleton *just* for tests, we just force all headers to be |
| 263 |
// aligned to 8 in this weird "zombie" gecko mode. |
| 264 |
// |
| 265 |
// This shouldn't affect runtime layout (padding), but it will |
| 266 |
// result in us asking the allocator to needlessly overalign |
| 267 |
// non-empty ThinVecs containing align < 8 types in |
| 268 |
// zombie-mode, but not in "real" geck-ffi mode. Minor. |
| 269 |
#[cfg_attr(all(feature = "gecko-ffi", any(test, miri)), repr(align(8)))] |
| 270 |
#[repr(C)] |
| 271 |
struct Header { |
| 272 |
_len: SizeType, |
| 273 |
_cap: SizeType, |
| 274 |
} |
| 275 |
|
| 276 |
impl Header { |
| 277 |
#[inline] |
| 278 |
#[allow(clippy::unnecessary_cast)] |
| 279 |
fn len(&self) -> usize { |
| 280 |
self._len as usize |
| 281 |
} |
| 282 |
|
| 283 |
#[inline] |
| 284 |
fn set_len(&mut self, len: usize) { |
| 285 |
self._len = assert_size(len); |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
#[cfg(feature = "gecko-ffi")] |
| 290 |
impl Header { |
| 291 |
fn cap(&self) -> usize { |
| 292 |
unpack_capacity(self._cap) |
| 293 |
} |
| 294 |
|
| 295 |
fn set_cap(&mut self, cap: usize) { |
| 296 |
// debug check that our packing is working |
| 297 |
debug_assert_eq!(unpack_capacity(pack_capacity(cap as SizeType)), cap); |
| 298 |
// FIXME: this assert is busted because it reads uninit memory |
| 299 |
// debug_assert!(!self.uses_stack_allocated_buffer()); |
| 300 |
|
| 301 |
// NOTE: this always stores a cleared auto bit, because set_cap |
| 302 |
// is only invoked by Rust, and Rust doesn't create auto arrays. |
| 303 |
self._cap = pack_capacity(assert_size(cap)); |
| 304 |
} |
| 305 |
|
| 306 |
fn uses_stack_allocated_buffer(&self) -> bool { |
| 307 |
is_auto(self._cap) |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
#[cfg(not(feature = "gecko-ffi"))] |
| 312 |
impl Header { |
| 313 |
#[allow(clippy::unnecessary_cast)] |
| 314 |
fn cap(&self) -> usize { |
| 315 |
self._cap as usize |
| 316 |
} |
| 317 |
|
| 318 |
fn set_cap(&mut self, cap: usize) { |
| 319 |
self._cap = assert_size(cap); |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
/// Singleton that all empty collections share. |
| 324 |
/// Note: can't store non-zero ZSTs, we allocate in that case. We could |
| 325 |
/// optimize everything to not do that (basically, make ptr == len and branch |
| 326 |
/// on size == 0 in every method), but it's a bunch of work for something that |
| 327 |
/// doesn't matter much. |
| 328 |
#[cfg(any(not(feature = "gecko-ffi"), test, miri))] |
| 329 |
static EMPTY_HEADER: Header = Header { _len: 0, _cap: 0 }; |
| 330 |
|
| 331 |
#[cfg(all(feature = "gecko-ffi", not(test), not(miri)))] |
| 332 |
extern "C" { |
| 333 |
#[link_name = "sEmptyTArrayHeader"] |
| 334 |
static EMPTY_HEADER: Header; |
| 335 |
} |
| 336 |
|
| 337 |
// Utils for computing layouts of allocations |
| 338 |
|
| 339 |
/// Gets the size necessary to allocate a `ThinVec<T>` with the give capacity. |
| 340 |
/// |
| 341 |
/// # Panics |
| 342 |
/// |
| 343 |
/// This will panic if isize::MAX is overflowed at any point. |
| 344 |
fn alloc_size<T>(cap: usize) -> usize { |
| 345 |
// Compute "real" header size with pointer math |
| 346 |
// |
| 347 |
// We turn everything into isizes here so that we can catch isize::MAX overflow, |
| 348 |
// we never want to allow allocations larger than that! |
| 349 |
let header_size = mem::size_of::<Header>() as isize; |
| 350 |
let padding = padding::<T>() as isize; |
| 351 |
|
| 352 |
let data_size = if mem::size_of::<T>() == 0 { |
| 353 |
// If we're allocating an array for ZSTs we need a header/padding but no actual |
| 354 |
// space for items, so we don't care about the capacity that was requested! |
| 355 |
0 |
| 356 |
} else { |
| 357 |
let cap: isize = cap.try_into().expect("capacity overflow"); |
| 358 |
let elem_size = mem::size_of::<T>() as isize; |
| 359 |
elem_size.checked_mul(cap).expect("capacity overflow") |
| 360 |
}; |
| 361 |
|
| 362 |
let final_size = data_size |
| 363 |
.checked_add(header_size + padding) |
| 364 |
.expect("capacity overflow"); |
| 365 |
|
| 366 |
// Ok now we can turn it back into a usize (don't need to worry about negatives) |
| 367 |
final_size as usize |
| 368 |
} |
| 369 |
|
| 370 |
/// Gets the padding necessary for the array of a `ThinVec<T>` |
| 371 |
fn padding<T>() -> usize { |
| 372 |
let alloc_align = alloc_align::<T>(); |
| 373 |
let header_size = mem::size_of::<Header>(); |
| 374 |
|
| 375 |
if alloc_align > header_size { |
| 376 |
if cfg!(feature = "gecko-ffi") { |
| 377 |
panic!( |
| 378 |
"nsTArray does not handle alignment above > {} correctly", |
| 379 |
header_size |
| 380 |
); |
| 381 |
} |
| 382 |
alloc_align - header_size |
| 383 |
} else { |
| 384 |
0 |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
/// Gets the align necessary to allocate a `ThinVec<T>` |
| 389 |
fn alloc_align<T>() -> usize { |
| 390 |
max(mem::align_of::<T>(), mem::align_of::<Header>()) |
| 391 |
} |
| 392 |
|
| 393 |
/// Gets the layout necessary to allocate a `ThinVec<T>` |
| 394 |
/// |
| 395 |
/// # Panics |
| 396 |
/// |
| 397 |
/// Panics if the required size overflows `isize::MAX`. |
| 398 |
fn layout<T>(cap: usize) -> Layout { |
| 399 |
unsafe { Layout::from_size_align_unchecked(alloc_size::<T>(cap), alloc_align::<T>()) } |
| 400 |
} |
| 401 |
|
| 402 |
/// Allocates a header (and array) for a `ThinVec<T>` with the given capacity. |
| 403 |
/// |
| 404 |
/// # Panics |
| 405 |
/// |
| 406 |
/// Panics if the required size overflows `isize::MAX`. |
| 407 |
fn header_with_capacity<T>(cap: usize) -> NonNull<Header> { |
| 408 |
debug_assert!(cap > 0); |
| 409 |
unsafe { |
| 410 |
let layout = layout::<T>(cap); |
| 411 |
let header = alloc(layout) as *mut Header; |
| 412 |
|
| 413 |
if header.is_null() { |
| 414 |
handle_alloc_error(layout) |
| 415 |
} |
| 416 |
|
| 417 |
// "Infinite" capacity for zero-sized types: |
| 418 |
(*header).set_cap(if mem::size_of::<T>() == 0 { |
| 419 |
MAX_CAP |
| 420 |
} else { |
| 421 |
cap |
| 422 |
}); |
| 423 |
(*header).set_len(0); |
| 424 |
|
| 425 |
NonNull::new_unchecked(header) |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
/// See the crate's top level documentation for a description of this type. |
| 430 |
#[repr(C)] |
| 431 |
pub struct ThinVec<T> { |
| 432 |
ptr: NonNull<Header>, |
| 433 |
boo: PhantomData<T>, |
| 434 |
} |
| 435 |
|
| 436 |
unsafe impl<T: Sync> Sync for ThinVec<T> {} |
| 437 |
unsafe impl<T: Send> Send for ThinVec<T> {} |
| 438 |
|
| 439 |
/// Creates a `ThinVec` containing the arguments. |
| 440 |
/// |
| 441 |
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`. |
| 442 |
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")] |
| 443 |
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")] |
| 444 |
/// #[macro_use] extern crate thin_vec; |
| 445 |
/// |
| 446 |
/// fn main() { |
| 447 |
/// let v = thin_vec![1, 2, 3]; |
| 448 |
/// assert_eq!(v.len(), 3); |
| 449 |
/// assert_eq!(v[0], 1); |
| 450 |
/// assert_eq!(v[1], 2); |
| 451 |
/// assert_eq!(v[2], 3); |
| 452 |
/// |
| 453 |
/// let v = thin_vec![1; 3]; |
| 454 |
/// assert_eq!(v, [1, 1, 1]); |
| 455 |
/// } |
| 456 |
/// ``` |
| 457 |
#[macro_export] |
| 458 |
macro_rules! thin_vec { |
| 459 |
(@UNIT $($t:tt)*) => (()); |
| 460 |
|
| 461 |
($elem:expr; $n:expr) => ({ |
| 462 |
let mut vec = $crate::ThinVec::new(); |
| 463 |
vec.resize($n, $elem); |
| 464 |
vec |
| 465 |
}); |
| 466 |
() => {$crate::ThinVec::new()}; |
| 467 |
($($x:expr),*) => ({ |
| 468 |
let len = [$(thin_vec!(@UNIT $x)),*].len(); |
| 469 |
let mut vec = $crate::ThinVec::with_capacity(len); |
| 470 |
$(vec.push($x);)* |
| 471 |
vec |
| 472 |
}); |
| 473 |
($($x:expr,)*) => (thin_vec![$($x),*]); |
| 474 |
} |
| 475 |
|
| 476 |
impl<T> ThinVec<T> { |
| 477 |
/// Creates a new empty ThinVec. |
| 478 |
/// |
| 479 |
/// This will not allocate. |
| 480 |
pub fn new() -> ThinVec<T> { |
| 481 |
ThinVec::with_capacity(0) |
| 482 |
} |
| 483 |
|
| 484 |
/// Constructs a new, empty `ThinVec<T>` with at least the specified capacity. |
| 485 |
/// |
| 486 |
/// The vector will be able to hold at least `capacity` elements without |
| 487 |
/// reallocating. This method is allowed to allocate for more elements than |
| 488 |
/// `capacity`. If `capacity` is 0, the vector will not allocate. |
| 489 |
/// |
| 490 |
/// It is important to note that although the returned vector has the |
| 491 |
/// minimum *capacity* specified, the vector will have a zero *length*. |
| 492 |
/// |
| 493 |
/// If it is important to know the exact allocated capacity of a `ThinVec`, |
| 494 |
/// always use the [`capacity`] method after construction. |
| 495 |
/// |
| 496 |
/// **NOTE**: unlike `Vec`, `ThinVec` **MUST** allocate once to keep track of non-zero |
| 497 |
/// lengths. As such, we cannot provide the same guarantees about ThinVecs |
| 498 |
/// of ZSTs not allocating. However the allocation never needs to be resized |
| 499 |
/// to add more ZSTs, since the underlying array is still length 0. |
| 500 |
/// |
| 501 |
/// [Capacity and reallocation]: #capacity-and-reallocation |
| 502 |
/// [`capacity`]: Vec::capacity |
| 503 |
/// |
| 504 |
/// # Panics |
| 505 |
/// |
| 506 |
/// Panics if the new capacity exceeds `isize::MAX` bytes. |
| 507 |
/// |
| 508 |
/// # Examples |
| 509 |
/// |
| 510 |
/// ``` |
| 511 |
/// use thin_vec::ThinVec; |
| 512 |
/// |
| 513 |
/// let mut vec = ThinVec::with_capacity(10); |
| 514 |
/// |
| 515 |
/// // The vector contains no items, even though it has capacity for more |
| 516 |
/// assert_eq!(vec.len(), 0); |
| 517 |
/// assert!(vec.capacity() >= 10); |
| 518 |
/// |
| 519 |
/// // These are all done without reallocating... |
| 520 |
/// for i in 0..10 { |
| 521 |
/// vec.push(i); |
| 522 |
/// } |
| 523 |
/// assert_eq!(vec.len(), 10); |
| 524 |
/// assert!(vec.capacity() >= 10); |
| 525 |
/// |
| 526 |
/// // ...but this may make the vector reallocate |
| 527 |
/// vec.push(11); |
| 528 |
/// assert_eq!(vec.len(), 11); |
| 529 |
/// assert!(vec.capacity() >= 11); |
| 530 |
/// |
| 531 |
/// // A vector of a zero-sized type will always over-allocate, since no |
| 532 |
/// // space is needed to store the actual elements. |
| 533 |
/// let vec_units = ThinVec::<()>::with_capacity(10); |
| 534 |
/// |
| 535 |
/// // Only true **without** the gecko-ffi feature! |
| 536 |
/// // assert_eq!(vec_units.capacity(), usize::MAX); |
| 537 |
/// ``` |
| 538 |
pub fn with_capacity(cap: usize) -> ThinVec<T> { |
| 539 |
// `padding` contains ~static assertions against types that are |
| 540 |
// incompatible with the current feature flags. We also call it to |
| 541 |
// invoke these assertions when getting a pointer to the `ThinVec` |
| 542 |
// contents, but since we also get a pointer to the contents in the |
| 543 |
// `Drop` impl, trippng an assertion along that code path causes a |
| 544 |
// double panic. We duplicate the assertion here so that it is |
| 545 |
// testable, |
| 546 |
let _ = padding::<T>(); |
| 547 |
|
| 548 |
if cap == 0 { |
| 549 |
unsafe { |
| 550 |
ThinVec { |
| 551 |
ptr: NonNull::new_unchecked(&EMPTY_HEADER as *const Header as *mut Header), |
| 552 |
boo: PhantomData, |
| 553 |
} |
| 554 |
} |
| 555 |
} else { |
| 556 |
ThinVec { |
| 557 |
ptr: header_with_capacity::<T>(cap), |
| 558 |
boo: PhantomData, |
| 559 |
} |
| 560 |
} |
| 561 |
} |
| 562 |
|
| 563 |
// Accessor conveniences |
| 564 |
|
| 565 |
fn ptr(&self) -> *mut Header { |
| 566 |
self.ptr.as_ptr() |
| 567 |
} |
| 568 |
fn header(&self) -> &Header { |
| 569 |
unsafe { self.ptr.as_ref() } |
| 570 |
} |
| 571 |
fn data_raw(&self) -> *mut T { |
| 572 |
// `padding` contains ~static assertions against types that are |
| 573 |
// incompatible with the current feature flags. Even if we don't |
| 574 |
// care about its result, we should always call it before getting |
| 575 |
// a data pointer to guard against invalid types! |
| 576 |
let padding = padding::<T>(); |
| 577 |
|
| 578 |
// Although we ensure the data array is aligned when we allocate, |
| 579 |
// we can't do that with the empty singleton. So when it might not |
| 580 |
// be properly aligned, we substitute in the NonNull::dangling |
| 581 |
// which *is* aligned. |
| 582 |
// |
| 583 |
// To minimize dynamic branches on `cap` for all accesses |
| 584 |
// to the data, we include this guard which should only involve |
| 585 |
// compile-time constants. Ideally this should result in the branch |
| 586 |
// only be included for types with excessive alignment. |
| 587 |
let empty_header_is_aligned = if cfg!(feature = "gecko-ffi") { |
| 588 |
// in gecko-ffi mode `padding` will ensure this under |
| 589 |
// the assumption that the header has size 8 and the |
| 590 |
// static empty singleton is aligned to 8. |
| 591 |
true |
| 592 |
} else { |
| 593 |
// In non-gecko-ffi mode, the empty singleton is just |
| 594 |
// naturally aligned to the Header. If the Header is at |
| 595 |
// least as aligned as T *and* the padding would have |
| 596 |
// been 0, then one-past-the-end of the empty singleton |
| 597 |
// *is* a valid data pointer and we can remove the |
| 598 |
// `dangling` special case. |
| 599 |
mem::align_of::<Header>() >= mem::align_of::<T>() && padding == 0 |
| 600 |
}; |
| 601 |
|
| 602 |
unsafe { |
| 603 |
if !empty_header_is_aligned && self.header().cap() == 0 { |
| 604 |
NonNull::dangling().as_ptr() |
| 605 |
} else { |
| 606 |
// This could technically result in overflow, but padding |
| 607 |
// would have to be absurdly large for this to occur. |
| 608 |
let header_size = mem::size_of::<Header>(); |
| 609 |
let ptr = self.ptr.as_ptr() as *mut u8; |
| 610 |
ptr.add(header_size + padding) as *mut T |
| 611 |
} |
| 612 |
} |
| 613 |
} |
| 614 |
|
| 615 |
// This is unsafe when the header is EMPTY_HEADER. |
| 616 |
unsafe fn header_mut(&mut self) -> &mut Header { |
| 617 |
&mut *self.ptr() |
| 618 |
} |
| 619 |
|
| 620 |
/// Returns the number of elements in the vector, also referred to |
| 621 |
/// as its 'length'. |
| 622 |
/// |
| 623 |
/// # Examples |
| 624 |
/// |
| 625 |
/// ``` |
| 626 |
/// use thin_vec::thin_vec; |
| 627 |
/// |
| 628 |
/// let a = thin_vec![1, 2, 3]; |
| 629 |
/// assert_eq!(a.len(), 3); |
| 630 |
/// ``` |
| 631 |
pub fn len(&self) -> usize { |
| 632 |
self.header().len() |
| 633 |
} |
| 634 |
|
| 635 |
/// Returns `true` if the vector contains no elements. |
| 636 |
/// |
| 637 |
/// # Examples |
| 638 |
/// |
| 639 |
/// ``` |
| 640 |
/// use thin_vec::ThinVec; |
| 641 |
/// |
| 642 |
/// let mut v = ThinVec::new(); |
| 643 |
/// assert!(v.is_empty()); |
| 644 |
/// |
| 645 |
/// v.push(1); |
| 646 |
/// assert!(!v.is_empty()); |
| 647 |
/// ``` |
| 648 |
pub fn is_empty(&self) -> bool { |
| 649 |
self.len() == 0 |
| 650 |
} |
| 651 |
|
| 652 |
/// Returns the number of elements the vector can hold without |
| 653 |
/// reallocating. |
| 654 |
/// |
| 655 |
/// # Examples |
| 656 |
/// |
| 657 |
/// ``` |
| 658 |
/// use thin_vec::ThinVec; |
| 659 |
/// |
| 660 |
/// let vec: ThinVec<i32> = ThinVec::with_capacity(10); |
| 661 |
/// assert_eq!(vec.capacity(), 10); |
| 662 |
/// ``` |
| 663 |
pub fn capacity(&self) -> usize { |
| 664 |
self.header().cap() |
| 665 |
} |
| 666 |
|
| 667 |
/// Forces the length of the vector to `new_len`. |
| 668 |
/// |
| 669 |
/// This is a low-level operation that maintains none of the normal |
| 670 |
/// invariants of the type. Normally changing the length of a vector |
| 671 |
/// is done using one of the safe operations instead, such as |
| 672 |
/// [`truncate`], [`resize`], [`extend`], or [`clear`]. |
| 673 |
/// |
| 674 |
/// [`truncate`]: ThinVec::truncate |
| 675 |
/// [`resize`]: ThinVec::resize |
| 676 |
/// [`extend`]: ThinVec::extend |
| 677 |
/// [`clear`]: ThinVec::clear |
| 678 |
/// |
| 679 |
/// # Safety |
| 680 |
/// |
| 681 |
/// - `new_len` must be less than or equal to [`capacity()`]. |
| 682 |
/// - The elements at `old_len..new_len` must be initialized. |
| 683 |
/// |
| 684 |
/// [`capacity()`]: ThinVec::capacity |
| 685 |
/// |
| 686 |
/// # Examples |
| 687 |
/// |
| 688 |
/// This method can be useful for situations in which the vector |
| 689 |
/// is serving as a buffer for other code, particularly over FFI: |
| 690 |
/// |
| 691 |
/// ```no_run |
| 692 |
/// use thin_vec::ThinVec; |
| 693 |
/// |
| 694 |
/// # // This is just a minimal skeleton for the doc example; |
| 695 |
/// # // don't use this as a starting point for a real library. |
| 696 |
/// # pub struct StreamWrapper { strm: *mut std::ffi::c_void } |
| 697 |
/// # const Z_OK: i32 = 0; |
| 698 |
/// # extern "C" { |
| 699 |
/// # fn deflateGetDictionary( |
| 700 |
/// # strm: *mut std::ffi::c_void, |
| 701 |
/// # dictionary: *mut u8, |
| 702 |
/// # dictLength: *mut usize, |
| 703 |
/// # ) -> i32; |
| 704 |
/// # } |
| 705 |
/// # impl StreamWrapper { |
| 706 |
/// pub fn get_dictionary(&self) -> Option<ThinVec<u8>> { |
| 707 |
/// // Per the FFI method's docs, "32768 bytes is always enough". |
| 708 |
/// let mut dict = ThinVec::with_capacity(32_768); |
| 709 |
/// let mut dict_length = 0; |
| 710 |
/// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: |
| 711 |
/// // 1. `dict_length` elements were initialized. |
| 712 |
/// // 2. `dict_length` <= the capacity (32_768) |
| 713 |
/// // which makes `set_len` safe to call. |
| 714 |
/// unsafe { |
| 715 |
/// // Make the FFI call... |
| 716 |
/// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); |
| 717 |
/// if r == Z_OK { |
| 718 |
/// // ...and update the length to what was initialized. |
| 719 |
/// dict.set_len(dict_length); |
| 720 |
/// Some(dict) |
| 721 |
/// } else { |
| 722 |
/// None |
| 723 |
/// } |
| 724 |
/// } |
| 725 |
/// } |
| 726 |
/// # } |
| 727 |
/// ``` |
| 728 |
/// |
| 729 |
/// While the following example is sound, there is a memory leak since |
| 730 |
/// the inner vectors were not freed prior to the `set_len` call: |
| 731 |
/// |
| 732 |
/// ```no_run |
| 733 |
/// use thin_vec::thin_vec; |
| 734 |
/// |
| 735 |
/// let mut vec = thin_vec![thin_vec![1, 0, 0], |
| 736 |
/// thin_vec![0, 1, 0], |
| 737 |
/// thin_vec![0, 0, 1]]; |
| 738 |
/// // SAFETY: |
| 739 |
/// // 1. `old_len..0` is empty so no elements need to be initialized. |
| 740 |
/// // 2. `0 <= capacity` always holds whatever `capacity` is. |
| 741 |
/// unsafe { |
| 742 |
/// vec.set_len(0); |
| 743 |
/// } |
| 744 |
/// ``` |
| 745 |
/// |
| 746 |
/// Normally, here, one would use [`clear`] instead to correctly drop |
| 747 |
/// the contents and thus not leak memory. |
| 748 |
pub unsafe fn set_len(&mut self, len: usize) { |
| 749 |
if self.is_singleton() { |
| 750 |
// A prerequisite of `Vec::set_len` is that `new_len` must be |
| 751 |
// less than or equal to capacity(). The same applies here. |
| 752 |
assert!(len == 0, "invalid set_len({}) on empty ThinVec", len); |
| 753 |
} else { |
| 754 |
self.header_mut().set_len(len) |
| 755 |
} |
| 756 |
} |
| 757 |
|
| 758 |
// For internal use only, when setting the length and it's known to be the non-singleton. |
| 759 |
unsafe fn set_len_non_singleton(&mut self, len: usize) { |
| 760 |
self.header_mut().set_len(len) |
| 761 |
} |
| 762 |
|
| 763 |
/// Appends an element to the back of a collection. |
| 764 |
/// |
| 765 |
/// # Panics |
| 766 |
/// |
| 767 |
/// Panics if the new capacity exceeds `isize::MAX` bytes. |
| 768 |
/// |
| 769 |
/// # Examples |
| 770 |
/// |
| 771 |
/// ``` |
| 772 |
/// use thin_vec::thin_vec; |
| 773 |
/// |
| 774 |
/// let mut vec = thin_vec![1, 2]; |
| 775 |
/// vec.push(3); |
| 776 |
/// assert_eq!(vec, [1, 2, 3]); |
| 777 |
/// ``` |
| 778 |
pub fn push(&mut self, val: T) { |
| 779 |
let old_len = self.len(); |
| 780 |
if old_len == self.capacity() { |
| 781 |
self.reserve(1); |
| 782 |
} |
| 783 |
unsafe { |
| 784 |
ptr::write(self.data_raw().add(old_len), val); |
| 785 |
self.set_len_non_singleton(old_len + 1); |
| 786 |
} |
| 787 |
} |
| 788 |
|
| 789 |
/// Removes the last element from a vector and returns it, or [`None`] if it |
| 790 |
/// is empty. |
| 791 |
/// |
| 792 |
/// # Examples |
| 793 |
/// |
| 794 |
/// ``` |
| 795 |
/// use thin_vec::thin_vec; |
| 796 |
/// |
| 797 |
/// let mut vec = thin_vec![1, 2, 3]; |
| 798 |
/// assert_eq!(vec.pop(), Some(3)); |
| 799 |
/// assert_eq!(vec, [1, 2]); |
| 800 |
/// ``` |
| 801 |
pub fn pop(&mut self) -> Option<T> { |
| 802 |
let old_len = self.len(); |
| 803 |
if old_len == 0 { |
| 804 |
return None; |
| 805 |
} |
| 806 |
|
| 807 |
unsafe { |
| 808 |
self.set_len_non_singleton(old_len - 1); |
| 809 |
Some(ptr::read(self.data_raw().add(old_len - 1))) |
| 810 |
} |
| 811 |
} |
| 812 |
|
| 813 |
/// Inserts an element at position `index` within the vector, shifting all |
| 814 |
/// elements after it to the right. |
| 815 |
/// |
| 816 |
/// # Panics |
| 817 |
/// |
| 818 |
/// Panics if `index > len`. |
| 819 |
/// |
| 820 |
/// # Examples |
| 821 |
/// |
| 822 |
/// ``` |
| 823 |
/// use thin_vec::thin_vec; |
| 824 |
/// |
| 825 |
/// let mut vec = thin_vec![1, 2, 3]; |
| 826 |
/// vec.insert(1, 4); |
| 827 |
/// assert_eq!(vec, [1, 4, 2, 3]); |
| 828 |
/// vec.insert(4, 5); |
| 829 |
/// assert_eq!(vec, [1, 4, 2, 3, 5]); |
| 830 |
/// ``` |
| 831 |
pub fn insert(&mut self, idx: usize, elem: T) { |
| 832 |
let old_len = self.len(); |
| 833 |
|
| 834 |
assert!(idx <= old_len, "Index out of bounds"); |
| 835 |
if old_len == self.capacity() { |
| 836 |
self.reserve(1); |
| 837 |
} |
| 838 |
unsafe { |
| 839 |
let ptr = self.data_raw(); |
| 840 |
ptr::copy(ptr.add(idx), ptr.add(idx + 1), old_len - idx); |
| 841 |
ptr::write(ptr.add(idx), elem); |
| 842 |
self.set_len_non_singleton(old_len + 1); |
| 843 |
} |
| 844 |
} |
| 845 |
|
| 846 |
/// Removes and returns the element at position `index` within the vector, |
| 847 |
/// shifting all elements after it to the left. |
| 848 |
/// |
| 849 |
/// Note: Because this shifts over the remaining elements, it has a |
| 850 |
/// worst-case performance of *O*(*n*). If you don't need the order of elements |
| 851 |
/// to be preserved, use [`swap_remove`] instead. If you'd like to remove |
| 852 |
/// elements from the beginning of the `ThinVec`, consider using `std::collections::VecDeque`. |
| 853 |
/// |
| 854 |
/// [`swap_remove`]: ThinVec::swap_remove |
| 855 |
/// |
| 856 |
/// # Panics |
| 857 |
/// |
| 858 |
/// Panics if `index` is out of bounds. |
| 859 |
/// |
| 860 |
/// # Examples |
| 861 |
/// |
| 862 |
/// ``` |
| 863 |
/// use thin_vec::thin_vec; |
| 864 |
/// |
| 865 |
/// let mut v = thin_vec![1, 2, 3]; |
| 866 |
/// assert_eq!(v.remove(1), 2); |
| 867 |
/// assert_eq!(v, [1, 3]); |
| 868 |
/// ``` |
| 869 |
pub fn remove(&mut self, idx: usize) -> T { |
| 870 |
let old_len = self.len(); |
| 871 |
|
| 872 |
assert!(idx < old_len, "Index out of bounds"); |
| 873 |
|
| 874 |
unsafe { |
| 875 |
self.set_len_non_singleton(old_len - 1); |
| 876 |
let ptr = self.data_raw(); |
| 877 |
let val = ptr::read(self.data_raw().add(idx)); |
| 878 |
ptr::copy(ptr.add(idx + 1), ptr.add(idx), old_len - idx - 1); |
| 879 |
val |
| 880 |
} |
| 881 |
} |
| 882 |
|
| 883 |
/// Removes an element from the vector and returns it. |
| 884 |
/// |
| 885 |
/// The removed element is replaced by the last element of the vector. |
| 886 |
/// |
| 887 |
/// This does not preserve ordering, but is *O*(1). |
| 888 |
/// If you need to preserve the element order, use [`remove`] instead. |
| 889 |
/// |
| 890 |
/// [`remove`]: ThinVec::remove |
| 891 |
/// |
| 892 |
/// # Panics |
| 893 |
/// |
| 894 |
/// Panics if `index` is out of bounds. |
| 895 |
/// |
| 896 |
/// # Examples |
| 897 |
/// |
| 898 |
/// ``` |
| 899 |
/// use thin_vec::thin_vec; |
| 900 |
/// |
| 901 |
/// let mut v = thin_vec!["foo", "bar", "baz", "qux"]; |
| 902 |
/// |
| 903 |
/// assert_eq!(v.swap_remove(1), "bar"); |
| 904 |
/// assert_eq!(v, ["foo", "qux", "baz"]); |
| 905 |
/// |
| 906 |
/// assert_eq!(v.swap_remove(0), "foo"); |
| 907 |
/// assert_eq!(v, ["baz", "qux"]); |
| 908 |
/// ``` |
| 909 |
pub fn swap_remove(&mut self, idx: usize) -> T { |
| 910 |
let old_len = self.len(); |
| 911 |
|
| 912 |
assert!(idx < old_len, "Index out of bounds"); |
| 913 |
|
| 914 |
unsafe { |
| 915 |
let ptr = self.data_raw(); |
| 916 |
ptr::swap(ptr.add(idx), ptr.add(old_len - 1)); |
| 917 |
self.set_len_non_singleton(old_len - 1); |
| 918 |
ptr::read(ptr.add(old_len - 1)) |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
/// Shortens the vector, keeping the first `len` elements and dropping |
| 923 |
/// the rest. |
| 924 |
/// |
| 925 |
/// If `len` is greater than the vector's current length, this has no |
| 926 |
/// effect. |
| 927 |
/// |
| 928 |
/// The [`drain`] method can emulate `truncate`, but causes the excess |
| 929 |
/// elements to be returned instead of dropped. |
| 930 |
/// |
| 931 |
/// Note that this method has no effect on the allocated capacity |
| 932 |
/// of the vector. |
| 933 |
/// |
| 934 |
/// # Examples |
| 935 |
/// |
| 936 |
/// Truncating a five element vector to two elements: |
| 937 |
/// |
| 938 |
/// ``` |
| 939 |
/// use thin_vec::thin_vec; |
| 940 |
/// |
| 941 |
/// let mut vec = thin_vec![1, 2, 3, 4, 5]; |
| 942 |
/// vec.truncate(2); |
| 943 |
/// assert_eq!(vec, [1, 2]); |
| 944 |
/// ``` |
| 945 |
/// |
| 946 |
/// No truncation occurs when `len` is greater than the vector's current |
| 947 |
/// length: |
| 948 |
/// |
| 949 |
/// ``` |
| 950 |
/// use thin_vec::thin_vec; |
| 951 |
/// |
| 952 |
/// let mut vec = thin_vec![1, 2, 3]; |
| 953 |
/// vec.truncate(8); |
| 954 |
/// assert_eq!(vec, [1, 2, 3]); |
| 955 |
/// ``` |
| 956 |
/// |
| 957 |
/// Truncating when `len == 0` is equivalent to calling the [`clear`] |
| 958 |
/// method. |
| 959 |
/// |
| 960 |
/// ``` |
| 961 |
/// use thin_vec::thin_vec; |
| 962 |
/// |
| 963 |
/// let mut vec = thin_vec![1, 2, 3]; |
| 964 |
/// vec.truncate(0); |
| 965 |
/// assert_eq!(vec, []); |
| 966 |
/// ``` |
| 967 |
/// |
| 968 |
/// [`clear`]: ThinVec::clear |
| 969 |
/// [`drain`]: ThinVec::drain |
| 970 |
pub fn truncate(&mut self, len: usize) { |
| 971 |
unsafe { |
| 972 |
// drop any extra elements |
| 973 |
while len < self.len() { |
| 974 |
// decrement len before the drop_in_place(), so a panic on Drop |
| 975 |
// doesn't re-drop the just-failed value. |
| 976 |
let new_len = self.len() - 1; |
| 977 |
self.set_len_non_singleton(new_len); |
| 978 |
ptr::drop_in_place(self.data_raw().add(new_len)); |
| 979 |
} |
| 980 |
} |
| 981 |
} |
| 982 |
|
| 983 |
/// Clears the vector, removing all values. |
| 984 |
/// |
| 985 |
/// Note that this method has no effect on the allocated capacity |
| 986 |
/// of the vector. |
| 987 |
/// |
| 988 |
/// # Examples |
| 989 |
/// |
| 990 |
/// ``` |
| 991 |
/// use thin_vec::thin_vec; |
| 992 |
/// |
| 993 |
/// let mut v = thin_vec![1, 2, 3]; |
| 994 |
/// v.clear(); |
| 995 |
/// assert!(v.is_empty()); |
| 996 |
/// ``` |
| 997 |
pub fn clear(&mut self) { |
| 998 |
unsafe { |
| 999 |
ptr::drop_in_place(&mut self[..]); |
| 1000 |
self.set_len(0); // could be the singleton |
| 1001 |
} |
| 1002 |
} |
| 1003 |
|
| 1004 |
/// Extracts a slice containing the entire vector. |
| 1005 |
/// |
| 1006 |
/// Equivalent to `&s[..]`. |
| 1007 |
/// |
| 1008 |
/// # Examples |
| 1009 |
/// |
| 1010 |
/// ``` |
| 1011 |
/// use thin_vec::thin_vec; |
| 1012 |
/// use std::io::{self, Write}; |
| 1013 |
/// let buffer = thin_vec![1, 2, 3, 5, 8]; |
| 1014 |
/// io::sink().write(buffer.as_slice()).unwrap(); |
| 1015 |
/// ``` |
| 1016 |
pub fn as_slice(&self) -> &[T] { |
| 1017 |
unsafe { slice::from_raw_parts(self.data_raw(), self.len()) } |
| 1018 |
} |
| 1019 |
|
| 1020 |
/// Extracts a mutable slice of the entire vector. |
| 1021 |
/// |
| 1022 |
/// Equivalent to `&mut s[..]`. |
| 1023 |
/// |
| 1024 |
/// # Examples |
| 1025 |
/// |
| 1026 |
/// ``` |
| 1027 |
/// use thin_vec::thin_vec; |
| 1028 |
/// use std::io::{self, Read}; |
| 1029 |
/// let mut buffer = vec![0; 3]; |
| 1030 |
/// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); |
| 1031 |
/// ``` |
| 1032 |
pub fn as_mut_slice(&mut self) -> &mut [T] { |
| 1033 |
unsafe { slice::from_raw_parts_mut(self.data_raw(), self.len()) } |
| 1034 |
} |
| 1035 |
|
| 1036 |
/// Reserve capacity for at least `additional` more elements to be inserted. |
| 1037 |
/// |
| 1038 |
/// May reserve more space than requested, to avoid frequent reallocations. |
| 1039 |
/// |
| 1040 |
/// Panics if the new capacity overflows `usize`. |
| 1041 |
/// |
| 1042 |
/// Re-allocates only if `self.capacity() < self.len() + additional`. |
| 1043 |
#[cfg(not(feature = "gecko-ffi"))] |
| 1044 |
pub fn reserve(&mut self, additional: usize) { |
| 1045 |
let len = self.len(); |
| 1046 |
let old_cap = self.capacity(); |
| 1047 |
let min_cap = len.checked_add(additional).expect("capacity overflow"); |
| 1048 |
if min_cap <= old_cap { |
| 1049 |
return; |
| 1050 |
} |
| 1051 |
// Ensure the new capacity is at least double, to guarantee exponential growth. |
| 1052 |
let double_cap = if old_cap == 0 { |
| 1053 |
// skip to 4 because tiny ThinVecs are dumb; but not if that would cause overflow |
| 1054 |
if mem::size_of::<T>() > (!0) / 8 { |
| 1055 |
1 |
| 1056 |
} else { |
| 1057 |
4 |
| 1058 |
} |
| 1059 |
} else { |
| 1060 |
old_cap.saturating_mul(2) |
| 1061 |
}; |
| 1062 |
let new_cap = max(min_cap, double_cap); |
| 1063 |
unsafe { |
| 1064 |
self.reallocate(new_cap); |
| 1065 |
} |
| 1066 |
} |
| 1067 |
|
| 1068 |
/// Reserve capacity for at least `additional` more elements to be inserted. |
| 1069 |
/// |
| 1070 |
/// This method mimics the growth algorithm used by the C++ implementation |
| 1071 |
/// of nsTArray. |
| 1072 |
#[cfg(feature = "gecko-ffi")] |
| 1073 |
pub fn reserve(&mut self, additional: usize) { |
| 1074 |
let elem_size = mem::size_of::<T>(); |
| 1075 |
|
| 1076 |
let len = self.len(); |
| 1077 |
let old_cap = self.capacity(); |
| 1078 |
let min_cap = len.checked_add(additional).expect("capacity overflow"); |
| 1079 |
if min_cap <= old_cap { |
| 1080 |
return; |
| 1081 |
} |
| 1082 |
|
| 1083 |
// The growth logic can't handle zero-sized types, so we have to exit |
| 1084 |
// early here. |
| 1085 |
if elem_size == 0 { |
| 1086 |
unsafe { |
| 1087 |
self.reallocate(min_cap); |
| 1088 |
} |
| 1089 |
return; |
| 1090 |
} |
| 1091 |
|
| 1092 |
let min_cap_bytes = assert_size(min_cap) |
| 1093 |
.checked_mul(assert_size(elem_size)) |
| 1094 |
.and_then(|x| x.checked_add(assert_size(mem::size_of::<Header>()))) |
| 1095 |
.unwrap(); |
| 1096 |
|
| 1097 |
// Perform some checked arithmetic to ensure all of the numbers we |
| 1098 |
// compute will end up in range. |
| 1099 |
let will_fit = min_cap_bytes.checked_mul(2).is_some(); |
| 1100 |
if !will_fit { |
| 1101 |
panic!("Exceeded maximum nsTArray size"); |
| 1102 |
} |
| 1103 |
|
| 1104 |
const SLOW_GROWTH_THRESHOLD: usize = 8 * 1024 * 1024; |
| 1105 |
|
| 1106 |
let bytes = if min_cap > SLOW_GROWTH_THRESHOLD { |
| 1107 |
// Grow by a minimum of 1.125x |
| 1108 |
let old_cap_bytes = old_cap * elem_size + mem::size_of::<Header>(); |
| 1109 |
let min_growth = old_cap_bytes + (old_cap_bytes >> 3); |
| 1110 |
let growth = max(min_growth, min_cap_bytes as usize); |
| 1111 |
|
| 1112 |
// Round up to the next megabyte. |
| 1113 |
const MB: usize = 1 << 20; |
| 1114 |
MB * ((growth + MB - 1) / MB) |
| 1115 |
} else { |
| 1116 |
// Try to allocate backing buffers in powers of two. |
| 1117 |
min_cap_bytes.next_power_of_two() as usize |
| 1118 |
}; |
| 1119 |
|
| 1120 |
let cap = (bytes - std::mem::size_of::<Header>()) / elem_size; |
| 1121 |
unsafe { |
| 1122 |
self.reallocate(cap); |
| 1123 |
} |
| 1124 |
} |
| 1125 |
|
| 1126 |
/// Reserves the minimum capacity for `additional` more elements to be inserted. |
| 1127 |
/// |
| 1128 |
/// Panics if the new capacity overflows `usize`. |
| 1129 |
/// |
| 1130 |
/// Re-allocates only if `self.capacity() < self.len() + additional`. |
| 1131 |
pub fn reserve_exact(&mut self, additional: usize) { |
| 1132 |
let new_cap = self |
| 1133 |
.len() |
| 1134 |
.checked_add(additional) |
| 1135 |
.expect("capacity overflow"); |
| 1136 |
let old_cap = self.capacity(); |
| 1137 |
if new_cap > old_cap { |
| 1138 |
unsafe { |
| 1139 |
self.reallocate(new_cap); |
| 1140 |
} |
| 1141 |
} |
| 1142 |
} |
| 1143 |
|
| 1144 |
/// Shrinks the capacity of the vector as much as possible. |
| 1145 |
/// |
| 1146 |
/// It will drop down as close as possible to the length but the allocator |
| 1147 |
/// may still inform the vector that there is space for a few more elements. |
| 1148 |
/// |
| 1149 |
/// # Examples |
| 1150 |
/// |
| 1151 |
/// ``` |
| 1152 |
/// use thin_vec::ThinVec; |
| 1153 |
/// |
| 1154 |
/// let mut vec = ThinVec::with_capacity(10); |
| 1155 |
/// vec.extend([1, 2, 3]); |
| 1156 |
/// assert_eq!(vec.capacity(), 10); |
| 1157 |
/// vec.shrink_to_fit(); |
| 1158 |
/// assert!(vec.capacity() >= 3); |
| 1159 |
/// ``` |
| 1160 |
pub fn shrink_to_fit(&mut self) { |
| 1161 |
let old_cap = self.capacity(); |
| 1162 |
let new_cap = self.len(); |
| 1163 |
if new_cap < old_cap { |
| 1164 |
if new_cap == 0 { |
| 1165 |
*self = ThinVec::new(); |
| 1166 |
} else { |
| 1167 |
unsafe { |
| 1168 |
self.reallocate(new_cap); |
| 1169 |
} |
| 1170 |
} |
| 1171 |
} |
| 1172 |
} |
| 1173 |
|
| 1174 |
/// Retains only the elements specified by the predicate. |
| 1175 |
/// |
| 1176 |
/// In other words, remove all elements `e` such that `f(&e)` returns `false`. |
| 1177 |
/// This method operates in place and preserves the order of the retained |
| 1178 |
/// elements. |
| 1179 |
/// |
| 1180 |
/// # Examples |
| 1181 |
/// |
| 1182 |
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`. |
| 1183 |
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")] |
| 1184 |
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")] |
| 1185 |
/// # #[macro_use] extern crate thin_vec; |
| 1186 |
/// # fn main() { |
| 1187 |
/// let mut vec = thin_vec![1, 2, 3, 4]; |
| 1188 |
/// vec.retain(|&x| x%2 == 0); |
| 1189 |
/// assert_eq!(vec, [2, 4]); |
| 1190 |
/// # } |
| 1191 |
/// ``` |
| 1192 |
pub fn retain<F>(&mut self, mut f: F) |
| 1193 |
where |
| 1194 |
F: FnMut(&T) -> bool, |
| 1195 |
{ |
| 1196 |
self.retain_mut(|x| f(&*x)); |
| 1197 |
} |
| 1198 |
|
| 1199 |
/// Retains only the elements specified by the predicate, passing a mutable reference to it. |
| 1200 |
/// |
| 1201 |
/// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. |
| 1202 |
/// This method operates in place and preserves the order of the retained |
| 1203 |
/// elements. |
| 1204 |
/// |
| 1205 |
/// # Examples |
| 1206 |
/// |
| 1207 |
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`. |
| 1208 |
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")] |
| 1209 |
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")] |
| 1210 |
/// # #[macro_use] extern crate thin_vec; |
| 1211 |
/// # fn main() { |
| 1212 |
/// let mut vec = thin_vec![1, 2, 3, 4, 5]; |
| 1213 |
/// vec.retain_mut(|x| { |
| 1214 |
/// *x += 1; |
| 1215 |
/// (*x)%2 == 0 |
| 1216 |
/// }); |
| 1217 |
/// assert_eq!(vec, [2, 4, 6]); |
| 1218 |
/// # } |
| 1219 |
/// ``` |
| 1220 |
pub fn retain_mut<F>(&mut self, mut f: F) |
| 1221 |
where |
| 1222 |
F: FnMut(&mut T) -> bool, |
| 1223 |
{ |
| 1224 |
let len = self.len(); |
| 1225 |
let mut del = 0; |
| 1226 |
{ |
| 1227 |
let v = &mut self[..]; |
| 1228 |
|
| 1229 |
for i in 0..len { |
| 1230 |
if !f(&mut v[i]) { |
| 1231 |
del += 1; |
| 1232 |
} else if del > 0 { |
| 1233 |
v.swap(i - del, i); |
| 1234 |
} |
| 1235 |
} |
| 1236 |
} |
| 1237 |
if del > 0 { |
| 1238 |
self.truncate(len - del); |
| 1239 |
} |
| 1240 |
} |
| 1241 |
|
| 1242 |
/// Removes consecutive elements in the vector that resolve to the same key. |
| 1243 |
/// |
| 1244 |
/// If the vector is sorted, this removes all duplicates. |
| 1245 |
/// |
| 1246 |
/// # Examples |
| 1247 |
/// |
| 1248 |
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`. |
| 1249 |
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")] |
| 1250 |
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")] |
| 1251 |
/// # #[macro_use] extern crate thin_vec; |
| 1252 |
/// # fn main() { |
| 1253 |
/// let mut vec = thin_vec![10, 20, 21, 30, 20]; |
| 1254 |
/// |
| 1255 |
/// vec.dedup_by_key(|i| *i / 10); |
| 1256 |
/// |
| 1257 |
/// assert_eq!(vec, [10, 20, 30, 20]); |
| 1258 |
/// # } |
| 1259 |
/// ``` |
| 1260 |
pub fn dedup_by_key<F, K>(&mut self, mut key: F) |
| 1261 |
where |
| 1262 |
F: FnMut(&mut T) -> K, |
| 1263 |
K: PartialEq<K>, |
| 1264 |
{ |
| 1265 |
self.dedup_by(|a, b| key(a) == key(b)) |
| 1266 |
} |
| 1267 |
|
| 1268 |
/// Removes consecutive elements in the vector according to a predicate. |
| 1269 |
/// |
| 1270 |
/// The `same_bucket` function is passed references to two elements from the vector, and |
| 1271 |
/// returns `true` if the elements compare equal, or `false` if they do not. Only the first |
| 1272 |
/// of adjacent equal items is kept. |
| 1273 |
/// |
| 1274 |
/// If the vector is sorted, this removes all duplicates. |
| 1275 |
/// |
| 1276 |
/// # Examples |
| 1277 |
/// |
| 1278 |
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`. |
| 1279 |
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")] |
| 1280 |
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")] |
| 1281 |
/// # #[macro_use] extern crate thin_vec; |
| 1282 |
/// # fn main() { |
| 1283 |
/// let mut vec = thin_vec!["foo", "bar", "Bar", "baz", "bar"]; |
| 1284 |
/// |
| 1285 |
/// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); |
| 1286 |
/// |
| 1287 |
/// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); |
| 1288 |
/// # } |
| 1289 |
/// ``` |
| 1290 |
#[allow(clippy::swap_ptr_to_ref)] |
| 1291 |
pub fn dedup_by<F>(&mut self, mut same_bucket: F) |
| 1292 |
where |
| 1293 |
F: FnMut(&mut T, &mut T) -> bool, |
| 1294 |
{ |
| 1295 |
// See the comments in `Vec::dedup` for a detailed explanation of this code. |
| 1296 |
unsafe { |
| 1297 |
let ln = self.len(); |
| 1298 |
if ln <= 1 { |
| 1299 |
return; |
| 1300 |
} |
| 1301 |
|
| 1302 |
// Avoid bounds checks by using raw pointers. |
| 1303 |
let p = self.as_mut_ptr(); |
| 1304 |
let mut r: usize = 1; |
| 1305 |
let mut w: usize = 1; |
| 1306 |
|
| 1307 |
while r < ln { |
| 1308 |
let p_r = p.add(r); |
| 1309 |
let p_wm1 = p.add(w - 1); |
| 1310 |
if !same_bucket(&mut *p_r, &mut *p_wm1) { |
| 1311 |
if r != w { |
| 1312 |
let p_w = p_wm1.add(1); |
| 1313 |
mem::swap(&mut *p_r, &mut *p_w); |
| 1314 |
} |
| 1315 |
w += 1; |
| 1316 |
} |
| 1317 |
r += 1; |
| 1318 |
} |
| 1319 |
|
| 1320 |
self.truncate(w); |
| 1321 |
} |
| 1322 |
} |
| 1323 |
|
| 1324 |
/// Splits the collection into two at the given index. |
| 1325 |
/// |
| 1326 |
/// Returns a newly allocated vector containing the elements in the range |
| 1327 |
/// `[at, len)`. After the call, the original vector will be left containing |
| 1328 |
/// the elements `[0, at)` with its previous capacity unchanged. |
| 1329 |
/// |
| 1330 |
/// # Panics |
| 1331 |
/// |
| 1332 |
/// Panics if `at > len`. |
| 1333 |
/// |
| 1334 |
/// # Examples |
| 1335 |
/// |
| 1336 |
/// ``` |
| 1337 |
/// use thin_vec::thin_vec; |
| 1338 |
/// |
| 1339 |
/// let mut vec = thin_vec![1, 2, 3]; |
| 1340 |
/// let vec2 = vec.split_off(1); |
| 1341 |
/// assert_eq!(vec, [1]); |
| 1342 |
/// assert_eq!(vec2, [2, 3]); |
| 1343 |
/// ``` |
| 1344 |
pub fn split_off(&mut self, at: usize) -> ThinVec<T> { |
| 1345 |
let old_len = self.len(); |
| 1346 |
let new_vec_len = old_len - at; |
| 1347 |
|
| 1348 |
assert!(at <= old_len, "Index out of bounds"); |
| 1349 |
|
| 1350 |
unsafe { |
| 1351 |
let mut new_vec = ThinVec::with_capacity(new_vec_len); |
| 1352 |
|
| 1353 |
ptr::copy_nonoverlapping(self.data_raw().add(at), new_vec.data_raw(), new_vec_len); |
| 1354 |
|
| 1355 |
new_vec.set_len(new_vec_len); // could be the singleton |
| 1356 |
self.set_len(at); // could be the singleton |
| 1357 |
|
| 1358 |
new_vec |
| 1359 |
} |
| 1360 |
} |
| 1361 |
|
| 1362 |
/// Moves all the elements of `other` into `self`, leaving `other` empty. |
| 1363 |
/// |
| 1364 |
/// # Panics |
| 1365 |
/// |
| 1366 |
/// Panics if the new capacity exceeds `isize::MAX` bytes. |
| 1367 |
/// |
| 1368 |
/// # Examples |
| 1369 |
/// |
| 1370 |
/// ``` |
| 1371 |
/// use thin_vec::thin_vec; |
| 1372 |
/// |
| 1373 |
/// let mut vec = thin_vec![1, 2, 3]; |
| 1374 |
/// let mut vec2 = thin_vec![4, 5, 6]; |
| 1375 |
/// vec.append(&mut vec2); |
| 1376 |
/// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); |
| 1377 |
/// assert_eq!(vec2, []); |
| 1378 |
/// ``` |
| 1379 |
pub fn append(&mut self, other: &mut ThinVec<T>) { |
| 1380 |
self.extend(other.drain(..)) |
| 1381 |
} |
| 1382 |
|
| 1383 |
/// Removes the specified range from the vector in bulk, returning all |
| 1384 |
/// removed elements as an iterator. If the iterator is dropped before |
| 1385 |
/// being fully consumed, it drops the remaining removed elements. |
| 1386 |
/// |
| 1387 |
/// The returned iterator keeps a mutable borrow on the vector to optimize |
| 1388 |
/// its implementation. |
| 1389 |
/// |
| 1390 |
/// # Panics |
| 1391 |
/// |
| 1392 |
/// Panics if the starting point is greater than the end point or if |
| 1393 |
/// the end point is greater than the length of the vector. |
| 1394 |
/// |
| 1395 |
/// # Leaking |
| 1396 |
/// |
| 1397 |
/// If the returned iterator goes out of scope without being dropped (due to |
| 1398 |
/// [`mem::forget`], for example), the vector may have lost and leaked |
| 1399 |
/// elements arbitrarily, including elements outside the range. |
| 1400 |
/// |
| 1401 |
/// # Examples |
| 1402 |
/// |
| 1403 |
/// ``` |
| 1404 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 1405 |
/// |
| 1406 |
/// let mut v = thin_vec![1, 2, 3]; |
| 1407 |
/// let u: ThinVec<_> = v.drain(1..).collect(); |
| 1408 |
/// assert_eq!(v, &[1]); |
| 1409 |
/// assert_eq!(u, &[2, 3]); |
| 1410 |
/// |
| 1411 |
/// // A full range clears the vector, like `clear()` does |
| 1412 |
/// v.drain(..); |
| 1413 |
/// assert_eq!(v, &[]); |
| 1414 |
/// ``` |
| 1415 |
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T> |
| 1416 |
where |
| 1417 |
R: RangeBounds<usize>, |
| 1418 |
{ |
| 1419 |
// See comments in the Drain struct itself for details on this |
| 1420 |
let len = self.len(); |
| 1421 |
let start = match range.start_bound() { |
| 1422 |
Bound::Included(&n) => n, |
| 1423 |
Bound::Excluded(&n) => n + 1, |
| 1424 |
Bound::Unbounded => 0, |
| 1425 |
}; |
| 1426 |
let end = match range.end_bound() { |
| 1427 |
Bound::Included(&n) => n + 1, |
| 1428 |
Bound::Excluded(&n) => n, |
| 1429 |
Bound::Unbounded => len, |
| 1430 |
}; |
| 1431 |
assert!(start <= end); |
| 1432 |
assert!(end <= len); |
| 1433 |
|
| 1434 |
unsafe { |
| 1435 |
// Set our length to the start bound |
| 1436 |
self.set_len(start); // could be the singleton |
| 1437 |
|
| 1438 |
let iter = |
| 1439 |
slice::from_raw_parts_mut(self.data_raw().add(start), end - start).iter_mut(); |
| 1440 |
|
| 1441 |
Drain { |
| 1442 |
iter, |
| 1443 |
vec: self, |
| 1444 |
end, |
| 1445 |
tail: len - end, |
| 1446 |
} |
| 1447 |
} |
| 1448 |
} |
| 1449 |
|
| 1450 |
/// Creates a splicing iterator that replaces the specified range in the vector |
| 1451 |
/// with the given `replace_with` iterator and yields the removed items. |
| 1452 |
/// `replace_with` does not need to be the same length as `range`. |
| 1453 |
/// |
| 1454 |
/// `range` is removed even if the iterator is not consumed until the end. |
| 1455 |
/// |
| 1456 |
/// It is unspecified how many elements are removed from the vector |
| 1457 |
/// if the `Splice` value is leaked. |
| 1458 |
/// |
| 1459 |
/// The input iterator `replace_with` is only consumed when the `Splice` value is dropped. |
| 1460 |
/// |
| 1461 |
/// This is optimal if: |
| 1462 |
/// |
| 1463 |
/// * The tail (elements in the vector after `range`) is empty, |
| 1464 |
/// * or `replace_with` yields fewer or equal elements than `range`’s length |
| 1465 |
/// * or the lower bound of its `size_hint()` is exact. |
| 1466 |
/// |
| 1467 |
/// Otherwise, a temporary vector is allocated and the tail is moved twice. |
| 1468 |
/// |
| 1469 |
/// # Panics |
| 1470 |
/// |
| 1471 |
/// Panics if the starting point is greater than the end point or if |
| 1472 |
/// the end point is greater than the length of the vector. |
| 1473 |
/// |
| 1474 |
/// # Examples |
| 1475 |
/// |
| 1476 |
/// ``` |
| 1477 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 1478 |
/// |
| 1479 |
/// let mut v = thin_vec![1, 2, 3, 4]; |
| 1480 |
/// let new = [7, 8, 9]; |
| 1481 |
/// let u: ThinVec<_> = v.splice(1..3, new).collect(); |
| 1482 |
/// assert_eq!(v, &[1, 7, 8, 9, 4]); |
| 1483 |
/// assert_eq!(u, &[2, 3]); |
| 1484 |
/// ``` |
| 1485 |
#[inline] |
| 1486 |
pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter> |
| 1487 |
where |
| 1488 |
R: RangeBounds<usize>, |
| 1489 |
I: IntoIterator<Item = T>, |
| 1490 |
{ |
| 1491 |
Splice { |
| 1492 |
drain: self.drain(range), |
| 1493 |
replace_with: replace_with.into_iter(), |
| 1494 |
} |
| 1495 |
} |
| 1496 |
|
| 1497 |
/// Resize the buffer and update its capacity, without changing the length. |
| 1498 |
/// Unsafe because it can cause length to be greater than capacity. |
| 1499 |
unsafe fn reallocate(&mut self, new_cap: usize) { |
| 1500 |
debug_assert!(new_cap > 0); |
| 1501 |
if self.has_allocation() { |
| 1502 |
let old_cap = self.capacity(); |
| 1503 |
let ptr = realloc( |
| 1504 |
self.ptr() as *mut u8, |
| 1505 |
layout::<T>(old_cap), |
| 1506 |
alloc_size::<T>(new_cap), |
| 1507 |
) as *mut Header; |
| 1508 |
|
| 1509 |
if ptr.is_null() { |
| 1510 |
handle_alloc_error(layout::<T>(new_cap)) |
| 1511 |
} |
| 1512 |
(*ptr).set_cap(new_cap); |
| 1513 |
self.ptr = NonNull::new_unchecked(ptr); |
| 1514 |
} else { |
| 1515 |
let new_header = header_with_capacity::<T>(new_cap); |
| 1516 |
|
| 1517 |
// If we get here and have a non-zero len, then we must be handling |
| 1518 |
// a gecko auto array, and we have items in a stack buffer. We shouldn't |
| 1519 |
// free it, but we should memcopy the contents out of it and mark it as empty. |
| 1520 |
// |
| 1521 |
// T is assumed to be trivially relocatable, as this is ~required |
| 1522 |
// for Rust compatibility anyway. Furthermore, we assume C++ won't try |
| 1523 |
// to unconditionally destroy the contents of the stack allocated buffer |
| 1524 |
// (i.e. it's obfuscated behind a union). |
| 1525 |
// |
| 1526 |
// In effect, we are partially reimplementing the auto array move constructor |
| 1527 |
// by leaving behind a valid empty instance. |
| 1528 |
let len = self.len(); |
| 1529 |
if cfg!(feature = "gecko-ffi") && len > 0 { |
| 1530 |
new_header |
| 1531 |
.as_ptr() |
| 1532 |
.add(1) |
| 1533 |
.cast::<T>() |
| 1534 |
.copy_from_nonoverlapping(self.data_raw(), len); |
| 1535 |
self.set_len_non_singleton(0); |
| 1536 |
} |
| 1537 |
|
| 1538 |
self.ptr = new_header; |
| 1539 |
} |
| 1540 |
} |
| 1541 |
|
| 1542 |
#[cfg(feature = "gecko-ffi")] |
| 1543 |
#[inline] |
| 1544 |
#[allow(unused_unsafe)] |
| 1545 |
fn is_singleton(&self) -> bool { |
| 1546 |
// NOTE: the tests will complain that this "unsafe" isn't needed, but it *IS*! |
| 1547 |
// In production this refers to an *extern static* which *is* unsafe to reference. |
| 1548 |
// In tests this refers to a local static because we don't have Firefox's codebase |
| 1549 |
// providing the symbol! |
| 1550 |
unsafe { self.ptr.as_ptr() as *const Header == &EMPTY_HEADER } |
| 1551 |
} |
| 1552 |
|
| 1553 |
#[cfg(not(feature = "gecko-ffi"))] |
| 1554 |
#[inline] |
| 1555 |
fn is_singleton(&self) -> bool { |
| 1556 |
self.ptr.as_ptr() as *const Header == &EMPTY_HEADER |
| 1557 |
} |
| 1558 |
|
| 1559 |
#[cfg(feature = "gecko-ffi")] |
| 1560 |
#[inline] |
| 1561 |
fn has_allocation(&self) -> bool { |
| 1562 |
unsafe { !self.is_singleton() && !self.ptr.as_ref().uses_stack_allocated_buffer() } |
| 1563 |
} |
| 1564 |
|
| 1565 |
#[cfg(not(feature = "gecko-ffi"))] |
| 1566 |
#[inline] |
| 1567 |
fn has_allocation(&self) -> bool { |
| 1568 |
!self.is_singleton() |
| 1569 |
} |
| 1570 |
} |
| 1571 |
|
| 1572 |
impl<T: Clone> ThinVec<T> { |
| 1573 |
/// Resizes the `Vec` in-place so that `len()` is equal to `new_len`. |
| 1574 |
/// |
| 1575 |
/// If `new_len` is greater than `len()`, the `Vec` is extended by the |
| 1576 |
/// difference, with each additional slot filled with `value`. |
| 1577 |
/// If `new_len` is less than `len()`, the `Vec` is simply truncated. |
| 1578 |
/// |
| 1579 |
/// # Examples |
| 1580 |
/// |
| 1581 |
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`. |
| 1582 |
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")] |
| 1583 |
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")] |
| 1584 |
/// # #[macro_use] extern crate thin_vec; |
| 1585 |
/// # fn main() { |
| 1586 |
/// let mut vec = thin_vec!["hello"]; |
| 1587 |
/// vec.resize(3, "world"); |
| 1588 |
/// assert_eq!(vec, ["hello", "world", "world"]); |
| 1589 |
/// |
| 1590 |
/// let mut vec = thin_vec![1, 2, 3, 4]; |
| 1591 |
/// vec.resize(2, 0); |
| 1592 |
/// assert_eq!(vec, [1, 2]); |
| 1593 |
/// # } |
| 1594 |
/// ``` |
| 1595 |
pub fn resize(&mut self, new_len: usize, value: T) { |
| 1596 |
let old_len = self.len(); |
| 1597 |
|
| 1598 |
if new_len > old_len { |
| 1599 |
let additional = new_len - old_len; |
| 1600 |
self.reserve(additional); |
| 1601 |
for _ in 1..additional { |
| 1602 |
self.push(value.clone()); |
| 1603 |
} |
| 1604 |
// We can write the last element directly without cloning needlessly |
| 1605 |
if additional > 0 { |
| 1606 |
self.push(value); |
| 1607 |
} |
| 1608 |
} else if new_len < old_len { |
| 1609 |
self.truncate(new_len); |
| 1610 |
} |
| 1611 |
} |
| 1612 |
|
| 1613 |
/// Clones and appends all elements in a slice to the `ThinVec`. |
| 1614 |
/// |
| 1615 |
/// Iterates over the slice `other`, clones each element, and then appends |
| 1616 |
/// it to this `ThinVec`. The `other` slice is traversed in-order. |
| 1617 |
/// |
| 1618 |
/// Note that this function is same as [`extend`] except that it is |
| 1619 |
/// specialized to work with slices instead. If and when Rust gets |
| 1620 |
/// specialization this function will likely be deprecated (but still |
| 1621 |
/// available). |
| 1622 |
/// |
| 1623 |
/// # Examples |
| 1624 |
/// |
| 1625 |
/// ``` |
| 1626 |
/// use thin_vec::thin_vec; |
| 1627 |
/// |
| 1628 |
/// let mut vec = thin_vec![1]; |
| 1629 |
/// vec.extend_from_slice(&[2, 3, 4]); |
| 1630 |
/// assert_eq!(vec, [1, 2, 3, 4]); |
| 1631 |
/// ``` |
| 1632 |
/// |
| 1633 |
/// [`extend`]: ThinVec::extend |
| 1634 |
pub fn extend_from_slice(&mut self, other: &[T]) { |
| 1635 |
self.extend(other.iter().cloned()) |
| 1636 |
} |
| 1637 |
} |
| 1638 |
|
| 1639 |
impl<T: PartialEq> ThinVec<T> { |
| 1640 |
/// Removes consecutive repeated elements in the vector. |
| 1641 |
/// |
| 1642 |
/// If the vector is sorted, this removes all duplicates. |
| 1643 |
/// |
| 1644 |
/// # Examples |
| 1645 |
/// |
| 1646 |
// A hack to avoid linking problems with `cargo test --features=gecko-ffi`. |
| 1647 |
#[cfg_attr(not(feature = "gecko-ffi"), doc = "```")] |
| 1648 |
#[cfg_attr(feature = "gecko-ffi", doc = "```ignore")] |
| 1649 |
/// # #[macro_use] extern crate thin_vec; |
| 1650 |
/// # fn main() { |
| 1651 |
/// let mut vec = thin_vec![1, 2, 2, 3, 2]; |
| 1652 |
/// |
| 1653 |
/// vec.dedup(); |
| 1654 |
/// |
| 1655 |
/// assert_eq!(vec, [1, 2, 3, 2]); |
| 1656 |
/// # } |
| 1657 |
/// ``` |
| 1658 |
pub fn dedup(&mut self) { |
| 1659 |
self.dedup_by(|a, b| a == b) |
| 1660 |
} |
| 1661 |
} |
| 1662 |
|
| 1663 |
impl<T> Drop for ThinVec<T> { |
| 1664 |
#[inline] |
| 1665 |
fn drop(&mut self) { |
| 1666 |
#[cold] |
| 1667 |
#[inline(never)] |
| 1668 |
fn drop_non_singleton<T>(this: &mut ThinVec<T>) { |
| 1669 |
unsafe { |
| 1670 |
ptr::drop_in_place(&mut this[..]); |
| 1671 |
|
| 1672 |
#[cfg(feature = "gecko-ffi")] |
| 1673 |
if this.ptr.as_ref().uses_stack_allocated_buffer() { |
| 1674 |
return; |
| 1675 |
} |
| 1676 |
|
| 1677 |
dealloc(this.ptr() as *mut u8, layout::<T>(this.capacity())) |
| 1678 |
} |
| 1679 |
} |
| 1680 |
|
| 1681 |
if !self.is_singleton() { |
| 1682 |
drop_non_singleton(self); |
| 1683 |
} |
| 1684 |
} |
| 1685 |
} |
| 1686 |
|
| 1687 |
impl<T> Deref for ThinVec<T> { |
| 1688 |
type Target = [T]; |
| 1689 |
|
| 1690 |
fn deref(&self) -> &[T] { |
| 1691 |
self.as_slice() |
| 1692 |
} |
| 1693 |
} |
| 1694 |
|
| 1695 |
impl<T> DerefMut for ThinVec<T> { |
| 1696 |
fn deref_mut(&mut self) -> &mut [T] { |
| 1697 |
self.as_mut_slice() |
| 1698 |
} |
| 1699 |
} |
| 1700 |
|
| 1701 |
impl<T> Borrow<[T]> for ThinVec<T> { |
| 1702 |
fn borrow(&self) -> &[T] { |
| 1703 |
self.as_slice() |
| 1704 |
} |
| 1705 |
} |
| 1706 |
|
| 1707 |
impl<T> BorrowMut<[T]> for ThinVec<T> { |
| 1708 |
fn borrow_mut(&mut self) -> &mut [T] { |
| 1709 |
self.as_mut_slice() |
| 1710 |
} |
| 1711 |
} |
| 1712 |
|
| 1713 |
impl<T> AsRef<[T]> for ThinVec<T> { |
| 1714 |
fn as_ref(&self) -> &[T] { |
| 1715 |
self.as_slice() |
| 1716 |
} |
| 1717 |
} |
| 1718 |
|
| 1719 |
impl<T> Extend<T> for ThinVec<T> { |
| 1720 |
#[inline] |
| 1721 |
fn extend<I>(&mut self, iter: I) |
| 1722 |
where |
| 1723 |
I: IntoIterator<Item = T>, |
| 1724 |
{ |
| 1725 |
let iter = iter.into_iter(); |
| 1726 |
let hint = iter.size_hint().0; |
| 1727 |
if hint > 0 { |
| 1728 |
self.reserve(hint); |
| 1729 |
} |
| 1730 |
for x in iter { |
| 1731 |
self.push(x); |
| 1732 |
} |
| 1733 |
} |
| 1734 |
} |
| 1735 |
|
| 1736 |
impl<T: fmt::Debug> fmt::Debug for ThinVec<T> { |
| 1737 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1738 |
fmt::Debug::fmt(&**self, f) |
| 1739 |
} |
| 1740 |
} |
| 1741 |
|
| 1742 |
impl<T> Hash for ThinVec<T> |
| 1743 |
where |
| 1744 |
T: Hash, |
| 1745 |
{ |
| 1746 |
fn hash<H>(&self, state: &mut H) |
| 1747 |
where |
| 1748 |
H: Hasher, |
| 1749 |
{ |
| 1750 |
self[..].hash(state); |
| 1751 |
} |
| 1752 |
} |
| 1753 |
|
| 1754 |
impl<T> PartialOrd for ThinVec<T> |
| 1755 |
where |
| 1756 |
T: PartialOrd, |
| 1757 |
{ |
| 1758 |
#[inline] |
| 1759 |
fn partial_cmp(&self, other: &ThinVec<T>) -> Option<Ordering> { |
| 1760 |
self[..].partial_cmp(&other[..]) |
| 1761 |
} |
| 1762 |
} |
| 1763 |
|
| 1764 |
impl<T> Ord for ThinVec<T> |
| 1765 |
where |
| 1766 |
T: Ord, |
| 1767 |
{ |
| 1768 |
#[inline] |
| 1769 |
fn cmp(&self, other: &ThinVec<T>) -> Ordering { |
| 1770 |
self[..].cmp(&other[..]) |
| 1771 |
} |
| 1772 |
} |
| 1773 |
|
| 1774 |
impl<A, B> PartialEq<ThinVec<B>> for ThinVec<A> |
| 1775 |
where |
| 1776 |
A: PartialEq<B>, |
| 1777 |
{ |
| 1778 |
#[inline] |
| 1779 |
fn eq(&self, other: &ThinVec<B>) -> bool { |
| 1780 |
self[..] == other[..] |
| 1781 |
} |
| 1782 |
} |
| 1783 |
|
| 1784 |
impl<A, B> PartialEq<Vec<B>> for ThinVec<A> |
| 1785 |
where |
| 1786 |
A: PartialEq<B>, |
| 1787 |
{ |
| 1788 |
#[inline] |
| 1789 |
fn eq(&self, other: &Vec<B>) -> bool { |
| 1790 |
self[..] == other[..] |
| 1791 |
} |
| 1792 |
} |
| 1793 |
|
| 1794 |
impl<A, B> PartialEq<[B]> for ThinVec<A> |
| 1795 |
where |
| 1796 |
A: PartialEq<B>, |
| 1797 |
{ |
| 1798 |
#[inline] |
| 1799 |
fn eq(&self, other: &[B]) -> bool { |
| 1800 |
self[..] == other[..] |
| 1801 |
} |
| 1802 |
} |
| 1803 |
|
| 1804 |
impl<'a, A, B> PartialEq<&'a [B]> for ThinVec<A> |
| 1805 |
where |
| 1806 |
A: PartialEq<B>, |
| 1807 |
{ |
| 1808 |
#[inline] |
| 1809 |
fn eq(&self, other: &&'a [B]) -> bool { |
| 1810 |
self[..] == other[..] |
| 1811 |
} |
| 1812 |
} |
| 1813 |
|
| 1814 |
// Serde impls based on |
| 1815 |
// https://github.com/bluss/arrayvec/blob/67ec907a98c0f40c4b76066fed3c1af59d35cf6a/src/arrayvec.rs#L1222-L1267 |
| 1816 |
#[cfg(feature = "serde")] |
| 1817 |
impl<T: serde::Serialize> serde::Serialize for ThinVec<T> { |
| 1818 |
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 1819 |
where |
| 1820 |
S: serde::Serializer, |
| 1821 |
{ |
| 1822 |
serializer.collect_seq(self.as_slice()) |
| 1823 |
} |
| 1824 |
} |
| 1825 |
|
| 1826 |
#[cfg(feature = "serde")] |
| 1827 |
impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for ThinVec<T> { |
| 1828 |
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 1829 |
where |
| 1830 |
D: serde::Deserializer<'de>, |
| 1831 |
{ |
| 1832 |
use serde::de::{SeqAccess, Visitor}; |
| 1833 |
use serde::Deserialize; |
| 1834 |
|
| 1835 |
struct ThinVecVisitor<T>(PhantomData<T>); |
| 1836 |
|
| 1837 |
impl<'de, T: Deserialize<'de>> Visitor<'de> for ThinVecVisitor<T> { |
| 1838 |
type Value = ThinVec<T>; |
| 1839 |
|
| 1840 |
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 1841 |
write!(formatter, "a sequence") |
| 1842 |
} |
| 1843 |
|
| 1844 |
fn visit_seq<SA>(self, mut seq: SA) -> Result<Self::Value, SA::Error> |
| 1845 |
where |
| 1846 |
SA: SeqAccess<'de>, |
| 1847 |
{ |
| 1848 |
// Same policy as |
| 1849 |
// https://github.com/serde-rs/serde/blob/ce0844b9ecc32377b5e4545d759d385a8c46bc6a/serde/src/private/size_hint.rs#L13 |
| 1850 |
let initial_capacity = seq.size_hint().unwrap_or_default().min(4096); |
| 1851 |
let mut values = ThinVec::<T>::with_capacity(initial_capacity); |
| 1852 |
|
| 1853 |
while let Some(value) = seq.next_element()? { |
| 1854 |
values.push(value); |
| 1855 |
} |
| 1856 |
|
| 1857 |
Ok(values) |
| 1858 |
} |
| 1859 |
} |
| 1860 |
|
| 1861 |
deserializer.deserialize_seq(ThinVecVisitor::<T>(PhantomData)) |
| 1862 |
} |
| 1863 |
} |
| 1864 |
|
| 1865 |
macro_rules! array_impls { |
| 1866 |
($($N:expr)*) => {$( |
| 1867 |
impl<A, B> PartialEq<[B; $N]> for ThinVec<A> where A: PartialEq<B> { |
| 1868 |
#[inline] |
| 1869 |
fn eq(&self, other: &[B; $N]) -> bool { self[..] == other[..] } |
| 1870 |
} |
| 1871 |
|
| 1872 |
impl<'a, A, B> PartialEq<&'a [B; $N]> for ThinVec<A> where A: PartialEq<B> { |
| 1873 |
#[inline] |
| 1874 |
fn eq(&self, other: &&'a [B; $N]) -> bool { self[..] == other[..] } |
| 1875 |
} |
| 1876 |
)*} |
| 1877 |
} |
| 1878 |
|
| 1879 |
array_impls! { |
| 1880 |
0 1 2 3 4 5 6 7 8 9 |
| 1881 |
10 11 12 13 14 15 16 17 18 19 |
| 1882 |
20 21 22 23 24 25 26 27 28 29 |
| 1883 |
30 31 32 |
| 1884 |
} |
| 1885 |
|
| 1886 |
impl<T> Eq for ThinVec<T> where T: Eq {} |
| 1887 |
|
| 1888 |
impl<T> IntoIterator for ThinVec<T> { |
| 1889 |
type Item = T; |
| 1890 |
type IntoIter = IntoIter<T>; |
| 1891 |
|
| 1892 |
fn into_iter(self) -> IntoIter<T> { |
| 1893 |
IntoIter { |
| 1894 |
vec: self, |
| 1895 |
start: 0, |
| 1896 |
} |
| 1897 |
} |
| 1898 |
} |
| 1899 |
|
| 1900 |
impl<'a, T> IntoIterator for &'a ThinVec<T> { |
| 1901 |
type Item = &'a T; |
| 1902 |
type IntoIter = slice::Iter<'a, T>; |
| 1903 |
|
| 1904 |
fn into_iter(self) -> slice::Iter<'a, T> { |
| 1905 |
self.iter() |
| 1906 |
} |
| 1907 |
} |
| 1908 |
|
| 1909 |
impl<'a, T> IntoIterator for &'a mut ThinVec<T> { |
| 1910 |
type Item = &'a mut T; |
| 1911 |
type IntoIter = slice::IterMut<'a, T>; |
| 1912 |
|
| 1913 |
fn into_iter(self) -> slice::IterMut<'a, T> { |
| 1914 |
self.iter_mut() |
| 1915 |
} |
| 1916 |
} |
| 1917 |
|
| 1918 |
impl<T> Clone for ThinVec<T> |
| 1919 |
where |
| 1920 |
T: Clone, |
| 1921 |
{ |
| 1922 |
#[inline] |
| 1923 |
fn clone(&self) -> ThinVec<T> { |
| 1924 |
#[cold] |
| 1925 |
#[inline(never)] |
| 1926 |
fn clone_non_singleton<T: Clone>(this: &ThinVec<T>) -> ThinVec<T> { |
| 1927 |
let len = this.len(); |
| 1928 |
let mut new_vec = ThinVec::<T>::with_capacity(len); |
| 1929 |
let mut data_raw = new_vec.data_raw(); |
| 1930 |
for x in this.iter() { |
| 1931 |
unsafe { |
| 1932 |
ptr::write(data_raw, x.clone()); |
| 1933 |
data_raw = data_raw.add(1); |
| 1934 |
} |
| 1935 |
} |
| 1936 |
unsafe { |
| 1937 |
// `this` is not the singleton, but `new_vec` will be if |
| 1938 |
// `this` is empty. |
| 1939 |
new_vec.set_len(len); // could be the singleton |
| 1940 |
} |
| 1941 |
new_vec |
| 1942 |
} |
| 1943 |
|
| 1944 |
if self.is_singleton() { |
| 1945 |
ThinVec::new() |
| 1946 |
} else { |
| 1947 |
clone_non_singleton(self) |
| 1948 |
} |
| 1949 |
} |
| 1950 |
} |
| 1951 |
|
| 1952 |
impl<T> Default for ThinVec<T> { |
| 1953 |
fn default() -> ThinVec<T> { |
| 1954 |
ThinVec::new() |
| 1955 |
} |
| 1956 |
} |
| 1957 |
|
| 1958 |
impl<T> FromIterator<T> for ThinVec<T> { |
| 1959 |
#[inline] |
| 1960 |
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> ThinVec<T> { |
| 1961 |
let mut vec = ThinVec::new(); |
| 1962 |
vec.extend(iter.into_iter()); |
| 1963 |
vec |
| 1964 |
} |
| 1965 |
} |
| 1966 |
|
| 1967 |
impl<T: Clone> From<&[T]> for ThinVec<T> { |
| 1968 |
/// Allocate a `ThinVec<T>` and fill it by cloning `s`'s items. |
| 1969 |
/// |
| 1970 |
/// # Examples |
| 1971 |
/// |
| 1972 |
/// ``` |
| 1973 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 1974 |
/// |
| 1975 |
/// assert_eq!(ThinVec::from(&[1, 2, 3][..]), thin_vec![1, 2, 3]); |
| 1976 |
/// ``` |
| 1977 |
fn from(s: &[T]) -> ThinVec<T> { |
| 1978 |
s.iter().cloned().collect() |
| 1979 |
} |
| 1980 |
} |
| 1981 |
|
| 1982 |
#[cfg(not(no_global_oom_handling))] |
| 1983 |
impl<T: Clone> From<&mut [T]> for ThinVec<T> { |
| 1984 |
/// Allocate a `ThinVec<T>` and fill it by cloning `s`'s items. |
| 1985 |
/// |
| 1986 |
/// # Examples |
| 1987 |
/// |
| 1988 |
/// ``` |
| 1989 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 1990 |
/// |
| 1991 |
/// assert_eq!(ThinVec::from(&mut [1, 2, 3][..]), thin_vec![1, 2, 3]); |
| 1992 |
/// ``` |
| 1993 |
fn from(s: &mut [T]) -> ThinVec<T> { |
| 1994 |
s.iter().cloned().collect() |
| 1995 |
} |
| 1996 |
} |
| 1997 |
|
| 1998 |
impl<T, const N: usize> From<[T; N]> for ThinVec<T> { |
| 1999 |
/// Allocate a `ThinVec<T>` and move `s`'s items into it. |
| 2000 |
/// |
| 2001 |
/// # Examples |
| 2002 |
/// |
| 2003 |
/// ``` |
| 2004 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2005 |
/// |
| 2006 |
/// assert_eq!(ThinVec::from([1, 2, 3]), thin_vec![1, 2, 3]); |
| 2007 |
/// ``` |
| 2008 |
fn from(s: [T; N]) -> ThinVec<T> { |
| 2009 |
std::iter::IntoIterator::into_iter(s).collect() |
| 2010 |
} |
| 2011 |
} |
| 2012 |
|
| 2013 |
impl<T> From<Box<[T]>> for ThinVec<T> { |
| 2014 |
/// Convert a boxed slice into a vector by transferring ownership of |
| 2015 |
/// the existing heap allocation. |
| 2016 |
/// |
| 2017 |
/// **NOTE:** unlike `std`, this must reallocate to change the layout! |
| 2018 |
/// |
| 2019 |
/// # Examples |
| 2020 |
/// |
| 2021 |
/// ``` |
| 2022 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2023 |
/// |
| 2024 |
/// let b: Box<[i32]> = thin_vec![1, 2, 3].into_iter().collect(); |
| 2025 |
/// assert_eq!(ThinVec::from(b), thin_vec![1, 2, 3]); |
| 2026 |
/// ``` |
| 2027 |
fn from(s: Box<[T]>) -> Self { |
| 2028 |
// Can just lean on the fact that `Box<[T]>` -> `Vec<T>` is Free. |
| 2029 |
Vec::from(s).into_iter().collect() |
| 2030 |
} |
| 2031 |
} |
| 2032 |
|
| 2033 |
impl<T> From<Vec<T>> for ThinVec<T> { |
| 2034 |
/// Convert a `std::Vec` into a `ThinVec`. |
| 2035 |
/// |
| 2036 |
/// **NOTE:** this must reallocate to change the layout! |
| 2037 |
/// |
| 2038 |
/// # Examples |
| 2039 |
/// |
| 2040 |
/// ``` |
| 2041 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2042 |
/// |
| 2043 |
/// let b: Vec<i32> = vec![1, 2, 3]; |
| 2044 |
/// assert_eq!(ThinVec::from(b), thin_vec![1, 2, 3]); |
| 2045 |
/// ``` |
| 2046 |
fn from(s: Vec<T>) -> Self { |
| 2047 |
s.into_iter().collect() |
| 2048 |
} |
| 2049 |
} |
| 2050 |
|
| 2051 |
impl<T> From<ThinVec<T>> for Vec<T> { |
| 2052 |
/// Convert a `ThinVec` into a `std::Vec`. |
| 2053 |
/// |
| 2054 |
/// **NOTE:** this must reallocate to change the layout! |
| 2055 |
/// |
| 2056 |
/// # Examples |
| 2057 |
/// |
| 2058 |
/// ``` |
| 2059 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2060 |
/// |
| 2061 |
/// let b: ThinVec<i32> = thin_vec![1, 2, 3]; |
| 2062 |
/// assert_eq!(Vec::from(b), vec![1, 2, 3]); |
| 2063 |
/// ``` |
| 2064 |
fn from(s: ThinVec<T>) -> Self { |
| 2065 |
s.into_iter().collect() |
| 2066 |
} |
| 2067 |
} |
| 2068 |
|
| 2069 |
impl<T> From<ThinVec<T>> for Box<[T]> { |
| 2070 |
/// Convert a vector into a boxed slice. |
| 2071 |
/// |
| 2072 |
/// If `v` has excess capacity, its items will be moved into a |
| 2073 |
/// newly-allocated buffer with exactly the right capacity. |
| 2074 |
/// |
| 2075 |
/// **NOTE:** unlike `std`, this must reallocate to change the layout! |
| 2076 |
/// |
| 2077 |
/// # Examples |
| 2078 |
/// |
| 2079 |
/// ``` |
| 2080 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2081 |
/// assert_eq!(Box::from(thin_vec![1, 2, 3]), thin_vec![1, 2, 3].into_iter().collect()); |
| 2082 |
/// ``` |
| 2083 |
fn from(v: ThinVec<T>) -> Self { |
| 2084 |
v.into_iter().collect() |
| 2085 |
} |
| 2086 |
} |
| 2087 |
|
| 2088 |
impl From<&str> for ThinVec<u8> { |
| 2089 |
/// Allocate a `ThinVec<u8>` and fill it with a UTF-8 string. |
| 2090 |
/// |
| 2091 |
/// # Examples |
| 2092 |
/// |
| 2093 |
/// ``` |
| 2094 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2095 |
/// |
| 2096 |
/// assert_eq!(ThinVec::from("123"), thin_vec![b'1', b'2', b'3']); |
| 2097 |
/// ``` |
| 2098 |
fn from(s: &str) -> ThinVec<u8> { |
| 2099 |
From::from(s.as_bytes()) |
| 2100 |
} |
| 2101 |
} |
| 2102 |
|
| 2103 |
impl<T, const N: usize> TryFrom<ThinVec<T>> for [T; N] { |
| 2104 |
type Error = ThinVec<T>; |
| 2105 |
|
| 2106 |
/// Gets the entire contents of the `ThinVec<T>` as an array, |
| 2107 |
/// if its size exactly matches that of the requested array. |
| 2108 |
/// |
| 2109 |
/// # Examples |
| 2110 |
/// |
| 2111 |
/// ``` |
| 2112 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2113 |
/// use std::convert::TryInto; |
| 2114 |
/// |
| 2115 |
/// assert_eq!(thin_vec![1, 2, 3].try_into(), Ok([1, 2, 3])); |
| 2116 |
/// assert_eq!(<ThinVec<i32>>::new().try_into(), Ok([])); |
| 2117 |
/// ``` |
| 2118 |
/// |
| 2119 |
/// If the length doesn't match, the input comes back in `Err`: |
| 2120 |
/// ``` |
| 2121 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2122 |
/// use std::convert::TryInto; |
| 2123 |
/// |
| 2124 |
/// let r: Result<[i32; 4], _> = (0..10).collect::<ThinVec<_>>().try_into(); |
| 2125 |
/// assert_eq!(r, Err(thin_vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); |
| 2126 |
/// ``` |
| 2127 |
/// |
| 2128 |
/// If you're fine with just getting a prefix of the `ThinVec<T>`, |
| 2129 |
/// you can call [`.truncate(N)`](ThinVec::truncate) first. |
| 2130 |
/// ``` |
| 2131 |
/// use thin_vec::{ThinVec, thin_vec}; |
| 2132 |
/// use std::convert::TryInto; |
| 2133 |
/// |
| 2134 |
/// let mut v = ThinVec::from("hello world"); |
| 2135 |
/// v.sort(); |
| 2136 |
/// v.truncate(2); |
| 2137 |
/// let [a, b]: [_; 2] = v.try_into().unwrap(); |
| 2138 |
/// assert_eq!(a, b' '); |
| 2139 |
/// assert_eq!(b, b'd'); |
| 2140 |
/// ``` |
| 2141 |
fn try_from(mut vec: ThinVec<T>) -> Result<[T; N], ThinVec<T>> { |
| 2142 |
if vec.len() != N { |
| 2143 |
return Err(vec); |
| 2144 |
} |
| 2145 |
|
| 2146 |
// SAFETY: `.set_len(0)` is always sound. |
| 2147 |
unsafe { vec.set_len(0) }; |
| 2148 |
|
| 2149 |
// SAFETY: A `ThinVec`'s pointer is always aligned properly, and |
| 2150 |
// the alignment the array needs is the same as the items. |
| 2151 |
// We checked earlier that we have sufficient items. |
| 2152 |
// The items will not double-drop as the `set_len` |
| 2153 |
// tells the `ThinVec` not to also drop them. |
| 2154 |
let array = unsafe { ptr::read(vec.data_raw() as *const [T; N]) }; |
| 2155 |
Ok(array) |
| 2156 |
} |
| 2157 |
} |
| 2158 |
|
| 2159 |
/// An iterator that moves out of a vector. |
| 2160 |
/// |
| 2161 |
/// This `struct` is created by the [`ThinVec::into_iter`][] |
| 2162 |
/// (provided by the [`IntoIterator`] trait). |
| 2163 |
/// |
| 2164 |
/// # Example |
| 2165 |
/// |
| 2166 |
/// ``` |
| 2167 |
/// use thin_vec::thin_vec; |
| 2168 |
/// |
| 2169 |
/// let v = thin_vec![0, 1, 2]; |
| 2170 |
/// let iter: thin_vec::IntoIter<_> = v.into_iter(); |
| 2171 |
/// ``` |
| 2172 |
pub struct IntoIter<T> { |
| 2173 |
vec: ThinVec<T>, |
| 2174 |
start: usize, |
| 2175 |
} |
| 2176 |
|
| 2177 |
impl<T> IntoIter<T> { |
| 2178 |
/// Returns the remaining items of this iterator as a slice. |
| 2179 |
/// |
| 2180 |
/// # Examples |
| 2181 |
/// |
| 2182 |
/// ``` |
| 2183 |
/// use thin_vec::thin_vec; |
| 2184 |
/// |
| 2185 |
/// let vec = thin_vec!['a', 'b', 'c']; |
| 2186 |
/// let mut into_iter = vec.into_iter(); |
| 2187 |
/// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); |
| 2188 |
/// let _ = into_iter.next().unwrap(); |
| 2189 |
/// assert_eq!(into_iter.as_slice(), &['b', 'c']); |
| 2190 |
/// ``` |
| 2191 |
pub fn as_slice(&self) -> &[T] { |
| 2192 |
unsafe { slice::from_raw_parts(self.vec.data_raw().add(self.start), self.len()) } |
| 2193 |
} |
| 2194 |
|
| 2195 |
/// Returns the remaining items of this iterator as a mutable slice. |
| 2196 |
/// |
| 2197 |
/// # Examples |
| 2198 |
/// |
| 2199 |
/// ``` |
| 2200 |
/// use thin_vec::thin_vec; |
| 2201 |
/// |
| 2202 |
/// let vec = thin_vec!['a', 'b', 'c']; |
| 2203 |
/// let mut into_iter = vec.into_iter(); |
| 2204 |
/// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); |
| 2205 |
/// into_iter.as_mut_slice()[2] = 'z'; |
| 2206 |
/// assert_eq!(into_iter.next().unwrap(), 'a'); |
| 2207 |
/// assert_eq!(into_iter.next().unwrap(), 'b'); |
| 2208 |
/// assert_eq!(into_iter.next().unwrap(), 'z'); |
| 2209 |
/// ``` |
| 2210 |
pub fn as_mut_slice(&mut self) -> &mut [T] { |
| 2211 |
unsafe { &mut *self.as_raw_mut_slice() } |
| 2212 |
} |
| 2213 |
|
| 2214 |
fn as_raw_mut_slice(&mut self) -> *mut [T] { |
| 2215 |
unsafe { ptr::slice_from_raw_parts_mut(self.vec.data_raw().add(self.start), self.len()) } |
| 2216 |
} |
| 2217 |
} |
| 2218 |
|
| 2219 |
impl<T> Iterator for IntoIter<T> { |
| 2220 |
type Item = T; |
| 2221 |
fn next(&mut self) -> Option<T> { |
| 2222 |
if self.start == self.vec.len() { |
| 2223 |
None |
| 2224 |
} else { |
| 2225 |
unsafe { |
| 2226 |
let old_start = self.start; |
| 2227 |
self.start += 1; |
| 2228 |
Some(ptr::read(self.vec.data_raw().add(old_start))) |
| 2229 |
} |
| 2230 |
} |
| 2231 |
} |
| 2232 |
|
| 2233 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 2234 |
let len = self.vec.len() - self.start; |
| 2235 |
(len, Some(len)) |
| 2236 |
} |
| 2237 |
} |
| 2238 |
|
| 2239 |
impl<T> DoubleEndedIterator for IntoIter<T> { |
| 2240 |
fn next_back(&mut self) -> Option<T> { |
| 2241 |
if self.start == self.vec.len() { |
| 2242 |
None |
| 2243 |
} else { |
| 2244 |
self.vec.pop() |
| 2245 |
} |
| 2246 |
} |
| 2247 |
} |
| 2248 |
|
| 2249 |
impl<T> ExactSizeIterator for IntoIter<T> {} |
| 2250 |
|
| 2251 |
impl<T> std::iter::FusedIterator for IntoIter<T> {} |
| 2252 |
|
| 2253 |
// SAFETY: the length calculation is trivial, we're an array! And if it's wrong we're So Screwed. |
| 2254 |
#[cfg(feature = "unstable")] |
| 2255 |
unsafe impl<T> std::iter::TrustedLen for IntoIter<T> {} |
| 2256 |
|
| 2257 |
impl<T> Drop for IntoIter<T> { |
| 2258 |
#[inline] |
| 2259 |
fn drop(&mut self) { |
| 2260 |
#[cold] |
| 2261 |
#[inline(never)] |
| 2262 |
fn drop_non_singleton<T>(this: &mut IntoIter<T>) { |
| 2263 |
unsafe { |
| 2264 |
let mut vec = mem::replace(&mut this.vec, ThinVec::new()); |
| 2265 |
ptr::drop_in_place(&mut vec[this.start..]); |
| 2266 |
vec.set_len_non_singleton(0) |
| 2267 |
} |
| 2268 |
} |
| 2269 |
|
| 2270 |
if !self.vec.is_singleton() { |
| 2271 |
drop_non_singleton(self); |
| 2272 |
} |
| 2273 |
} |
| 2274 |
} |
| 2275 |
|
| 2276 |
impl<T: fmt::Debug> fmt::Debug for IntoIter<T> { |
| 2277 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2278 |
f.debug_tuple("IntoIter").field(&self.as_slice()).finish() |
| 2279 |
} |
| 2280 |
} |
| 2281 |
|
| 2282 |
impl<T> AsRef<[T]> for IntoIter<T> { |
| 2283 |
fn as_ref(&self) -> &[T] { |
| 2284 |
self.as_slice() |
| 2285 |
} |
| 2286 |
} |
| 2287 |
|
| 2288 |
impl<T: Clone> Clone for IntoIter<T> { |
| 2289 |
#[allow(clippy::into_iter_on_ref)] |
| 2290 |
fn clone(&self) -> Self { |
| 2291 |
// Just create a new `ThinVec` from the remaining elements and IntoIter it |
| 2292 |
self.as_slice() |
| 2293 |
.into_iter() |
| 2294 |
.cloned() |
| 2295 |
.collect::<ThinVec<_>>() |
| 2296 |
.into_iter() |
| 2297 |
} |
| 2298 |
} |
| 2299 |
|
| 2300 |
/// A draining iterator for `ThinVec<T>`. |
| 2301 |
/// |
| 2302 |
/// This `struct` is created by [`ThinVec::drain`]. |
| 2303 |
/// See its documentation for more. |
| 2304 |
/// |
| 2305 |
/// # Example |
| 2306 |
/// |
| 2307 |
/// ``` |
| 2308 |
/// use thin_vec::thin_vec; |
| 2309 |
/// |
| 2310 |
/// let mut v = thin_vec![0, 1, 2]; |
| 2311 |
/// let iter: thin_vec::Drain<_> = v.drain(..); |
| 2312 |
/// ``` |
| 2313 |
pub struct Drain<'a, T> { |
| 2314 |
// Ok so ThinVec::drain takes a range of the ThinVec and yields the contents by-value, |
| 2315 |
// then backshifts the array. During iteration the array is in an unsound state |
| 2316 |
// (big deinitialized hole in it), and this is very dangerous. |
| 2317 |
// |
| 2318 |
// Our first line of defense is the borrow checker: we have a mutable borrow, so nothing |
| 2319 |
// can access the ThinVec while we exist. As long as we make sure the ThinVec is in a valid |
| 2320 |
// state again before we release the borrow, everything should be A-OK! We do this cleanup |
| 2321 |
// in our Drop impl. |
| 2322 |
// |
| 2323 |
// Unfortunately, that's unsound, because mem::forget exists and The Leakpocalypse Is Real. |
| 2324 |
// So we can't actually guarantee our destructor runs before our borrow expires. Thankfully |
| 2325 |
// this isn't fatal: we can just set the ThinVec's len to 0 at the start, so if anyone |
| 2326 |
// leaks the Drain, we just leak everything the ThinVec contained out of spite! If they |
| 2327 |
// *don't* leak us then we can properly repair the len in our Drop impl. This is known |
| 2328 |
// as "leak amplification", and is the same approach std uses. |
| 2329 |
// |
| 2330 |
// But we can do slightly better than setting the len to 0! The drain breaks us up into |
| 2331 |
// these parts: |
| 2332 |
// |
| 2333 |
// ```text |
| 2334 |
// |
| 2335 |
// [A, B, C, D, E, F, G, H, _, _] |
| 2336 |
// ____ __________ ____ ____ |
| 2337 |
// | | | | |
| 2338 |
// prefix drain tail spare-cap |
| 2339 |
// ``` |
| 2340 |
// |
| 2341 |
// As the drain iterator is consumed from both ends (DoubleEnded!), we'll start to look |
| 2342 |
// like this: |
| 2343 |
// |
| 2344 |
// ```text |
| 2345 |
// [A, B, _, _, E, _, G, H, _, _] |
| 2346 |
// ____ __________ ____ ____ |
| 2347 |
// | | | | |
| 2348 |
// prefix drain tail spare-cap |
| 2349 |
// ``` |
| 2350 |
// |
| 2351 |
// Note that the prefix is always valid and untouched, as such we can set the len |
| 2352 |
// to the prefix when doing leak-amplification. As a bonus, we can use this value |
| 2353 |
// to remember where the drain range starts. At the end we'll look like this |
| 2354 |
// (we exhaust ourselves in our Drop impl): |
| 2355 |
// |
| 2356 |
// ```text |
| 2357 |
// [A, B, _, _, _, _, G, H, _, _] |
| 2358 |
// _____ __________ _____ ____ |
| 2359 |
// | | | | |
| 2360 |
// len drain tail spare-cap |
| 2361 |
// ``` |
| 2362 |
// |
| 2363 |
// And need to become this: |
| 2364 |
// |
| 2365 |
// ```text |
| 2366 |
// [A, B, G, H, _, _, _, _, _, _] |
| 2367 |
// ___________ ________________ |
| 2368 |
// | | |
| 2369 |
// len spare-cap |
| 2370 |
// ``` |
| 2371 |
// |
| 2372 |
// All this requires is moving the tail back to the prefix (stored in `len`) |
| 2373 |
// and setting `len` to `len + tail_len` to undo the leak amplification. |
| 2374 |
/// An iterator over the elements we're removing. |
| 2375 |
/// |
| 2376 |
/// As we go we'll be `read`ing out of the mutable refs yielded by this. |
| 2377 |
/// It's ok to use IterMut here because it promises to only take mutable |
| 2378 |
/// refs to the parts we haven't yielded yet. |
| 2379 |
/// |
| 2380 |
/// A downside of this (and the *mut below) is that it makes this type invariant, when |
| 2381 |
/// technically it could be covariant? |
| 2382 |
iter: IterMut<'a, T>, |
| 2383 |
/// The actual ThinVec, which we need to hold onto to undo the leak amplification |
| 2384 |
/// and backshift the tail into place. This should only be accessed when we're |
| 2385 |
/// completely done with the IterMut in the `drop` impl of this type (or miri will get mad). |
| 2386 |
/// |
| 2387 |
/// Since we set the `len` of this to be before `IterMut`, we can use that `len` |
| 2388 |
/// to retrieve the index of the start of the drain range later. |
| 2389 |
vec: *mut ThinVec<T>, |
| 2390 |
/// The one-past-the-end index of the drain range, or equivalently the start of the tail. |
| 2391 |
end: usize, |
| 2392 |
/// The length of the tail. |
| 2393 |
tail: usize, |
| 2394 |
} |
| 2395 |
|
| 2396 |
impl<'a, T> Iterator for Drain<'a, T> { |
| 2397 |
type Item = T; |
| 2398 |
fn next(&mut self) -> Option<T> { |
| 2399 |
self.iter.next().map(|x| unsafe { ptr::read(x) }) |
| 2400 |
} |
| 2401 |
|
| 2402 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 2403 |
self.iter.size_hint() |
| 2404 |
} |
| 2405 |
} |
| 2406 |
|
| 2407 |
impl<'a, T> DoubleEndedIterator for Drain<'a, T> { |
| 2408 |
fn next_back(&mut self) -> Option<T> { |
| 2409 |
self.iter.next_back().map(|x| unsafe { ptr::read(x) }) |
| 2410 |
} |
| 2411 |
} |
| 2412 |
|
| 2413 |
impl<'a, T> ExactSizeIterator for Drain<'a, T> {} |
| 2414 |
|
| 2415 |
// SAFETY: we need to keep track of this perfectly Or Else anyway! |
| 2416 |
#[cfg(feature = "unstable")] |
| 2417 |
unsafe impl<T> std::iter::TrustedLen for Drain<'_, T> {} |
| 2418 |
|
| 2419 |
impl<T> std::iter::FusedIterator for Drain<'_, T> {} |
| 2420 |
|
| 2421 |
impl<'a, T> Drop for Drain<'a, T> { |
| 2422 |
fn drop(&mut self) { |
| 2423 |
// Consume the rest of the iterator. |
| 2424 |
for _ in self.by_ref() {} |
| 2425 |
|
| 2426 |
// Move the tail over the drained items, and update the length. |
| 2427 |
unsafe { |
| 2428 |
let vec = &mut *self.vec; |
| 2429 |
|
| 2430 |
// Don't mutate the empty singleton! |
| 2431 |
if !vec.is_singleton() { |
| 2432 |
let old_len = vec.len(); |
| 2433 |
let start = vec.data_raw().add(old_len); |
| 2434 |
let end = vec.data_raw().add(self.end); |
| 2435 |
ptr::copy(end, start, self.tail); |
| 2436 |
vec.set_len_non_singleton(old_len + self.tail); |
| 2437 |
} |
| 2438 |
} |
| 2439 |
} |
| 2440 |
} |
| 2441 |
|
| 2442 |
impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> { |
| 2443 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2444 |
f.debug_tuple("Drain").field(&self.iter.as_slice()).finish() |
| 2445 |
} |
| 2446 |
} |
| 2447 |
|
| 2448 |
impl<'a, T> Drain<'a, T> { |
| 2449 |
/// Returns the remaining items of this iterator as a slice. |
| 2450 |
/// |
| 2451 |
/// # Examples |
| 2452 |
/// |
| 2453 |
/// ``` |
| 2454 |
/// use thin_vec::thin_vec; |
| 2455 |
/// |
| 2456 |
/// let mut vec = thin_vec!['a', 'b', 'c']; |
| 2457 |
/// let mut drain = vec.drain(..); |
| 2458 |
/// assert_eq!(drain.as_slice(), &['a', 'b', 'c']); |
| 2459 |
/// let _ = drain.next().unwrap(); |
| 2460 |
/// assert_eq!(drain.as_slice(), &['b', 'c']); |
| 2461 |
/// ``` |
| 2462 |
#[must_use] |
| 2463 |
pub fn as_slice(&self) -> &[T] { |
| 2464 |
// SAFETY: this is A-OK because the elements that the underlying |
| 2465 |
// iterator still points at are still logically initialized and contiguous. |
| 2466 |
self.iter.as_slice() |
| 2467 |
} |
| 2468 |
} |
| 2469 |
|
| 2470 |
impl<'a, T> AsRef<[T]> for Drain<'a, T> { |
| 2471 |
fn as_ref(&self) -> &[T] { |
| 2472 |
self.as_slice() |
| 2473 |
} |
| 2474 |
} |
| 2475 |
|
| 2476 |
/// A splicing iterator for `ThinVec`. |
| 2477 |
/// |
| 2478 |
/// This struct is created by [`ThinVec::splice`][]. |
| 2479 |
/// See its documentation for more. |
| 2480 |
/// |
| 2481 |
/// # Example |
| 2482 |
/// |
| 2483 |
/// ``` |
| 2484 |
/// use thin_vec::thin_vec; |
| 2485 |
/// |
| 2486 |
/// let mut v = thin_vec![0, 1, 2]; |
| 2487 |
/// let new = [7, 8]; |
| 2488 |
/// let iter: thin_vec::Splice<_> = v.splice(1.., new); |
| 2489 |
/// ``` |
| 2490 |
#[derive(Debug)] |
| 2491 |
pub struct Splice<'a, I: Iterator + 'a> { |
| 2492 |
drain: Drain<'a, I::Item>, |
| 2493 |
replace_with: I, |
| 2494 |
} |
| 2495 |
|
| 2496 |
impl<I: Iterator> Iterator for Splice<'_, I> { |
| 2497 |
type Item = I::Item; |
| 2498 |
|
| 2499 |
fn next(&mut self) -> Option<Self::Item> { |
| 2500 |
self.drain.next() |
| 2501 |
} |
| 2502 |
|
| 2503 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 2504 |
self.drain.size_hint() |
| 2505 |
} |
| 2506 |
} |
| 2507 |
|
| 2508 |
impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> { |
| 2509 |
fn next_back(&mut self) -> Option<Self::Item> { |
| 2510 |
self.drain.next_back() |
| 2511 |
} |
| 2512 |
} |
| 2513 |
|
| 2514 |
impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {} |
| 2515 |
|
| 2516 |
impl<I: Iterator> Drop for Splice<'_, I> { |
| 2517 |
fn drop(&mut self) { |
| 2518 |
// Ensure we've fully drained out the range |
| 2519 |
self.drain.by_ref().for_each(drop); |
| 2520 |
|
| 2521 |
unsafe { |
| 2522 |
// If there's no tail elements, then the inner ThinVec is already |
| 2523 |
// correct and we can just extend it like normal. |
| 2524 |
if self.drain.tail == 0 { |
| 2525 |
(*self.drain.vec).extend(self.replace_with.by_ref()); |
| 2526 |
return; |
| 2527 |
} |
| 2528 |
|
| 2529 |
// First fill the range left by drain(). |
| 2530 |
if !self.drain.fill(&mut self.replace_with) { |
| 2531 |
return; |
| 2532 |
} |
| 2533 |
|
| 2534 |
// There may be more elements. Use the lower bound as an estimate. |
| 2535 |
let (lower_bound, _upper_bound) = self.replace_with.size_hint(); |
| 2536 |
if lower_bound > 0 { |
| 2537 |
self.drain.move_tail(lower_bound); |
| 2538 |
if !self.drain.fill(&mut self.replace_with) { |
| 2539 |
return; |
| 2540 |
} |
| 2541 |
} |
| 2542 |
|
| 2543 |
// Collect any remaining elements. |
| 2544 |
// This is a zero-length vector which does not allocate if `lower_bound` was exact. |
| 2545 |
let mut collected = self |
| 2546 |
.replace_with |
| 2547 |
.by_ref() |
| 2548 |
.collect::<Vec<I::Item>>() |
| 2549 |
.into_iter(); |
| 2550 |
// Now we have an exact count. |
| 2551 |
if collected.len() > 0 { |
| 2552 |
self.drain.move_tail(collected.len()); |
| 2553 |
let filled = self.drain.fill(&mut collected); |
| 2554 |
debug_assert!(filled); |
| 2555 |
debug_assert_eq!(collected.len(), 0); |
| 2556 |
} |
| 2557 |
} |
| 2558 |
// Let `Drain::drop` move the tail back if necessary and restore `vec.len`. |
| 2559 |
} |
| 2560 |
} |
| 2561 |
|
| 2562 |
/// Private helper methods for `Splice::drop` |
| 2563 |
impl<T> Drain<'_, T> { |
| 2564 |
/// The range from `self.vec.len` to `self.tail_start` contains elements |
| 2565 |
/// that have been moved out. |
| 2566 |
/// Fill that range as much as possible with new elements from the `replace_with` iterator. |
| 2567 |
/// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.) |
| 2568 |
unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool { |
| 2569 |
let vec = unsafe { &mut *self.vec }; |
| 2570 |
let range_start = vec.len(); |
| 2571 |
let range_end = self.end; |
| 2572 |
let range_slice = unsafe { |
| 2573 |
slice::from_raw_parts_mut(vec.data_raw().add(range_start), range_end - range_start) |
| 2574 |
}; |
| 2575 |
|
| 2576 |
for place in range_slice { |
| 2577 |
if let Some(new_item) = replace_with.next() { |
| 2578 |
unsafe { ptr::write(place, new_item) }; |
| 2579 |
vec.set_len(vec.len() + 1); |
| 2580 |
} else { |
| 2581 |
return false; |
| 2582 |
} |
| 2583 |
} |
| 2584 |
true |
| 2585 |
} |
| 2586 |
|
| 2587 |
/// Makes room for inserting more elements before the tail. |
| 2588 |
unsafe fn move_tail(&mut self, additional: usize) { |
| 2589 |
let vec = unsafe { &mut *self.vec }; |
| 2590 |
let len = self.end + self.tail; |
| 2591 |
vec.reserve(len.checked_add(additional).expect("capacity overflow")); |
| 2592 |
|
| 2593 |
let new_tail_start = self.end + additional; |
| 2594 |
unsafe { |
| 2595 |
let src = vec.data_raw().add(self.end); |
| 2596 |
let dst = vec.data_raw().add(new_tail_start); |
| 2597 |
ptr::copy(src, dst, self.tail); |
| 2598 |
} |
| 2599 |
self.end = new_tail_start; |
| 2600 |
} |
| 2601 |
} |
| 2602 |
|
| 2603 |
/// Write is implemented for `ThinVec<u8>` by appending to the vector. |
| 2604 |
/// The vector will grow as needed. |
| 2605 |
/// This implementation is identical to the one for `Vec<u8>`. |
| 2606 |
impl io::Write for ThinVec<u8> { |
| 2607 |
#[inline] |
| 2608 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 2609 |
self.extend_from_slice(buf); |
| 2610 |
Ok(buf.len()) |
| 2611 |
} |
| 2612 |
|
| 2613 |
#[inline] |
| 2614 |
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { |
| 2615 |
self.extend_from_slice(buf); |
| 2616 |
Ok(()) |
| 2617 |
} |
| 2618 |
|
| 2619 |
#[inline] |
| 2620 |
fn flush(&mut self) -> io::Result<()> { |
| 2621 |
Ok(()) |
| 2622 |
} |
| 2623 |
} |
| 2624 |
|
| 2625 |
// TODO: a million Index impls |
| 2626 |
|
| 2627 |
#[cfg(test)] |
| 2628 |
mod tests { |
| 2629 |
use super::{ThinVec, MAX_CAP}; |
| 2630 |
|
| 2631 |
#[test] |
| 2632 |
fn test_size_of() { |
| 2633 |
use std::mem::size_of; |
| 2634 |
assert_eq!(size_of::<ThinVec<u8>>(), size_of::<&u8>()); |
| 2635 |
|
| 2636 |
assert_eq!(size_of::<Option<ThinVec<u8>>>(), size_of::<&u8>()); |
| 2637 |
} |
| 2638 |
|
| 2639 |
#[test] |
| 2640 |
fn test_drop_empty() { |
| 2641 |
ThinVec::<u8>::new(); |
| 2642 |
} |
| 2643 |
|
| 2644 |
#[test] |
| 2645 |
fn test_data_ptr_alignment() { |
| 2646 |
let v = ThinVec::<u16>::new(); |
| 2647 |
assert!(v.data_raw() as usize % 2 == 0); |
| 2648 |
|
| 2649 |
let v = ThinVec::<u32>::new(); |
| 2650 |
assert!(v.data_raw() as usize % 4 == 0); |
| 2651 |
|
| 2652 |
let v = ThinVec::<u64>::new(); |
| 2653 |
assert!(v.data_raw() as usize % 8 == 0); |
| 2654 |
} |
| 2655 |
|
| 2656 |
#[test] |
| 2657 |
#[cfg_attr(feature = "gecko-ffi", should_panic)] |
| 2658 |
fn test_overaligned_type_is_rejected_for_gecko_ffi_mode() { |
| 2659 |
#[repr(align(16))] |
| 2660 |
struct Align16(u8); |
| 2661 |
|
| 2662 |
let v = ThinVec::<Align16>::new(); |
| 2663 |
assert!(v.data_raw() as usize % 16 == 0); |
| 2664 |
} |
| 2665 |
|
| 2666 |
#[test] |
| 2667 |
fn test_partial_eq() { |
| 2668 |
assert_eq!(thin_vec![0], thin_vec![0]); |
| 2669 |
assert_ne!(thin_vec![0], thin_vec![1]); |
| 2670 |
assert_eq!(thin_vec![1, 2, 3], vec![1, 2, 3]); |
| 2671 |
} |
| 2672 |
|
| 2673 |
#[test] |
| 2674 |
fn test_alloc() { |
| 2675 |
let mut v = ThinVec::new(); |
| 2676 |
assert!(!v.has_allocation()); |
| 2677 |
v.push(1); |
| 2678 |
assert!(v.has_allocation()); |
| 2679 |
v.pop(); |
| 2680 |
assert!(v.has_allocation()); |
| 2681 |
v.shrink_to_fit(); |
| 2682 |
assert!(!v.has_allocation()); |
| 2683 |
v.reserve(64); |
| 2684 |
assert!(v.has_allocation()); |
| 2685 |
v = ThinVec::with_capacity(64); |
| 2686 |
assert!(v.has_allocation()); |
| 2687 |
v = ThinVec::with_capacity(0); |
| 2688 |
assert!(!v.has_allocation()); |
| 2689 |
} |
| 2690 |
|
| 2691 |
#[test] |
| 2692 |
fn test_drain_items() { |
| 2693 |
let mut vec = thin_vec![1, 2, 3]; |
| 2694 |
let mut vec2 = thin_vec![]; |
| 2695 |
for i in vec.drain(..) { |
| 2696 |
vec2.push(i); |
| 2697 |
} |
| 2698 |
assert_eq!(vec, []); |
| 2699 |
assert_eq!(vec2, [1, 2, 3]); |
| 2700 |
} |
| 2701 |
|
| 2702 |
#[test] |
| 2703 |
fn test_drain_items_reverse() { |
| 2704 |
let mut vec = thin_vec![1, 2, 3]; |
| 2705 |
let mut vec2 = thin_vec![]; |
| 2706 |
for i in vec.drain(..).rev() { |
| 2707 |
vec2.push(i); |
| 2708 |
} |
| 2709 |
assert_eq!(vec, []); |
| 2710 |
assert_eq!(vec2, [3, 2, 1]); |
| 2711 |
} |
| 2712 |
|
| 2713 |
#[test] |
| 2714 |
fn test_drain_items_zero_sized() { |
| 2715 |
let mut vec = thin_vec![(), (), ()]; |
| 2716 |
let mut vec2 = thin_vec![]; |
| 2717 |
for i in vec.drain(..) { |
| 2718 |
vec2.push(i); |
| 2719 |
} |
| 2720 |
assert_eq!(vec, []); |
| 2721 |
assert_eq!(vec2, [(), (), ()]); |
| 2722 |
} |
| 2723 |
|
| 2724 |
#[test] |
| 2725 |
#[should_panic] |
| 2726 |
fn test_drain_out_of_bounds() { |
| 2727 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 2728 |
v.drain(5..6); |
| 2729 |
} |
| 2730 |
|
| 2731 |
#[test] |
| 2732 |
fn test_drain_range() { |
| 2733 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 2734 |
for _ in v.drain(4..) {} |
| 2735 |
assert_eq!(v, &[1, 2, 3, 4]); |
| 2736 |
|
| 2737 |
let mut v: ThinVec<_> = (1..6).map(|x| x.to_string()).collect(); |
| 2738 |
for _ in v.drain(1..4) {} |
| 2739 |
assert_eq!(v, &[1.to_string(), 5.to_string()]); |
| 2740 |
|
| 2741 |
let mut v: ThinVec<_> = (1..6).map(|x| x.to_string()).collect(); |
| 2742 |
for _ in v.drain(1..4).rev() {} |
| 2743 |
assert_eq!(v, &[1.to_string(), 5.to_string()]); |
| 2744 |
|
| 2745 |
let mut v: ThinVec<_> = thin_vec![(); 5]; |
| 2746 |
for _ in v.drain(1..4).rev() {} |
| 2747 |
assert_eq!(v, &[(), ()]); |
| 2748 |
} |
| 2749 |
|
| 2750 |
#[test] |
| 2751 |
fn test_drain_max_vec_size() { |
| 2752 |
let mut v = ThinVec::<()>::with_capacity(MAX_CAP); |
| 2753 |
unsafe { |
| 2754 |
v.set_len(MAX_CAP); |
| 2755 |
} |
| 2756 |
for _ in v.drain(MAX_CAP - 1..) {} |
| 2757 |
assert_eq!(v.len(), MAX_CAP - 1); |
| 2758 |
} |
| 2759 |
|
| 2760 |
#[test] |
| 2761 |
fn test_clear() { |
| 2762 |
let mut v = ThinVec::<i32>::new(); |
| 2763 |
assert_eq!(v.len(), 0); |
| 2764 |
assert_eq!(v.capacity(), 0); |
| 2765 |
assert_eq!(&v[..], &[]); |
| 2766 |
|
| 2767 |
v.clear(); |
| 2768 |
assert_eq!(v.len(), 0); |
| 2769 |
assert_eq!(v.capacity(), 0); |
| 2770 |
assert_eq!(&v[..], &[]); |
| 2771 |
|
| 2772 |
v.push(1); |
| 2773 |
v.push(2); |
| 2774 |
assert_eq!(v.len(), 2); |
| 2775 |
assert!(v.capacity() >= 2); |
| 2776 |
assert_eq!(&v[..], &[1, 2]); |
| 2777 |
|
| 2778 |
v.clear(); |
| 2779 |
assert_eq!(v.len(), 0); |
| 2780 |
assert!(v.capacity() >= 2); |
| 2781 |
assert_eq!(&v[..], &[]); |
| 2782 |
|
| 2783 |
v.push(3); |
| 2784 |
v.push(4); |
| 2785 |
assert_eq!(v.len(), 2); |
| 2786 |
assert!(v.capacity() >= 2); |
| 2787 |
assert_eq!(&v[..], &[3, 4]); |
| 2788 |
|
| 2789 |
v.clear(); |
| 2790 |
assert_eq!(v.len(), 0); |
| 2791 |
assert!(v.capacity() >= 2); |
| 2792 |
assert_eq!(&v[..], &[]); |
| 2793 |
|
| 2794 |
v.clear(); |
| 2795 |
assert_eq!(v.len(), 0); |
| 2796 |
assert!(v.capacity() >= 2); |
| 2797 |
assert_eq!(&v[..], &[]); |
| 2798 |
} |
| 2799 |
|
| 2800 |
#[test] |
| 2801 |
fn test_empty_singleton_torture() { |
| 2802 |
{ |
| 2803 |
let mut v = ThinVec::<i32>::new(); |
| 2804 |
assert_eq!(v.len(), 0); |
| 2805 |
assert_eq!(v.capacity(), 0); |
| 2806 |
assert!(v.is_empty()); |
| 2807 |
assert_eq!(&v[..], &[]); |
| 2808 |
assert_eq!(&mut v[..], &mut []); |
| 2809 |
|
| 2810 |
assert_eq!(v.pop(), None); |
| 2811 |
assert_eq!(v.len(), 0); |
| 2812 |
assert_eq!(v.capacity(), 0); |
| 2813 |
assert_eq!(&v[..], &[]); |
| 2814 |
} |
| 2815 |
|
| 2816 |
{ |
| 2817 |
let v = ThinVec::<i32>::new(); |
| 2818 |
assert_eq!(v.into_iter().count(), 0); |
| 2819 |
|
| 2820 |
let v = ThinVec::<i32>::new(); |
| 2821 |
for _ in v.into_iter() { |
| 2822 |
unreachable!(); |
| 2823 |
} |
| 2824 |
} |
| 2825 |
|
| 2826 |
{ |
| 2827 |
let mut v = ThinVec::<i32>::new(); |
| 2828 |
assert_eq!(v.drain(..).len(), 0); |
| 2829 |
|
| 2830 |
for _ in v.drain(..) { |
| 2831 |
unreachable!() |
| 2832 |
} |
| 2833 |
|
| 2834 |
assert_eq!(v.len(), 0); |
| 2835 |
assert_eq!(v.capacity(), 0); |
| 2836 |
assert_eq!(&v[..], &[]); |
| 2837 |
} |
| 2838 |
|
| 2839 |
{ |
| 2840 |
let mut v = ThinVec::<i32>::new(); |
| 2841 |
assert_eq!(v.splice(.., []).len(), 0); |
| 2842 |
|
| 2843 |
for _ in v.splice(.., []) { |
| 2844 |
unreachable!() |
| 2845 |
} |
| 2846 |
|
| 2847 |
assert_eq!(v.len(), 0); |
| 2848 |
assert_eq!(v.capacity(), 0); |
| 2849 |
assert_eq!(&v[..], &[]); |
| 2850 |
} |
| 2851 |
|
| 2852 |
{ |
| 2853 |
let mut v = ThinVec::<i32>::new(); |
| 2854 |
v.truncate(1); |
| 2855 |
assert_eq!(v.len(), 0); |
| 2856 |
assert_eq!(v.capacity(), 0); |
| 2857 |
assert_eq!(&v[..], &[]); |
| 2858 |
|
| 2859 |
v.truncate(0); |
| 2860 |
assert_eq!(v.len(), 0); |
| 2861 |
assert_eq!(v.capacity(), 0); |
| 2862 |
assert_eq!(&v[..], &[]); |
| 2863 |
} |
| 2864 |
|
| 2865 |
{ |
| 2866 |
let mut v = ThinVec::<i32>::new(); |
| 2867 |
v.shrink_to_fit(); |
| 2868 |
assert_eq!(v.len(), 0); |
| 2869 |
assert_eq!(v.capacity(), 0); |
| 2870 |
assert_eq!(&v[..], &[]); |
| 2871 |
} |
| 2872 |
|
| 2873 |
{ |
| 2874 |
let mut v = ThinVec::<i32>::new(); |
| 2875 |
let new = v.split_off(0); |
| 2876 |
assert_eq!(v.len(), 0); |
| 2877 |
assert_eq!(v.capacity(), 0); |
| 2878 |
assert_eq!(&v[..], &[]); |
| 2879 |
|
| 2880 |
assert_eq!(new.len(), 0); |
| 2881 |
assert_eq!(new.capacity(), 0); |
| 2882 |
assert_eq!(&new[..], &[]); |
| 2883 |
} |
| 2884 |
|
| 2885 |
{ |
| 2886 |
let mut v = ThinVec::<i32>::new(); |
| 2887 |
let mut other = ThinVec::<i32>::new(); |
| 2888 |
v.append(&mut other); |
| 2889 |
|
| 2890 |
assert_eq!(v.len(), 0); |
| 2891 |
assert_eq!(v.capacity(), 0); |
| 2892 |
assert_eq!(&v[..], &[]); |
| 2893 |
|
| 2894 |
assert_eq!(other.len(), 0); |
| 2895 |
assert_eq!(other.capacity(), 0); |
| 2896 |
assert_eq!(&other[..], &[]); |
| 2897 |
} |
| 2898 |
|
| 2899 |
{ |
| 2900 |
let mut v = ThinVec::<i32>::new(); |
| 2901 |
v.reserve(0); |
| 2902 |
|
| 2903 |
assert_eq!(v.len(), 0); |
| 2904 |
assert_eq!(v.capacity(), 0); |
| 2905 |
assert_eq!(&v[..], &[]); |
| 2906 |
} |
| 2907 |
|
| 2908 |
{ |
| 2909 |
let mut v = ThinVec::<i32>::new(); |
| 2910 |
v.reserve_exact(0); |
| 2911 |
|
| 2912 |
assert_eq!(v.len(), 0); |
| 2913 |
assert_eq!(v.capacity(), 0); |
| 2914 |
assert_eq!(&v[..], &[]); |
| 2915 |
} |
| 2916 |
|
| 2917 |
{ |
| 2918 |
let mut v = ThinVec::<i32>::new(); |
| 2919 |
v.reserve(0); |
| 2920 |
|
| 2921 |
assert_eq!(v.len(), 0); |
| 2922 |
assert_eq!(v.capacity(), 0); |
| 2923 |
assert_eq!(&v[..], &[]); |
| 2924 |
} |
| 2925 |
|
| 2926 |
{ |
| 2927 |
let v = ThinVec::<i32>::with_capacity(0); |
| 2928 |
|
| 2929 |
assert_eq!(v.len(), 0); |
| 2930 |
assert_eq!(v.capacity(), 0); |
| 2931 |
assert_eq!(&v[..], &[]); |
| 2932 |
} |
| 2933 |
|
| 2934 |
{ |
| 2935 |
let v = ThinVec::<i32>::default(); |
| 2936 |
|
| 2937 |
assert_eq!(v.len(), 0); |
| 2938 |
assert_eq!(v.capacity(), 0); |
| 2939 |
assert_eq!(&v[..], &[]); |
| 2940 |
} |
| 2941 |
|
| 2942 |
{ |
| 2943 |
let mut v = ThinVec::<i32>::new(); |
| 2944 |
v.retain(|_| unreachable!()); |
| 2945 |
|
| 2946 |
assert_eq!(v.len(), 0); |
| 2947 |
assert_eq!(v.capacity(), 0); |
| 2948 |
assert_eq!(&v[..], &[]); |
| 2949 |
} |
| 2950 |
|
| 2951 |
{ |
| 2952 |
let mut v = ThinVec::<i32>::new(); |
| 2953 |
v.retain_mut(|_| unreachable!()); |
| 2954 |
|
| 2955 |
assert_eq!(v.len(), 0); |
| 2956 |
assert_eq!(v.capacity(), 0); |
| 2957 |
assert_eq!(&v[..], &[]); |
| 2958 |
} |
| 2959 |
|
| 2960 |
{ |
| 2961 |
let mut v = ThinVec::<i32>::new(); |
| 2962 |
v.dedup_by_key(|x| *x); |
| 2963 |
|
| 2964 |
assert_eq!(v.len(), 0); |
| 2965 |
assert_eq!(v.capacity(), 0); |
| 2966 |
assert_eq!(&v[..], &[]); |
| 2967 |
} |
| 2968 |
|
| 2969 |
{ |
| 2970 |
let mut v = ThinVec::<i32>::new(); |
| 2971 |
v.dedup_by(|_, _| unreachable!()); |
| 2972 |
|
| 2973 |
assert_eq!(v.len(), 0); |
| 2974 |
assert_eq!(v.capacity(), 0); |
| 2975 |
assert_eq!(&v[..], &[]); |
| 2976 |
} |
| 2977 |
|
| 2978 |
{ |
| 2979 |
let v = ThinVec::<i32>::new(); |
| 2980 |
let v = v.clone(); |
| 2981 |
|
| 2982 |
assert_eq!(v.len(), 0); |
| 2983 |
assert_eq!(v.capacity(), 0); |
| 2984 |
assert_eq!(&v[..], &[]); |
| 2985 |
} |
| 2986 |
} |
| 2987 |
|
| 2988 |
#[test] |
| 2989 |
fn test_clone() { |
| 2990 |
let mut v = ThinVec::<i32>::new(); |
| 2991 |
assert!(v.is_singleton()); |
| 2992 |
v.push(0); |
| 2993 |
v.pop(); |
| 2994 |
assert!(!v.is_singleton()); |
| 2995 |
|
| 2996 |
let v2 = v.clone(); |
| 2997 |
assert!(v2.is_singleton()); |
| 2998 |
} |
| 2999 |
} |
| 3000 |
|
| 3001 |
#[cfg(test)] |
| 3002 |
mod std_tests { |
| 3003 |
#![allow(clippy::reversed_empty_ranges)] |
| 3004 |
|
| 3005 |
use super::*; |
| 3006 |
use std::mem::size_of; |
| 3007 |
use std::usize; |
| 3008 |
|
| 3009 |
struct DropCounter<'a> { |
| 3010 |
count: &'a mut u32, |
| 3011 |
} |
| 3012 |
|
| 3013 |
impl<'a> Drop for DropCounter<'a> { |
| 3014 |
fn drop(&mut self) { |
| 3015 |
*self.count += 1; |
| 3016 |
} |
| 3017 |
} |
| 3018 |
|
| 3019 |
#[test] |
| 3020 |
fn test_small_vec_struct() { |
| 3021 |
assert!(size_of::<ThinVec<u8>>() == size_of::<usize>()); |
| 3022 |
} |
| 3023 |
|
| 3024 |
#[test] |
| 3025 |
fn test_double_drop() { |
| 3026 |
struct TwoVec<T> { |
| 3027 |
x: ThinVec<T>, |
| 3028 |
y: ThinVec<T>, |
| 3029 |
} |
| 3030 |
|
| 3031 |
let (mut count_x, mut count_y) = (0, 0); |
| 3032 |
{ |
| 3033 |
let mut tv = TwoVec { |
| 3034 |
x: ThinVec::new(), |
| 3035 |
y: ThinVec::new(), |
| 3036 |
}; |
| 3037 |
tv.x.push(DropCounter { |
| 3038 |
count: &mut count_x, |
| 3039 |
}); |
| 3040 |
tv.y.push(DropCounter { |
| 3041 |
count: &mut count_y, |
| 3042 |
}); |
| 3043 |
|
| 3044 |
// If ThinVec had a drop flag, here is where it would be zeroed. |
| 3045 |
// Instead, it should rely on its internal state to prevent |
| 3046 |
// doing anything significant when dropped multiple times. |
| 3047 |
drop(tv.x); |
| 3048 |
|
| 3049 |
// Here tv goes out of scope, tv.y should be dropped, but not tv.x. |
| 3050 |
} |
| 3051 |
|
| 3052 |
assert_eq!(count_x, 1); |
| 3053 |
assert_eq!(count_y, 1); |
| 3054 |
} |
| 3055 |
|
| 3056 |
#[test] |
| 3057 |
fn test_reserve() { |
| 3058 |
let mut v = ThinVec::new(); |
| 3059 |
assert_eq!(v.capacity(), 0); |
| 3060 |
|
| 3061 |
v.reserve(2); |
| 3062 |
assert!(v.capacity() >= 2); |
| 3063 |
|
| 3064 |
for i in 0..16 { |
| 3065 |
v.push(i); |
| 3066 |
} |
| 3067 |
|
| 3068 |
assert!(v.capacity() >= 16); |
| 3069 |
v.reserve(16); |
| 3070 |
assert!(v.capacity() >= 32); |
| 3071 |
|
| 3072 |
v.push(16); |
| 3073 |
|
| 3074 |
v.reserve(16); |
| 3075 |
assert!(v.capacity() >= 33) |
| 3076 |
} |
| 3077 |
|
| 3078 |
#[test] |
| 3079 |
fn test_extend() { |
| 3080 |
let mut v = ThinVec::<usize>::new(); |
| 3081 |
let mut w = ThinVec::new(); |
| 3082 |
v.extend(w.clone()); |
| 3083 |
assert_eq!(v, &[]); |
| 3084 |
|
| 3085 |
v.extend(0..3); |
| 3086 |
for i in 0..3 { |
| 3087 |
w.push(i) |
| 3088 |
} |
| 3089 |
|
| 3090 |
assert_eq!(v, w); |
| 3091 |
|
| 3092 |
v.extend(3..10); |
| 3093 |
for i in 3..10 { |
| 3094 |
w.push(i) |
| 3095 |
} |
| 3096 |
|
| 3097 |
assert_eq!(v, w); |
| 3098 |
|
| 3099 |
v.extend(w.clone()); // specializes to `append` |
| 3100 |
assert!(v.iter().eq(w.iter().chain(w.iter()))); |
| 3101 |
|
| 3102 |
// Zero sized types |
| 3103 |
#[derive(PartialEq, Debug)] |
| 3104 |
struct Foo; |
| 3105 |
|
| 3106 |
let mut a = ThinVec::new(); |
| 3107 |
let b = thin_vec![Foo, Foo]; |
| 3108 |
|
| 3109 |
a.extend(b); |
| 3110 |
assert_eq!(a, &[Foo, Foo]); |
| 3111 |
|
| 3112 |
// Double drop |
| 3113 |
let mut count_x = 0; |
| 3114 |
{ |
| 3115 |
let mut x = ThinVec::new(); |
| 3116 |
let y = thin_vec![DropCounter { |
| 3117 |
count: &mut count_x |
| 3118 |
}]; |
| 3119 |
x.extend(y); |
| 3120 |
} |
| 3121 |
|
| 3122 |
assert_eq!(count_x, 1); |
| 3123 |
} |
| 3124 |
|
| 3125 |
/* TODO: implement extend for Iter<&Copy> |
| 3126 |
#[test] |
| 3127 |
fn test_extend_ref() { |
| 3128 |
let mut v = thin_vec![1, 2]; |
| 3129 |
v.extend(&[3, 4, 5]); |
| 3130 |
|
| 3131 |
assert_eq!(v.len(), 5); |
| 3132 |
assert_eq!(v, [1, 2, 3, 4, 5]); |
| 3133 |
|
| 3134 |
let w = thin_vec![6, 7]; |
| 3135 |
v.extend(&w); |
| 3136 |
|
| 3137 |
assert_eq!(v.len(), 7); |
| 3138 |
assert_eq!(v, [1, 2, 3, 4, 5, 6, 7]); |
| 3139 |
} |
| 3140 |
*/ |
| 3141 |
|
| 3142 |
#[test] |
| 3143 |
fn test_slice_from_mut() { |
| 3144 |
let mut values = thin_vec![1, 2, 3, 4, 5]; |
| 3145 |
{ |
| 3146 |
let slice = &mut values[2..]; |
| 3147 |
assert!(slice == [3, 4, 5]); |
| 3148 |
for p in slice { |
| 3149 |
*p += 2; |
| 3150 |
} |
| 3151 |
} |
| 3152 |
|
| 3153 |
assert!(values == [1, 2, 5, 6, 7]); |
| 3154 |
} |
| 3155 |
|
| 3156 |
#[test] |
| 3157 |
fn test_slice_to_mut() { |
| 3158 |
let mut values = thin_vec![1, 2, 3, 4, 5]; |
| 3159 |
{ |
| 3160 |
let slice = &mut values[..2]; |
| 3161 |
assert!(slice == [1, 2]); |
| 3162 |
for p in slice { |
| 3163 |
*p += 1; |
| 3164 |
} |
| 3165 |
} |
| 3166 |
|
| 3167 |
assert!(values == [2, 3, 3, 4, 5]); |
| 3168 |
} |
| 3169 |
|
| 3170 |
#[test] |
| 3171 |
fn test_split_at_mut() { |
| 3172 |
let mut values = thin_vec![1, 2, 3, 4, 5]; |
| 3173 |
{ |
| 3174 |
let (left, right) = values.split_at_mut(2); |
| 3175 |
{ |
| 3176 |
let left: &[_] = left; |
| 3177 |
assert!(left[..left.len()] == [1, 2]); |
| 3178 |
} |
| 3179 |
for p in left { |
| 3180 |
*p += 1; |
| 3181 |
} |
| 3182 |
|
| 3183 |
{ |
| 3184 |
let right: &[_] = right; |
| 3185 |
assert!(right[..right.len()] == [3, 4, 5]); |
| 3186 |
} |
| 3187 |
for p in right { |
| 3188 |
*p += 2; |
| 3189 |
} |
| 3190 |
} |
| 3191 |
|
| 3192 |
assert_eq!(values, [2, 3, 5, 6, 7]); |
| 3193 |
} |
| 3194 |
|
| 3195 |
#[test] |
| 3196 |
fn test_clone() { |
| 3197 |
let v: ThinVec<i32> = thin_vec![]; |
| 3198 |
let w = thin_vec![1, 2, 3]; |
| 3199 |
|
| 3200 |
assert_eq!(v, v.clone()); |
| 3201 |
|
| 3202 |
let z = w.clone(); |
| 3203 |
assert_eq!(w, z); |
| 3204 |
// they should be disjoint in memory. |
| 3205 |
assert!(w.as_ptr() != z.as_ptr()) |
| 3206 |
} |
| 3207 |
|
| 3208 |
#[test] |
| 3209 |
fn test_clone_from() { |
| 3210 |
let mut v = thin_vec![]; |
| 3211 |
let three: ThinVec<Box<_>> = thin_vec![Box::new(1), Box::new(2), Box::new(3)]; |
| 3212 |
let two: ThinVec<Box<_>> = thin_vec![Box::new(4), Box::new(5)]; |
| 3213 |
// zero, long |
| 3214 |
v.clone_from(&three); |
| 3215 |
assert_eq!(v, three); |
| 3216 |
|
| 3217 |
// equal |
| 3218 |
v.clone_from(&three); |
| 3219 |
assert_eq!(v, three); |
| 3220 |
|
| 3221 |
// long, short |
| 3222 |
v.clone_from(&two); |
| 3223 |
assert_eq!(v, two); |
| 3224 |
|
| 3225 |
// short, long |
| 3226 |
v.clone_from(&three); |
| 3227 |
assert_eq!(v, three) |
| 3228 |
} |
| 3229 |
|
| 3230 |
#[test] |
| 3231 |
fn test_retain() { |
| 3232 |
let mut vec = thin_vec![1, 2, 3, 4]; |
| 3233 |
vec.retain(|&x| x % 2 == 0); |
| 3234 |
assert_eq!(vec, [2, 4]); |
| 3235 |
} |
| 3236 |
|
| 3237 |
#[test] |
| 3238 |
fn test_retain_mut() { |
| 3239 |
let mut vec = thin_vec![9, 9, 9, 9]; |
| 3240 |
let mut i = 0; |
| 3241 |
vec.retain_mut(|x| { |
| 3242 |
i += 1; |
| 3243 |
*x = i; |
| 3244 |
i != 4 |
| 3245 |
}); |
| 3246 |
assert_eq!(vec, [1, 2, 3]); |
| 3247 |
} |
| 3248 |
|
| 3249 |
#[test] |
| 3250 |
fn test_dedup() { |
| 3251 |
fn case(a: ThinVec<i32>, b: ThinVec<i32>) { |
| 3252 |
let mut v = a; |
| 3253 |
v.dedup(); |
| 3254 |
assert_eq!(v, b); |
| 3255 |
} |
| 3256 |
case(thin_vec![], thin_vec![]); |
| 3257 |
case(thin_vec![1], thin_vec![1]); |
| 3258 |
case(thin_vec![1, 1], thin_vec![1]); |
| 3259 |
case(thin_vec![1, 2, 3], thin_vec![1, 2, 3]); |
| 3260 |
case(thin_vec![1, 1, 2, 3], thin_vec![1, 2, 3]); |
| 3261 |
case(thin_vec![1, 2, 2, 3], thin_vec![1, 2, 3]); |
| 3262 |
case(thin_vec![1, 2, 3, 3], thin_vec![1, 2, 3]); |
| 3263 |
case(thin_vec![1, 1, 2, 2, 2, 3, 3], thin_vec![1, 2, 3]); |
| 3264 |
} |
| 3265 |
|
| 3266 |
#[test] |
| 3267 |
fn test_dedup_by_key() { |
| 3268 |
fn case(a: ThinVec<i32>, b: ThinVec<i32>) { |
| 3269 |
let mut v = a; |
| 3270 |
v.dedup_by_key(|i| *i / 10); |
| 3271 |
assert_eq!(v, b); |
| 3272 |
} |
| 3273 |
case(thin_vec![], thin_vec![]); |
| 3274 |
case(thin_vec![10], thin_vec![10]); |
| 3275 |
case(thin_vec![10, 11], thin_vec![10]); |
| 3276 |
case(thin_vec![10, 20, 30], thin_vec![10, 20, 30]); |
| 3277 |
case(thin_vec![10, 11, 20, 30], thin_vec![10, 20, 30]); |
| 3278 |
case(thin_vec![10, 20, 21, 30], thin_vec![10, 20, 30]); |
| 3279 |
case(thin_vec![10, 20, 30, 31], thin_vec![10, 20, 30]); |
| 3280 |
case(thin_vec![10, 11, 20, 21, 22, 30, 31], thin_vec![10, 20, 30]); |
| 3281 |
} |
| 3282 |
|
| 3283 |
#[test] |
| 3284 |
fn test_dedup_by() { |
| 3285 |
let mut vec = thin_vec!["foo", "bar", "Bar", "baz", "bar"]; |
| 3286 |
vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); |
| 3287 |
|
| 3288 |
assert_eq!(vec, ["foo", "bar", "baz", "bar"]); |
| 3289 |
|
| 3290 |
let mut vec = thin_vec![("foo", 1), ("foo", 2), ("bar", 3), ("bar", 4), ("bar", 5)]; |
| 3291 |
vec.dedup_by(|a, b| { |
| 3292 |
a.0 == b.0 && { |
| 3293 |
b.1 += a.1; |
| 3294 |
true |
| 3295 |
} |
| 3296 |
}); |
| 3297 |
|
| 3298 |
assert_eq!(vec, [("foo", 3), ("bar", 12)]); |
| 3299 |
} |
| 3300 |
|
| 3301 |
#[test] |
| 3302 |
fn test_dedup_unique() { |
| 3303 |
let mut v0: ThinVec<Box<_>> = thin_vec![Box::new(1), Box::new(1), Box::new(2), Box::new(3)]; |
| 3304 |
v0.dedup(); |
| 3305 |
let mut v1: ThinVec<Box<_>> = thin_vec![Box::new(1), Box::new(2), Box::new(2), Box::new(3)]; |
| 3306 |
v1.dedup(); |
| 3307 |
let mut v2: ThinVec<Box<_>> = thin_vec![Box::new(1), Box::new(2), Box::new(3), Box::new(3)]; |
| 3308 |
v2.dedup(); |
| 3309 |
// If the boxed pointers were leaked or otherwise misused, valgrind |
| 3310 |
// and/or rt should raise errors. |
| 3311 |
} |
| 3312 |
|
| 3313 |
#[test] |
| 3314 |
fn zero_sized_values() { |
| 3315 |
let mut v = ThinVec::new(); |
| 3316 |
assert_eq!(v.len(), 0); |
| 3317 |
v.push(()); |
| 3318 |
assert_eq!(v.len(), 1); |
| 3319 |
v.push(()); |
| 3320 |
assert_eq!(v.len(), 2); |
| 3321 |
assert_eq!(v.pop(), Some(())); |
| 3322 |
assert_eq!(v.pop(), Some(())); |
| 3323 |
assert_eq!(v.pop(), None); |
| 3324 |
|
| 3325 |
assert_eq!(v.iter().count(), 0); |
| 3326 |
v.push(()); |
| 3327 |
assert_eq!(v.iter().count(), 1); |
| 3328 |
v.push(()); |
| 3329 |
assert_eq!(v.iter().count(), 2); |
| 3330 |
|
| 3331 |
for &() in &v {} |
| 3332 |
|
| 3333 |
assert_eq!(v.iter_mut().count(), 2); |
| 3334 |
v.push(()); |
| 3335 |
assert_eq!(v.iter_mut().count(), 3); |
| 3336 |
v.push(()); |
| 3337 |
assert_eq!(v.iter_mut().count(), 4); |
| 3338 |
|
| 3339 |
for &mut () in &mut v {} |
| 3340 |
unsafe { |
| 3341 |
v.set_len(0); |
| 3342 |
} |
| 3343 |
assert_eq!(v.iter_mut().count(), 0); |
| 3344 |
} |
| 3345 |
|
| 3346 |
#[test] |
| 3347 |
fn test_partition() { |
| 3348 |
assert_eq!( |
| 3349 |
thin_vec![].into_iter().partition(|x: &i32| *x < 3), |
| 3350 |
(thin_vec![], thin_vec![]) |
| 3351 |
); |
| 3352 |
assert_eq!( |
| 3353 |
thin_vec![1, 2, 3].into_iter().partition(|x| *x < 4), |
| 3354 |
(thin_vec![1, 2, 3], thin_vec![]) |
| 3355 |
); |
| 3356 |
assert_eq!( |
| 3357 |
thin_vec![1, 2, 3].into_iter().partition(|x| *x < 2), |
| 3358 |
(thin_vec![1], thin_vec![2, 3]) |
| 3359 |
); |
| 3360 |
assert_eq!( |
| 3361 |
thin_vec![1, 2, 3].into_iter().partition(|x| *x < 0), |
| 3362 |
(thin_vec![], thin_vec![1, 2, 3]) |
| 3363 |
); |
| 3364 |
} |
| 3365 |
|
| 3366 |
#[test] |
| 3367 |
fn test_zip_unzip() { |
| 3368 |
let z1 = thin_vec![(1, 4), (2, 5), (3, 6)]; |
| 3369 |
|
| 3370 |
let (left, right): (ThinVec<_>, ThinVec<_>) = z1.iter().cloned().unzip(); |
| 3371 |
|
| 3372 |
assert_eq!((1, 4), (left[0], right[0])); |
| 3373 |
assert_eq!((2, 5), (left[1], right[1])); |
| 3374 |
assert_eq!((3, 6), (left[2], right[2])); |
| 3375 |
} |
| 3376 |
|
| 3377 |
#[test] |
| 3378 |
fn test_vec_truncate_drop() { |
| 3379 |
static mut DROPS: u32 = 0; |
| 3380 |
struct Elem(i32); |
| 3381 |
impl Drop for Elem { |
| 3382 |
fn drop(&mut self) { |
| 3383 |
unsafe { |
| 3384 |
DROPS += 1; |
| 3385 |
} |
| 3386 |
} |
| 3387 |
} |
| 3388 |
|
| 3389 |
let mut v = thin_vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)]; |
| 3390 |
assert_eq!(unsafe { DROPS }, 0); |
| 3391 |
v.truncate(3); |
| 3392 |
assert_eq!(unsafe { DROPS }, 2); |
| 3393 |
v.truncate(0); |
| 3394 |
assert_eq!(unsafe { DROPS }, 5); |
| 3395 |
} |
| 3396 |
|
| 3397 |
#[test] |
| 3398 |
#[should_panic] |
| 3399 |
fn test_vec_truncate_fail() { |
| 3400 |
struct BadElem(i32); |
| 3401 |
impl Drop for BadElem { |
| 3402 |
fn drop(&mut self) { |
| 3403 |
let BadElem(ref mut x) = *self; |
| 3404 |
if *x == 0xbadbeef { |
| 3405 |
panic!("BadElem panic: 0xbadbeef") |
| 3406 |
} |
| 3407 |
} |
| 3408 |
} |
| 3409 |
|
| 3410 |
let mut v = thin_vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)]; |
| 3411 |
v.truncate(0); |
| 3412 |
} |
| 3413 |
|
| 3414 |
#[test] |
| 3415 |
fn test_index() { |
| 3416 |
let vec = thin_vec![1, 2, 3]; |
| 3417 |
assert!(vec[1] == 2); |
| 3418 |
} |
| 3419 |
|
| 3420 |
#[test] |
| 3421 |
#[should_panic] |
| 3422 |
fn test_index_out_of_bounds() { |
| 3423 |
let vec = thin_vec![1, 2, 3]; |
| 3424 |
let _ = vec[3]; |
| 3425 |
} |
| 3426 |
|
| 3427 |
#[test] |
| 3428 |
#[should_panic] |
| 3429 |
fn test_slice_out_of_bounds_1() { |
| 3430 |
let x = thin_vec![1, 2, 3, 4, 5]; |
| 3431 |
let _ = &x[!0..]; |
| 3432 |
} |
| 3433 |
|
| 3434 |
#[test] |
| 3435 |
#[should_panic] |
| 3436 |
fn test_slice_out_of_bounds_2() { |
| 3437 |
let x = thin_vec![1, 2, 3, 4, 5]; |
| 3438 |
let _ = &x[..6]; |
| 3439 |
} |
| 3440 |
|
| 3441 |
#[test] |
| 3442 |
#[should_panic] |
| 3443 |
fn test_slice_out_of_bounds_3() { |
| 3444 |
let x = thin_vec![1, 2, 3, 4, 5]; |
| 3445 |
let _ = &x[!0..4]; |
| 3446 |
} |
| 3447 |
|
| 3448 |
#[test] |
| 3449 |
#[should_panic] |
| 3450 |
fn test_slice_out_of_bounds_4() { |
| 3451 |
let x = thin_vec![1, 2, 3, 4, 5]; |
| 3452 |
let _ = &x[1..6]; |
| 3453 |
} |
| 3454 |
|
| 3455 |
#[test] |
| 3456 |
#[should_panic] |
| 3457 |
fn test_slice_out_of_bounds_5() { |
| 3458 |
let x = thin_vec![1, 2, 3, 4, 5]; |
| 3459 |
let _ = &x[3..2]; |
| 3460 |
} |
| 3461 |
|
| 3462 |
#[test] |
| 3463 |
#[should_panic] |
| 3464 |
fn test_swap_remove_empty() { |
| 3465 |
let mut vec = ThinVec::<i32>::new(); |
| 3466 |
vec.swap_remove(0); |
| 3467 |
} |
| 3468 |
|
| 3469 |
#[test] |
| 3470 |
fn test_move_items() { |
| 3471 |
let vec = thin_vec![1, 2, 3]; |
| 3472 |
let mut vec2 = thin_vec![]; |
| 3473 |
for i in vec { |
| 3474 |
vec2.push(i); |
| 3475 |
} |
| 3476 |
assert_eq!(vec2, [1, 2, 3]); |
| 3477 |
} |
| 3478 |
|
| 3479 |
#[test] |
| 3480 |
fn test_move_items_reverse() { |
| 3481 |
let vec = thin_vec![1, 2, 3]; |
| 3482 |
let mut vec2 = thin_vec![]; |
| 3483 |
for i in vec.into_iter().rev() { |
| 3484 |
vec2.push(i); |
| 3485 |
} |
| 3486 |
assert_eq!(vec2, [3, 2, 1]); |
| 3487 |
} |
| 3488 |
|
| 3489 |
#[test] |
| 3490 |
fn test_move_items_zero_sized() { |
| 3491 |
let vec = thin_vec![(), (), ()]; |
| 3492 |
let mut vec2 = thin_vec![]; |
| 3493 |
for i in vec { |
| 3494 |
vec2.push(i); |
| 3495 |
} |
| 3496 |
assert_eq!(vec2, [(), (), ()]); |
| 3497 |
} |
| 3498 |
|
| 3499 |
#[test] |
| 3500 |
fn test_drain_items() { |
| 3501 |
let mut vec = thin_vec![1, 2, 3]; |
| 3502 |
let mut vec2 = thin_vec![]; |
| 3503 |
for i in vec.drain(..) { |
| 3504 |
vec2.push(i); |
| 3505 |
} |
| 3506 |
assert_eq!(vec, []); |
| 3507 |
assert_eq!(vec2, [1, 2, 3]); |
| 3508 |
} |
| 3509 |
|
| 3510 |
#[test] |
| 3511 |
fn test_drain_items_reverse() { |
| 3512 |
let mut vec = thin_vec![1, 2, 3]; |
| 3513 |
let mut vec2 = thin_vec![]; |
| 3514 |
for i in vec.drain(..).rev() { |
| 3515 |
vec2.push(i); |
| 3516 |
} |
| 3517 |
assert_eq!(vec, []); |
| 3518 |
assert_eq!(vec2, [3, 2, 1]); |
| 3519 |
} |
| 3520 |
|
| 3521 |
#[test] |
| 3522 |
fn test_drain_items_zero_sized() { |
| 3523 |
let mut vec = thin_vec![(), (), ()]; |
| 3524 |
let mut vec2 = thin_vec![]; |
| 3525 |
for i in vec.drain(..) { |
| 3526 |
vec2.push(i); |
| 3527 |
} |
| 3528 |
assert_eq!(vec, []); |
| 3529 |
assert_eq!(vec2, [(), (), ()]); |
| 3530 |
} |
| 3531 |
|
| 3532 |
#[test] |
| 3533 |
#[should_panic] |
| 3534 |
fn test_drain_out_of_bounds() { |
| 3535 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3536 |
v.drain(5..6); |
| 3537 |
} |
| 3538 |
|
| 3539 |
#[test] |
| 3540 |
fn test_drain_range() { |
| 3541 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3542 |
for _ in v.drain(4..) {} |
| 3543 |
assert_eq!(v, &[1, 2, 3, 4]); |
| 3544 |
|
| 3545 |
let mut v: ThinVec<_> = (1..6).map(|x| x.to_string()).collect(); |
| 3546 |
for _ in v.drain(1..4) {} |
| 3547 |
assert_eq!(v, &[1.to_string(), 5.to_string()]); |
| 3548 |
|
| 3549 |
let mut v: ThinVec<_> = (1..6).map(|x| x.to_string()).collect(); |
| 3550 |
for _ in v.drain(1..4).rev() {} |
| 3551 |
assert_eq!(v, &[1.to_string(), 5.to_string()]); |
| 3552 |
|
| 3553 |
let mut v: ThinVec<_> = thin_vec![(); 5]; |
| 3554 |
for _ in v.drain(1..4).rev() {} |
| 3555 |
assert_eq!(v, &[(), ()]); |
| 3556 |
} |
| 3557 |
|
| 3558 |
#[test] |
| 3559 |
fn test_drain_inclusive_range() { |
| 3560 |
let mut v = thin_vec!['a', 'b', 'c', 'd', 'e']; |
| 3561 |
for _ in v.drain(1..=3) {} |
| 3562 |
assert_eq!(v, &['a', 'e']); |
| 3563 |
|
| 3564 |
let mut v: ThinVec<_> = (0..=5).map(|x| x.to_string()).collect(); |
| 3565 |
for _ in v.drain(1..=5) {} |
| 3566 |
assert_eq!(v, &["0".to_string()]); |
| 3567 |
|
| 3568 |
let mut v: ThinVec<String> = (0..=5).map(|x| x.to_string()).collect(); |
| 3569 |
for _ in v.drain(0..=5) {} |
| 3570 |
assert_eq!(v, ThinVec::<String>::new()); |
| 3571 |
|
| 3572 |
let mut v: ThinVec<_> = (0..=5).map(|x| x.to_string()).collect(); |
| 3573 |
for _ in v.drain(0..=3) {} |
| 3574 |
assert_eq!(v, &["4".to_string(), "5".to_string()]); |
| 3575 |
|
| 3576 |
let mut v: ThinVec<_> = (0..=1).map(|x| x.to_string()).collect(); |
| 3577 |
for _ in v.drain(..=0) {} |
| 3578 |
assert_eq!(v, &["1".to_string()]); |
| 3579 |
} |
| 3580 |
|
| 3581 |
#[test] |
| 3582 |
#[cfg(not(feature = "gecko-ffi"))] |
| 3583 |
fn test_drain_max_vec_size() { |
| 3584 |
let mut v = ThinVec::<()>::with_capacity(usize::max_value()); |
| 3585 |
unsafe { |
| 3586 |
v.set_len(usize::max_value()); |
| 3587 |
} |
| 3588 |
for _ in v.drain(usize::max_value() - 1..) {} |
| 3589 |
assert_eq!(v.len(), usize::max_value() - 1); |
| 3590 |
|
| 3591 |
let mut v = ThinVec::<()>::with_capacity(usize::max_value()); |
| 3592 |
unsafe { |
| 3593 |
v.set_len(usize::max_value()); |
| 3594 |
} |
| 3595 |
for _ in v.drain(usize::max_value() - 1..=usize::max_value() - 1) {} |
| 3596 |
assert_eq!(v.len(), usize::max_value() - 1); |
| 3597 |
} |
| 3598 |
|
| 3599 |
#[test] |
| 3600 |
#[should_panic] |
| 3601 |
fn test_drain_inclusive_out_of_bounds() { |
| 3602 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3603 |
v.drain(5..=5); |
| 3604 |
} |
| 3605 |
|
| 3606 |
#[test] |
| 3607 |
fn test_splice() { |
| 3608 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3609 |
let a = [10, 11, 12]; |
| 3610 |
v.splice(2..4, a.iter().cloned()); |
| 3611 |
assert_eq!(v, &[1, 2, 10, 11, 12, 5]); |
| 3612 |
v.splice(1..3, Some(20)); |
| 3613 |
assert_eq!(v, &[1, 20, 11, 12, 5]); |
| 3614 |
} |
| 3615 |
|
| 3616 |
#[test] |
| 3617 |
fn test_splice_inclusive_range() { |
| 3618 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3619 |
let a = [10, 11, 12]; |
| 3620 |
let t1: ThinVec<_> = v.splice(2..=3, a.iter().cloned()).collect(); |
| 3621 |
assert_eq!(v, &[1, 2, 10, 11, 12, 5]); |
| 3622 |
assert_eq!(t1, &[3, 4]); |
| 3623 |
let t2: ThinVec<_> = v.splice(1..=2, Some(20)).collect(); |
| 3624 |
assert_eq!(v, &[1, 20, 11, 12, 5]); |
| 3625 |
assert_eq!(t2, &[2, 10]); |
| 3626 |
} |
| 3627 |
|
| 3628 |
#[test] |
| 3629 |
#[should_panic] |
| 3630 |
fn test_splice_out_of_bounds() { |
| 3631 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3632 |
let a = [10, 11, 12]; |
| 3633 |
v.splice(5..6, a.iter().cloned()); |
| 3634 |
} |
| 3635 |
|
| 3636 |
#[test] |
| 3637 |
#[should_panic] |
| 3638 |
fn test_splice_inclusive_out_of_bounds() { |
| 3639 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3640 |
let a = [10, 11, 12]; |
| 3641 |
v.splice(5..=5, a.iter().cloned()); |
| 3642 |
} |
| 3643 |
|
| 3644 |
#[test] |
| 3645 |
fn test_splice_items_zero_sized() { |
| 3646 |
let mut vec = thin_vec![(), (), ()]; |
| 3647 |
let vec2 = thin_vec![]; |
| 3648 |
let t: ThinVec<_> = vec.splice(1..2, vec2.iter().cloned()).collect(); |
| 3649 |
assert_eq!(vec, &[(), ()]); |
| 3650 |
assert_eq!(t, &[()]); |
| 3651 |
} |
| 3652 |
|
| 3653 |
#[test] |
| 3654 |
fn test_splice_unbounded() { |
| 3655 |
let mut vec = thin_vec![1, 2, 3, 4, 5]; |
| 3656 |
let t: ThinVec<_> = vec.splice(.., None).collect(); |
| 3657 |
assert_eq!(vec, &[]); |
| 3658 |
assert_eq!(t, &[1, 2, 3, 4, 5]); |
| 3659 |
} |
| 3660 |
|
| 3661 |
#[test] |
| 3662 |
fn test_splice_forget() { |
| 3663 |
let mut v = thin_vec![1, 2, 3, 4, 5]; |
| 3664 |
let a = [10, 11, 12]; |
| 3665 |
::std::mem::forget(v.splice(2..4, a.iter().cloned())); |
| 3666 |
assert_eq!(v, &[1, 2]); |
| 3667 |
} |
| 3668 |
|
| 3669 |
#[test] |
| 3670 |
fn test_splice_from_empty() { |
| 3671 |
let mut v = thin_vec![]; |
| 3672 |
let a = [10, 11, 12]; |
| 3673 |
v.splice(.., a.iter().cloned()); |
| 3674 |
assert_eq!(v, &[10, 11, 12]); |
| 3675 |
} |
| 3676 |
|
| 3677 |
/* probs won't ever impl this |
| 3678 |
#[test] |
| 3679 |
fn test_into_boxed_slice() { |
| 3680 |
let xs = thin_vec![1, 2, 3]; |
| 3681 |
let ys = xs.into_boxed_slice(); |
| 3682 |
assert_eq!(&*ys, [1, 2, 3]); |
| 3683 |
} |
| 3684 |
*/ |
| 3685 |
|
| 3686 |
#[test] |
| 3687 |
fn test_append() { |
| 3688 |
let mut vec = thin_vec![1, 2, 3]; |
| 3689 |
let mut vec2 = thin_vec![4, 5, 6]; |
| 3690 |
vec.append(&mut vec2); |
| 3691 |
assert_eq!(vec, [1, 2, 3, 4, 5, 6]); |
| 3692 |
assert_eq!(vec2, []); |
| 3693 |
} |
| 3694 |
|
| 3695 |
#[test] |
| 3696 |
fn test_split_off() { |
| 3697 |
let mut vec = thin_vec![1, 2, 3, 4, 5, 6]; |
| 3698 |
let vec2 = vec.split_off(4); |
| 3699 |
assert_eq!(vec, [1, 2, 3, 4]); |
| 3700 |
assert_eq!(vec2, [5, 6]); |
| 3701 |
} |
| 3702 |
|
| 3703 |
#[test] |
| 3704 |
fn test_into_iter_as_slice() { |
| 3705 |
let vec = thin_vec!['a', 'b', 'c']; |
| 3706 |
let mut into_iter = vec.into_iter(); |
| 3707 |
assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); |
| 3708 |
let _ = into_iter.next().unwrap(); |
| 3709 |
assert_eq!(into_iter.as_slice(), &['b', 'c']); |
| 3710 |
let _ = into_iter.next().unwrap(); |
| 3711 |
let _ = into_iter.next().unwrap(); |
| 3712 |
assert_eq!(into_iter.as_slice(), &[]); |
| 3713 |
} |
| 3714 |
|
| 3715 |
#[test] |
| 3716 |
fn test_into_iter_as_mut_slice() { |
| 3717 |
let vec = thin_vec!['a', 'b', 'c']; |
| 3718 |
let mut into_iter = vec.into_iter(); |
| 3719 |
assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); |
| 3720 |
into_iter.as_mut_slice()[0] = 'x'; |
| 3721 |
into_iter.as_mut_slice()[1] = 'y'; |
| 3722 |
assert_eq!(into_iter.next().unwrap(), 'x'); |
| 3723 |
assert_eq!(into_iter.as_slice(), &['y', 'c']); |
| 3724 |
} |
| 3725 |
|
| 3726 |
#[test] |
| 3727 |
fn test_into_iter_debug() { |
| 3728 |
let vec = thin_vec!['a', 'b', 'c']; |
| 3729 |
let into_iter = vec.into_iter(); |
| 3730 |
let debug = format!("{:?}", into_iter); |
| 3731 |
assert_eq!(debug, "IntoIter(['a', 'b', 'c'])"); |
| 3732 |
} |
| 3733 |
|
| 3734 |
#[test] |
| 3735 |
fn test_into_iter_count() { |
| 3736 |
assert_eq!(thin_vec![1, 2, 3].into_iter().count(), 3); |
| 3737 |
} |
| 3738 |
|
| 3739 |
#[test] |
| 3740 |
fn test_into_iter_clone() { |
| 3741 |
fn iter_equal<I: Iterator<Item = i32>>(it: I, slice: &[i32]) { |
| 3742 |
let v: ThinVec<i32> = it.collect(); |
| 3743 |
assert_eq!(&v[..], slice); |
| 3744 |
} |
| 3745 |
let mut it = thin_vec![1, 2, 3].into_iter(); |
| 3746 |
iter_equal(it.clone(), &[1, 2, 3]); |
| 3747 |
assert_eq!(it.next(), Some(1)); |
| 3748 |
let mut it = it.rev(); |
| 3749 |
iter_equal(it.clone(), &[3, 2]); |
| 3750 |
assert_eq!(it.next(), Some(3)); |
| 3751 |
iter_equal(it.clone(), &[2]); |
| 3752 |
assert_eq!(it.next(), Some(2)); |
| 3753 |
iter_equal(it.clone(), &[]); |
| 3754 |
assert_eq!(it.next(), None); |
| 3755 |
} |
| 3756 |
|
| 3757 |
/* TODO: make drain covariant |
| 3758 |
#[allow(dead_code)] |
| 3759 |
fn assert_covariance() { |
| 3760 |
fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> { |
| 3761 |
d |
| 3762 |
} |
| 3763 |
fn into_iter<'new>(i: IntoIter<&'static str>) -> IntoIter<&'new str> { |
| 3764 |
i |
| 3765 |
} |
| 3766 |
} |
| 3767 |
*/ |
| 3768 |
|
| 3769 |
/* TODO: specialize vec.into_iter().collect::<ThinVec<_>>(); |
| 3770 |
#[test] |
| 3771 |
fn from_into_inner() { |
| 3772 |
let vec = thin_vec![1, 2, 3]; |
| 3773 |
let ptr = vec.as_ptr(); |
| 3774 |
let vec = vec.into_iter().collect::<ThinVec<_>>(); |
| 3775 |
assert_eq!(vec, [1, 2, 3]); |
| 3776 |
assert_eq!(vec.as_ptr(), ptr); |
| 3777 |
|
| 3778 |
let ptr = &vec[1] as *const _; |
| 3779 |
let mut it = vec.into_iter(); |
| 3780 |
it.next().unwrap(); |
| 3781 |
let vec = it.collect::<ThinVec<_>>(); |
| 3782 |
assert_eq!(vec, [2, 3]); |
| 3783 |
assert!(ptr != vec.as_ptr()); |
| 3784 |
} |
| 3785 |
*/ |
| 3786 |
|
| 3787 |
#[test] |
| 3788 |
#[cfg_attr(feature = "gecko-ffi", ignore)] |
| 3789 |
fn overaligned_allocations() { |
| 3790 |
#[repr(align(256))] |
| 3791 |
struct Foo(usize); |
| 3792 |
let mut v = thin_vec![Foo(273)]; |
| 3793 |
for i in 0..0x1000 { |
| 3794 |
v.reserve_exact(i); |
| 3795 |
assert!(v[0].0 == 273); |
| 3796 |
assert!(v.as_ptr() as usize & 0xff == 0); |
| 3797 |
v.shrink_to_fit(); |
| 3798 |
assert!(v[0].0 == 273); |
| 3799 |
assert!(v.as_ptr() as usize & 0xff == 0); |
| 3800 |
} |
| 3801 |
} |
| 3802 |
|
| 3803 |
/* TODO: implement drain_filter? |
| 3804 |
#[test] |
| 3805 |
fn drain_filter_empty() { |
| 3806 |
let mut vec: ThinVec<i32> = thin_vec![]; |
| 3807 |
|
| 3808 |
{ |
| 3809 |
let mut iter = vec.drain_filter(|_| true); |
| 3810 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3811 |
assert_eq!(iter.next(), None); |
| 3812 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3813 |
assert_eq!(iter.next(), None); |
| 3814 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3815 |
} |
| 3816 |
assert_eq!(vec.len(), 0); |
| 3817 |
assert_eq!(vec, thin_vec![]); |
| 3818 |
} |
| 3819 |
|
| 3820 |
#[test] |
| 3821 |
fn drain_filter_zst() { |
| 3822 |
let mut vec = thin_vec![(), (), (), (), ()]; |
| 3823 |
let initial_len = vec.len(); |
| 3824 |
let mut count = 0; |
| 3825 |
{ |
| 3826 |
let mut iter = vec.drain_filter(|_| true); |
| 3827 |
assert_eq!(iter.size_hint(), (0, Some(initial_len))); |
| 3828 |
while let Some(_) = iter.next() { |
| 3829 |
count += 1; |
| 3830 |
assert_eq!(iter.size_hint(), (0, Some(initial_len - count))); |
| 3831 |
} |
| 3832 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3833 |
assert_eq!(iter.next(), None); |
| 3834 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3835 |
} |
| 3836 |
|
| 3837 |
assert_eq!(count, initial_len); |
| 3838 |
assert_eq!(vec.len(), 0); |
| 3839 |
assert_eq!(vec, thin_vec![]); |
| 3840 |
} |
| 3841 |
|
| 3842 |
#[test] |
| 3843 |
fn drain_filter_false() { |
| 3844 |
let mut vec = thin_vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 3845 |
|
| 3846 |
let initial_len = vec.len(); |
| 3847 |
let mut count = 0; |
| 3848 |
{ |
| 3849 |
let mut iter = vec.drain_filter(|_| false); |
| 3850 |
assert_eq!(iter.size_hint(), (0, Some(initial_len))); |
| 3851 |
for _ in iter.by_ref() { |
| 3852 |
count += 1; |
| 3853 |
} |
| 3854 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3855 |
assert_eq!(iter.next(), None); |
| 3856 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3857 |
} |
| 3858 |
|
| 3859 |
assert_eq!(count, 0); |
| 3860 |
assert_eq!(vec.len(), initial_len); |
| 3861 |
assert_eq!(vec, thin_vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); |
| 3862 |
} |
| 3863 |
|
| 3864 |
#[test] |
| 3865 |
fn drain_filter_true() { |
| 3866 |
let mut vec = thin_vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 3867 |
|
| 3868 |
let initial_len = vec.len(); |
| 3869 |
let mut count = 0; |
| 3870 |
{ |
| 3871 |
let mut iter = vec.drain_filter(|_| true); |
| 3872 |
assert_eq!(iter.size_hint(), (0, Some(initial_len))); |
| 3873 |
while let Some(_) = iter.next() { |
| 3874 |
count += 1; |
| 3875 |
assert_eq!(iter.size_hint(), (0, Some(initial_len - count))); |
| 3876 |
} |
| 3877 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3878 |
assert_eq!(iter.next(), None); |
| 3879 |
assert_eq!(iter.size_hint(), (0, Some(0))); |
| 3880 |
} |
| 3881 |
|
| 3882 |
assert_eq!(count, initial_len); |
| 3883 |
assert_eq!(vec.len(), 0); |
| 3884 |
assert_eq!(vec, thin_vec![]); |
| 3885 |
} |
| 3886 |
|
| 3887 |
#[test] |
| 3888 |
fn drain_filter_complex() { |
| 3889 |
|
| 3890 |
{ // [+xxx++++++xxxxx++++x+x++] |
| 3891 |
let mut vec = thin_vec![1, |
| 3892 |
2, 4, 6, |
| 3893 |
7, 9, 11, 13, 15, 17, |
| 3894 |
18, 20, 22, 24, 26, |
| 3895 |
27, 29, 31, 33, |
| 3896 |
34, |
| 3897 |
35, |
| 3898 |
36, |
| 3899 |
37, 39]; |
| 3900 |
|
| 3901 |
let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<ThinVec<_>>(); |
| 3902 |
assert_eq!(removed.len(), 10); |
| 3903 |
assert_eq!(removed, thin_vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); |
| 3904 |
|
| 3905 |
assert_eq!(vec.len(), 14); |
| 3906 |
assert_eq!(vec, thin_vec![1, 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39]); |
| 3907 |
} |
| 3908 |
|
| 3909 |
{ // [xxx++++++xxxxx++++x+x++] |
| 3910 |
let mut vec = thin_vec![2, 4, 6, |
| 3911 |
7, 9, 11, 13, 15, 17, |
| 3912 |
18, 20, 22, 24, 26, |
| 3913 |
27, 29, 31, 33, |
| 3914 |
34, |
| 3915 |
35, |
| 3916 |
36, |
| 3917 |
37, 39]; |
| 3918 |
|
| 3919 |
let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<ThinVec<_>>(); |
| 3920 |
assert_eq!(removed.len(), 10); |
| 3921 |
assert_eq!(removed, thin_vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); |
| 3922 |
|
| 3923 |
assert_eq!(vec.len(), 13); |
| 3924 |
assert_eq!(vec, thin_vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39]); |
| 3925 |
} |
| 3926 |
|
| 3927 |
{ // [xxx++++++xxxxx++++x+x] |
| 3928 |
let mut vec = thin_vec![2, 4, 6, |
| 3929 |
7, 9, 11, 13, 15, 17, |
| 3930 |
18, 20, 22, 24, 26, |
| 3931 |
27, 29, 31, 33, |
| 3932 |
34, |
| 3933 |
35, |
| 3934 |
36]; |
| 3935 |
|
| 3936 |
let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<ThinVec<_>>(); |
| 3937 |
assert_eq!(removed.len(), 10); |
| 3938 |
assert_eq!(removed, thin_vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); |
| 3939 |
|
| 3940 |
assert_eq!(vec.len(), 11); |
| 3941 |
assert_eq!(vec, thin_vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35]); |
| 3942 |
} |
| 3943 |
|
| 3944 |
{ // [xxxxxxxxxx+++++++++++] |
| 3945 |
let mut vec = thin_vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20, |
| 3946 |
1, 3, 5, 7, 9, 11, 13, 15, 17, 19]; |
| 3947 |
|
| 3948 |
let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<ThinVec<_>>(); |
| 3949 |
assert_eq!(removed.len(), 10); |
| 3950 |
assert_eq!(removed, thin_vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20]); |
| 3951 |
|
| 3952 |
assert_eq!(vec.len(), 10); |
| 3953 |
assert_eq!(vec, thin_vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]); |
| 3954 |
} |
| 3955 |
|
| 3956 |
{ // [+++++++++++xxxxxxxxxx] |
| 3957 |
let mut vec = thin_vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19, |
| 3958 |
2, 4, 6, 8, 10, 12, 14, 16, 18, 20]; |
| 3959 |
|
| 3960 |
let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<ThinVec<_>>(); |
| 3961 |
assert_eq!(removed.len(), 10); |
| 3962 |
assert_eq!(removed, thin_vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20]); |
| 3963 |
|
| 3964 |
assert_eq!(vec.len(), 10); |
| 3965 |
assert_eq!(vec, thin_vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]); |
| 3966 |
} |
| 3967 |
} |
| 3968 |
*/ |
| 3969 |
#[test] |
| 3970 |
fn test_reserve_exact() { |
| 3971 |
// This is all the same as test_reserve |
| 3972 |
|
| 3973 |
let mut v = ThinVec::new(); |
| 3974 |
assert_eq!(v.capacity(), 0); |
| 3975 |
|
| 3976 |
v.reserve_exact(2); |
| 3977 |
assert!(v.capacity() >= 2); |
| 3978 |
|
| 3979 |
for i in 0..16 { |
| 3980 |
v.push(i); |
| 3981 |
} |
| 3982 |
|
| 3983 |
assert!(v.capacity() >= 16); |
| 3984 |
v.reserve_exact(16); |
| 3985 |
assert!(v.capacity() >= 32); |
| 3986 |
|
| 3987 |
v.push(16); |
| 3988 |
|
| 3989 |
v.reserve_exact(16); |
| 3990 |
assert!(v.capacity() >= 33) |
| 3991 |
} |
| 3992 |
|
| 3993 |
/* TODO: implement try_reserve |
| 3994 |
#[test] |
| 3995 |
fn test_try_reserve() { |
| 3996 |
|
| 3997 |
// These are the interesting cases: |
| 3998 |
// * exactly isize::MAX should never trigger a CapacityOverflow (can be OOM) |
| 3999 |
// * > isize::MAX should always fail |
| 4000 |
// * On 16/32-bit should CapacityOverflow |
| 4001 |
// * On 64-bit should OOM |
| 4002 |
// * overflow may trigger when adding `len` to `cap` (in number of elements) |
| 4003 |
// * overflow may trigger when multiplying `new_cap` by size_of::<T> (to get bytes) |
| 4004 |
|
| 4005 |
const MAX_CAP: usize = isize::MAX as usize; |
| 4006 |
const MAX_USIZE: usize = usize::MAX; |
| 4007 |
|
| 4008 |
// On 16/32-bit, we check that allocations don't exceed isize::MAX, |
| 4009 |
// on 64-bit, we assume the OS will give an OOM for such a ridiculous size. |
| 4010 |
// Any platform that succeeds for these requests is technically broken with |
| 4011 |
// ptr::offset because LLVM is the worst. |
| 4012 |
let guards_against_isize = size_of::<usize>() < 8; |
| 4013 |
|
| 4014 |
{ |
| 4015 |
// Note: basic stuff is checked by test_reserve |
| 4016 |
let mut empty_bytes: ThinVec<u8> = ThinVec::new(); |
| 4017 |
|
| 4018 |
// Check isize::MAX doesn't count as an overflow |
| 4019 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_CAP) { |
| 4020 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4021 |
} |
| 4022 |
// Play it again, frank! (just to be sure) |
| 4023 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_CAP) { |
| 4024 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4025 |
} |
| 4026 |
|
| 4027 |
if guards_against_isize { |
| 4028 |
// Check isize::MAX + 1 does count as overflow |
| 4029 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_CAP + 1) { |
| 4030 |
} else { panic!("isize::MAX + 1 should trigger an overflow!") } |
| 4031 |
|
| 4032 |
// Check usize::MAX does count as overflow |
| 4033 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) { |
| 4034 |
} else { panic!("usize::MAX should trigger an overflow!") } |
| 4035 |
} else { |
| 4036 |
// Check isize::MAX + 1 is an OOM |
| 4037 |
if let Err(AllocErr) = empty_bytes.try_reserve(MAX_CAP + 1) { |
| 4038 |
} else { panic!("isize::MAX + 1 should trigger an OOM!") } |
| 4039 |
|
| 4040 |
// Check usize::MAX is an OOM |
| 4041 |
if let Err(AllocErr) = empty_bytes.try_reserve(MAX_USIZE) { |
| 4042 |
} else { panic!("usize::MAX should trigger an OOM!") } |
| 4043 |
} |
| 4044 |
} |
| 4045 |
|
| 4046 |
|
| 4047 |
{ |
| 4048 |
// Same basic idea, but with non-zero len |
| 4049 |
let mut ten_bytes: ThinVec<u8> = thin_vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 4050 |
|
| 4051 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 10) { |
| 4052 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4053 |
} |
| 4054 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 10) { |
| 4055 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4056 |
} |
| 4057 |
if guards_against_isize { |
| 4058 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 9) { |
| 4059 |
} else { panic!("isize::MAX + 1 should trigger an overflow!"); } |
| 4060 |
} else { |
| 4061 |
if let Err(AllocErr) = ten_bytes.try_reserve(MAX_CAP - 9) { |
| 4062 |
} else { panic!("isize::MAX + 1 should trigger an OOM!") } |
| 4063 |
} |
| 4064 |
// Should always overflow in the add-to-len |
| 4065 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_USIZE) { |
| 4066 |
} else { panic!("usize::MAX should trigger an overflow!") } |
| 4067 |
} |
| 4068 |
|
| 4069 |
|
| 4070 |
{ |
| 4071 |
// Same basic idea, but with interesting type size |
| 4072 |
let mut ten_u32s: ThinVec<u32> = thin_vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 4073 |
|
| 4074 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 10) { |
| 4075 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4076 |
} |
| 4077 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 10) { |
| 4078 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4079 |
} |
| 4080 |
if guards_against_isize { |
| 4081 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 9) { |
| 4082 |
} else { panic!("isize::MAX + 1 should trigger an overflow!"); } |
| 4083 |
} else { |
| 4084 |
if let Err(AllocErr) = ten_u32s.try_reserve(MAX_CAP/4 - 9) { |
| 4085 |
} else { panic!("isize::MAX + 1 should trigger an OOM!") } |
| 4086 |
} |
| 4087 |
// Should fail in the mul-by-size |
| 4088 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_USIZE - 20) { |
| 4089 |
} else { |
| 4090 |
panic!("usize::MAX should trigger an overflow!"); |
| 4091 |
} |
| 4092 |
} |
| 4093 |
|
| 4094 |
} |
| 4095 |
|
| 4096 |
#[test] |
| 4097 |
fn test_try_reserve_exact() { |
| 4098 |
|
| 4099 |
// This is exactly the same as test_try_reserve with the method changed. |
| 4100 |
// See that test for comments. |
| 4101 |
|
| 4102 |
const MAX_CAP: usize = isize::MAX as usize; |
| 4103 |
const MAX_USIZE: usize = usize::MAX; |
| 4104 |
|
| 4105 |
let guards_against_isize = size_of::<usize>() < 8; |
| 4106 |
|
| 4107 |
{ |
| 4108 |
let mut empty_bytes: ThinVec<u8> = ThinVec::new(); |
| 4109 |
|
| 4110 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_CAP) { |
| 4111 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4112 |
} |
| 4113 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_CAP) { |
| 4114 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4115 |
} |
| 4116 |
|
| 4117 |
if guards_against_isize { |
| 4118 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_CAP + 1) { |
| 4119 |
} else { panic!("isize::MAX + 1 should trigger an overflow!") } |
| 4120 |
|
| 4121 |
if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_USIZE) { |
| 4122 |
} else { panic!("usize::MAX should trigger an overflow!") } |
| 4123 |
} else { |
| 4124 |
if let Err(AllocErr) = empty_bytes.try_reserve_exact(MAX_CAP + 1) { |
| 4125 |
} else { panic!("isize::MAX + 1 should trigger an OOM!") } |
| 4126 |
|
| 4127 |
if let Err(AllocErr) = empty_bytes.try_reserve_exact(MAX_USIZE) { |
| 4128 |
} else { panic!("usize::MAX should trigger an OOM!") } |
| 4129 |
} |
| 4130 |
} |
| 4131 |
|
| 4132 |
|
| 4133 |
{ |
| 4134 |
let mut ten_bytes: ThinVec<u8> = thin_vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 4135 |
|
| 4136 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 10) { |
| 4137 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4138 |
} |
| 4139 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 10) { |
| 4140 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4141 |
} |
| 4142 |
if guards_against_isize { |
| 4143 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 9) { |
| 4144 |
} else { panic!("isize::MAX + 1 should trigger an overflow!"); } |
| 4145 |
} else { |
| 4146 |
if let Err(AllocErr) = ten_bytes.try_reserve_exact(MAX_CAP - 9) { |
| 4147 |
} else { panic!("isize::MAX + 1 should trigger an OOM!") } |
| 4148 |
} |
| 4149 |
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_USIZE) { |
| 4150 |
} else { panic!("usize::MAX should trigger an overflow!") } |
| 4151 |
} |
| 4152 |
|
| 4153 |
|
| 4154 |
{ |
| 4155 |
let mut ten_u32s: ThinVec<u32> = thin_vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
| 4156 |
|
| 4157 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 10) { |
| 4158 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4159 |
} |
| 4160 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 10) { |
| 4161 |
panic!("isize::MAX shouldn't trigger an overflow!"); |
| 4162 |
} |
| 4163 |
if guards_against_isize { |
| 4164 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) { |
| 4165 |
} else { panic!("isize::MAX + 1 should trigger an overflow!"); } |
| 4166 |
} else { |
| 4167 |
if let Err(AllocErr) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) { |
| 4168 |
} else { panic!("isize::MAX + 1 should trigger an OOM!") } |
| 4169 |
} |
| 4170 |
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_USIZE - 20) { |
| 4171 |
} else { panic!("usize::MAX should trigger an overflow!") } |
| 4172 |
} |
| 4173 |
} |
| 4174 |
*/ |
| 4175 |
|
| 4176 |
#[test] |
| 4177 |
#[cfg_attr(feature = "gecko-ffi", ignore)] |
| 4178 |
fn test_header_data() { |
| 4179 |
macro_rules! assert_aligned_head_ptr { |
| 4180 |
($typename:ty) => {{ |
| 4181 |
let v: ThinVec<$typename> = ThinVec::with_capacity(1 /* ensure allocation */); |
| 4182 |
let head_ptr: *mut $typename = v.data_raw(); |
| 4183 |
assert_eq!( |
| 4184 |
head_ptr as usize % std::mem::align_of::<$typename>(), |
| 4185 |
0, |
| 4186 |
"expected Header::data<{}> to be aligned", |
| 4187 |
stringify!($typename) |
| 4188 |
); |
| 4189 |
}}; |
| 4190 |
} |
| 4191 |
|
| 4192 |
const HEADER_SIZE: usize = std::mem::size_of::<Header>(); |
| 4193 |
assert_eq!(2 * std::mem::size_of::<usize>(), HEADER_SIZE); |
| 4194 |
|
| 4195 |
#[repr(C, align(128))] |
| 4196 |
struct Funky<T>(T); |
| 4197 |
assert_eq!(padding::<Funky<()>>(), 128 - HEADER_SIZE); |
| 4198 |
assert_aligned_head_ptr!(Funky<()>); |
| 4199 |
|
| 4200 |
assert_eq!(padding::<Funky<u8>>(), 128 - HEADER_SIZE); |
| 4201 |
assert_aligned_head_ptr!(Funky<u8>); |
| 4202 |
|
| 4203 |
assert_eq!(padding::<Funky<[(); 1024]>>(), 128 - HEADER_SIZE); |
| 4204 |
assert_aligned_head_ptr!(Funky<[(); 1024]>); |
| 4205 |
|
| 4206 |
assert_eq!(padding::<Funky<[*mut usize; 1024]>>(), 128 - HEADER_SIZE); |
| 4207 |
assert_aligned_head_ptr!(Funky<[*mut usize; 1024]>); |
| 4208 |
} |
| 4209 |
|
| 4210 |
#[cfg(feature = "serde")] |
| 4211 |
use serde_test::{assert_tokens, Token}; |
| 4212 |
|
| 4213 |
#[test] |
| 4214 |
#[cfg(feature = "serde")] |
| 4215 |
fn test_ser_de_empty() { |
| 4216 |
let vec = ThinVec::<u32>::new(); |
| 4217 |
|
| 4218 |
assert_tokens(&vec, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); |
| 4219 |
} |
| 4220 |
|
| 4221 |
#[test] |
| 4222 |
#[cfg(feature = "serde")] |
| 4223 |
fn test_ser_de() { |
| 4224 |
let mut vec = ThinVec::<u32>::new(); |
| 4225 |
vec.push(20); |
| 4226 |
vec.push(55); |
| 4227 |
vec.push(123); |
| 4228 |
|
| 4229 |
assert_tokens( |
| 4230 |
&vec, |
| 4231 |
&[ |
| 4232 |
Token::Seq { len: Some(3) }, |
| 4233 |
Token::U32(20), |
| 4234 |
Token::U32(55), |
| 4235 |
Token::U32(123), |
| 4236 |
Token::SeqEnd, |
| 4237 |
], |
| 4238 |
); |
| 4239 |
} |
| 4240 |
|
| 4241 |
#[test] |
| 4242 |
fn test_set_len() { |
| 4243 |
let mut vec: ThinVec<u32> = thin_vec![]; |
| 4244 |
unsafe { |
| 4245 |
vec.set_len(0); // at one point this caused a crash |
| 4246 |
} |
| 4247 |
} |
| 4248 |
|
| 4249 |
#[test] |
| 4250 |
#[should_panic(expected = "invalid set_len(1) on empty ThinVec")] |
| 4251 |
fn test_set_len_invalid() { |
| 4252 |
let mut vec: ThinVec<u32> = thin_vec![]; |
| 4253 |
unsafe { |
| 4254 |
vec.set_len(1); |
| 4255 |
} |
| 4256 |
} |
| 4257 |
|
| 4258 |
#[test] |
| 4259 |
#[should_panic(expected = "capacity overflow")] |
| 4260 |
fn test_capacity_overflow_header_too_big() { |
| 4261 |
let vec: ThinVec<u8> = ThinVec::with_capacity(isize::MAX as usize - 2); |
| 4262 |
assert!(vec.capacity() > 0); |
| 4263 |
} |
| 4264 |
#[test] |
| 4265 |
#[should_panic(expected = "capacity overflow")] |
| 4266 |
fn test_capacity_overflow_cap_too_big() { |
| 4267 |
let vec: ThinVec<u8> = ThinVec::with_capacity(isize::MAX as usize + 1); |
| 4268 |
assert!(vec.capacity() > 0); |
| 4269 |
} |
| 4270 |
#[test] |
| 4271 |
#[should_panic(expected = "capacity overflow")] |
| 4272 |
fn test_capacity_overflow_size_mul1() { |
| 4273 |
let vec: ThinVec<u16> = ThinVec::with_capacity(isize::MAX as usize + 1); |
| 4274 |
assert!(vec.capacity() > 0); |
| 4275 |
} |
| 4276 |
#[test] |
| 4277 |
#[should_panic(expected = "capacity overflow")] |
| 4278 |
fn test_capacity_overflow_size_mul2() { |
| 4279 |
let vec: ThinVec<u16> = ThinVec::with_capacity(isize::MAX as usize / 2 + 1); |
| 4280 |
assert!(vec.capacity() > 0); |
| 4281 |
} |
| 4282 |
#[test] |
| 4283 |
#[should_panic(expected = "capacity overflow")] |
| 4284 |
fn test_capacity_overflow_cap_really_isnt_isize() { |
| 4285 |
let vec: ThinVec<u8> = ThinVec::with_capacity(isize::MAX as usize); |
| 4286 |
assert!(vec.capacity() > 0); |
| 4287 |
} |
| 4288 |
} |