1 | #![unstable (feature = "raw_vec_internals" , reason = "unstable const warnings" , issue = "none" )] |
2 | |
3 | use core::alloc::LayoutError; |
4 | use core::cmp; |
5 | use core::hint; |
6 | use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; |
7 | use core::ptr::{self, NonNull, Unique}; |
8 | |
9 | #[cfg (not(no_global_oom_handling))] |
10 | use crate::alloc::handle_alloc_error; |
11 | use crate::alloc::{Allocator, Global, Layout}; |
12 | use crate::boxed::Box; |
13 | use crate::collections::TryReserveError; |
14 | use crate::collections::TryReserveErrorKind::*; |
15 | |
16 | #[cfg (test)] |
17 | mod tests; |
18 | |
19 | // One central function responsible for reporting capacity overflows. This'll |
20 | // ensure that the code generation related to these panics is minimal as there's |
21 | // only one location which panics rather than a bunch throughout the module. |
22 | #[cfg (not(no_global_oom_handling))] |
23 | #[cfg_attr (not(feature = "panic_immediate_abort" ), inline(never))] |
24 | fn capacity_overflow() -> ! { |
25 | panic!("capacity overflow" ); |
26 | } |
27 | |
28 | enum AllocInit { |
29 | /// The contents of the new memory are uninitialized. |
30 | Uninitialized, |
31 | #[cfg (not(no_global_oom_handling))] |
32 | /// The new memory is guaranteed to be zeroed. |
33 | Zeroed, |
34 | } |
35 | |
36 | #[repr (transparent)] |
37 | #[cfg_attr (target_pointer_width = "16" , rustc_layout_scalar_valid_range_end(0x7fff))] |
38 | #[cfg_attr (target_pointer_width = "32" , rustc_layout_scalar_valid_range_end(0x7fff_ffff))] |
39 | #[cfg_attr (target_pointer_width = "64" , rustc_layout_scalar_valid_range_end(0x7fff_ffff_ffff_ffff))] |
40 | struct Cap(usize); |
41 | |
42 | impl Cap { |
43 | const ZERO: Cap = unsafe { Cap(0) }; |
44 | } |
45 | |
46 | /// A low-level utility for more ergonomically allocating, reallocating, and deallocating |
47 | /// a buffer of memory on the heap without having to worry about all the corner cases |
48 | /// involved. This type is excellent for building your own data structures like Vec and VecDeque. |
49 | /// In particular: |
50 | /// |
51 | /// * Produces `Unique::dangling()` on zero-sized types. |
52 | /// * Produces `Unique::dangling()` on zero-length allocations. |
53 | /// * Avoids freeing `Unique::dangling()`. |
54 | /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics). |
55 | /// * Guards against 32-bit systems allocating more than isize::MAX bytes. |
56 | /// * Guards against overflowing your length. |
57 | /// * Calls `handle_alloc_error` for fallible allocations. |
58 | /// * Contains a `ptr::Unique` and thus endows the user with all related benefits. |
59 | /// * Uses the excess returned from the allocator to use the largest available capacity. |
60 | /// |
61 | /// This type does not in anyway inspect the memory that it manages. When dropped it *will* |
62 | /// free its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec` |
63 | /// to handle the actual things *stored* inside of a `RawVec`. |
64 | /// |
65 | /// Note that the excess of a zero-sized types is always infinite, so `capacity()` always returns |
66 | /// `usize::MAX`. This means that you need to be careful when round-tripping this type with a |
67 | /// `Box<[T]>`, since `capacity()` won't yield the length. |
68 | #[allow (missing_debug_implementations)] |
69 | pub(crate) struct RawVec<T, A: Allocator = Global> { |
70 | ptr: Unique<T>, |
71 | /// Never used for ZSTs; it's `capacity()`'s responsibility to return usize::MAX in that case. |
72 | /// |
73 | /// # Safety |
74 | /// |
75 | /// `cap` must be in the `0..=isize::MAX` range. |
76 | cap: Cap, |
77 | alloc: A, |
78 | } |
79 | |
80 | impl<T> RawVec<T, Global> { |
81 | /// HACK(Centril): This exists because stable `const fn` can only call stable `const fn`, so |
82 | /// they cannot call `Self::new()`. |
83 | /// |
84 | /// If you change `RawVec<T>::new` or dependencies, please take care to not introduce anything |
85 | /// that would truly const-call something unstable. |
86 | pub const NEW: Self = Self::new(); |
87 | |
88 | /// Creates the biggest possible `RawVec` (on the system heap) |
89 | /// without allocating. If `T` has positive size, then this makes a |
90 | /// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a |
91 | /// `RawVec` with capacity `usize::MAX`. Useful for implementing |
92 | /// delayed allocation. |
93 | #[must_use ] |
94 | pub const fn new() -> Self { |
95 | Self::new_in(Global) |
96 | } |
97 | |
98 | /// Creates a `RawVec` (on the system heap) with exactly the |
99 | /// capacity and alignment requirements for a `[T; capacity]`. This is |
100 | /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is |
101 | /// zero-sized. Note that if `T` is zero-sized this means you will |
102 | /// *not* get a `RawVec` with the requested capacity. |
103 | /// |
104 | /// Non-fallible version of `try_with_capacity` |
105 | /// |
106 | /// # Panics |
107 | /// |
108 | /// Panics if the requested capacity exceeds `isize::MAX` bytes. |
109 | /// |
110 | /// # Aborts |
111 | /// |
112 | /// Aborts on OOM. |
113 | #[cfg (not(any(no_global_oom_handling, test)))] |
114 | #[must_use ] |
115 | #[inline ] |
116 | pub fn with_capacity(capacity: usize) -> Self { |
117 | match Self::try_allocate_in(capacity, AllocInit::Uninitialized, Global) { |
118 | Ok(res) => res, |
119 | Err(err) => handle_error(err), |
120 | } |
121 | } |
122 | |
123 | /// Like `with_capacity`, but guarantees the buffer is zeroed. |
124 | #[cfg (not(any(no_global_oom_handling, test)))] |
125 | #[must_use ] |
126 | #[inline ] |
127 | pub fn with_capacity_zeroed(capacity: usize) -> Self { |
128 | Self::with_capacity_zeroed_in(capacity, Global) |
129 | } |
130 | } |
131 | |
132 | impl<T, A: Allocator> RawVec<T, A> { |
133 | // Tiny Vecs are dumb. Skip to: |
134 | // - 8 if the element size is 1, because any heap allocators is likely |
135 | // to round up a request of less than 8 bytes to at least 8 bytes. |
136 | // - 4 if elements are moderate-sized (<= 1 KiB). |
137 | // - 1 otherwise, to avoid wasting too much space for very short Vecs. |
138 | pub(crate) const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 { |
139 | 8 |
140 | } else if mem::size_of::<T>() <= 1024 { |
141 | 4 |
142 | } else { |
143 | 1 |
144 | }; |
145 | |
146 | /// Like `new`, but parameterized over the choice of allocator for |
147 | /// the returned `RawVec`. |
148 | pub const fn new_in(alloc: A) -> Self { |
149 | // `cap: 0` means "unallocated". zero-sized types are ignored. |
150 | Self { ptr: Unique::dangling(), cap: Cap::ZERO, alloc } |
151 | } |
152 | |
153 | /// Like `with_capacity`, but parameterized over the choice of |
154 | /// allocator for the returned `RawVec`. |
155 | #[cfg (not(no_global_oom_handling))] |
156 | #[inline ] |
157 | pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { |
158 | match Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc) { |
159 | Ok(res) => res, |
160 | Err(err) => handle_error(err), |
161 | } |
162 | } |
163 | |
164 | /// Like `try_with_capacity`, but parameterized over the choice of |
165 | /// allocator for the returned `RawVec`. |
166 | #[inline ] |
167 | pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> { |
168 | Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc) |
169 | } |
170 | |
171 | /// Like `with_capacity_zeroed`, but parameterized over the choice |
172 | /// of allocator for the returned `RawVec`. |
173 | #[cfg (not(no_global_oom_handling))] |
174 | #[inline ] |
175 | pub fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self { |
176 | match Self::try_allocate_in(capacity, AllocInit::Zeroed, alloc) { |
177 | Ok(res) => res, |
178 | Err(err) => handle_error(err), |
179 | } |
180 | } |
181 | |
182 | /// Converts the entire buffer into `Box<[MaybeUninit<T>]>` with the specified `len`. |
183 | /// |
184 | /// Note that this will correctly reconstitute any `cap` changes |
185 | /// that may have been performed. (See description of type for details.) |
186 | /// |
187 | /// # Safety |
188 | /// |
189 | /// * `len` must be greater than or equal to the most recently requested capacity, and |
190 | /// * `len` must be less than or equal to `self.capacity()`. |
191 | /// |
192 | /// Note, that the requested capacity and `self.capacity()` could differ, as |
193 | /// an allocator could overallocate and return a greater memory block than requested. |
194 | pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit<T>], A> { |
195 | // Sanity-check one half of the safety requirement (we cannot check the other half). |
196 | debug_assert!( |
197 | len <= self.capacity(), |
198 | "`len` must be smaller than or equal to `self.capacity()`" |
199 | ); |
200 | |
201 | let me = ManuallyDrop::new(self); |
202 | unsafe { |
203 | let slice = ptr::slice_from_raw_parts_mut(me.ptr() as *mut MaybeUninit<T>, len); |
204 | Box::from_raw_in(slice, ptr::read(&me.alloc)) |
205 | } |
206 | } |
207 | |
208 | fn try_allocate_in( |
209 | capacity: usize, |
210 | init: AllocInit, |
211 | alloc: A, |
212 | ) -> Result<Self, TryReserveError> { |
213 | // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. |
214 | |
215 | if T::IS_ZST || capacity == 0 { |
216 | Ok(Self::new_in(alloc)) |
217 | } else { |
218 | // We avoid `unwrap_or_else` here because it bloats the amount of |
219 | // LLVM IR generated. |
220 | let layout = match Layout::array::<T>(capacity) { |
221 | Ok(layout) => layout, |
222 | Err(_) => return Err(CapacityOverflow.into()), |
223 | }; |
224 | |
225 | if let Err(err) = alloc_guard(layout.size()) { |
226 | return Err(err); |
227 | } |
228 | |
229 | let result = match init { |
230 | AllocInit::Uninitialized => alloc.allocate(layout), |
231 | #[cfg (not(no_global_oom_handling))] |
232 | AllocInit::Zeroed => alloc.allocate_zeroed(layout), |
233 | }; |
234 | let ptr = match result { |
235 | Ok(ptr) => ptr, |
236 | Err(_) => return Err(AllocError { layout, non_exhaustive: () }.into()), |
237 | }; |
238 | |
239 | // Allocators currently return a `NonNull<[u8]>` whose length |
240 | // matches the size requested. If that ever changes, the capacity |
241 | // here should change to `ptr.len() / mem::size_of::<T>()`. |
242 | Ok(Self { ptr: Unique::from(ptr.cast()), cap: unsafe { Cap(capacity) }, alloc }) |
243 | } |
244 | } |
245 | |
246 | /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator. |
247 | /// |
248 | /// # Safety |
249 | /// |
250 | /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given |
251 | /// `capacity`. |
252 | /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit |
253 | /// systems). For ZSTs capacity is ignored. |
254 | /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is |
255 | /// guaranteed. |
256 | #[inline ] |
257 | pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self { |
258 | let cap = if T::IS_ZST { Cap::ZERO } else { unsafe { Cap(capacity) } }; |
259 | Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap, alloc } |
260 | } |
261 | |
262 | /// A convenience method for hoisting the non-null precondition out of [`RawVec::from_raw_parts_in`]. |
263 | /// |
264 | /// # Safety |
265 | /// |
266 | /// See [`RawVec::from_raw_parts_in`]. |
267 | #[inline ] |
268 | pub(crate) unsafe fn from_nonnull_in(ptr: NonNull<T>, capacity: usize, alloc: A) -> Self { |
269 | let cap = if T::IS_ZST { Cap::ZERO } else { unsafe { Cap(capacity) } }; |
270 | Self { ptr: Unique::from(ptr), cap, alloc } |
271 | } |
272 | |
273 | /// Gets a raw pointer to the start of the allocation. Note that this is |
274 | /// `Unique::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must |
275 | /// be careful. |
276 | #[inline ] |
277 | pub fn ptr(&self) -> *mut T { |
278 | self.ptr.as_ptr() |
279 | } |
280 | |
281 | #[inline ] |
282 | pub fn non_null(&self) -> NonNull<T> { |
283 | NonNull::from(self.ptr) |
284 | } |
285 | |
286 | /// Gets the capacity of the allocation. |
287 | /// |
288 | /// This will always be `usize::MAX` if `T` is zero-sized. |
289 | #[inline (always)] |
290 | pub fn capacity(&self) -> usize { |
291 | if T::IS_ZST { usize::MAX } else { self.cap.0 } |
292 | } |
293 | |
294 | /// Returns a shared reference to the allocator backing this `RawVec`. |
295 | pub fn allocator(&self) -> &A { |
296 | &self.alloc |
297 | } |
298 | |
299 | fn current_memory(&self) -> Option<(NonNull<u8>, Layout)> { |
300 | if T::IS_ZST || self.cap.0 == 0 { |
301 | None |
302 | } else { |
303 | // We could use Layout::array here which ensures the absence of isize and usize overflows |
304 | // and could hypothetically handle differences between stride and size, but this memory |
305 | // has already been allocated so we know it can't overflow and currently Rust does not |
306 | // support such types. So we can do better by skipping some checks and avoid an unwrap. |
307 | const { assert!(mem::size_of::<T>() % mem::align_of::<T>() == 0) }; |
308 | unsafe { |
309 | let align = mem::align_of::<T>(); |
310 | let size = mem::size_of::<T>().unchecked_mul(self.cap.0); |
311 | let layout = Layout::from_size_align_unchecked(size, align); |
312 | Some((self.ptr.cast().into(), layout)) |
313 | } |
314 | } |
315 | } |
316 | |
317 | /// Ensures that the buffer contains at least enough space to hold `len + |
318 | /// additional` elements. If it doesn't already have enough capacity, will |
319 | /// reallocate enough space plus comfortable slack space to get amortized |
320 | /// *O*(1) behavior. Will limit this behavior if it would needlessly cause |
321 | /// itself to panic. |
322 | /// |
323 | /// If `len` exceeds `self.capacity()`, this may fail to actually allocate |
324 | /// the requested space. This is not really unsafe, but the unsafe |
325 | /// code *you* write that relies on the behavior of this function may break. |
326 | /// |
327 | /// This is ideal for implementing a bulk-push operation like `extend`. |
328 | /// |
329 | /// # Panics |
330 | /// |
331 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
332 | /// |
333 | /// # Aborts |
334 | /// |
335 | /// Aborts on OOM. |
336 | #[cfg (not(no_global_oom_handling))] |
337 | #[inline ] |
338 | pub fn reserve(&mut self, len: usize, additional: usize) { |
339 | // Callers expect this function to be very cheap when there is already sufficient capacity. |
340 | // Therefore, we move all the resizing and error-handling logic from grow_amortized and |
341 | // handle_reserve behind a call, while making sure that this function is likely to be |
342 | // inlined as just a comparison and a call if the comparison fails. |
343 | #[cold ] |
344 | fn do_reserve_and_handle<T, A: Allocator>( |
345 | slf: &mut RawVec<T, A>, |
346 | len: usize, |
347 | additional: usize, |
348 | ) { |
349 | if let Err(err) = slf.grow_amortized(len, additional) { |
350 | handle_error(err); |
351 | } |
352 | } |
353 | |
354 | if self.needs_to_grow(len, additional) { |
355 | do_reserve_and_handle(self, len, additional); |
356 | } |
357 | } |
358 | |
359 | /// A specialized version of `self.reserve(len, 1)` which requires the |
360 | /// caller to ensure `len == self.capacity()`. |
361 | #[cfg (not(no_global_oom_handling))] |
362 | #[inline (never)] |
363 | pub fn grow_one(&mut self) { |
364 | if let Err(err) = self.grow_amortized(self.cap.0, 1) { |
365 | handle_error(err); |
366 | } |
367 | } |
368 | |
369 | /// The same as `reserve`, but returns on errors instead of panicking or aborting. |
370 | pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { |
371 | if self.needs_to_grow(len, additional) { |
372 | self.grow_amortized(len, additional)?; |
373 | } |
374 | unsafe { |
375 | // Inform the optimizer that the reservation has succeeded or wasn't needed |
376 | hint::assert_unchecked(!self.needs_to_grow(len, additional)); |
377 | } |
378 | Ok(()) |
379 | } |
380 | |
381 | /// Ensures that the buffer contains at least enough space to hold `len + |
382 | /// additional` elements. If it doesn't already, will reallocate the |
383 | /// minimum possible amount of memory necessary. Generally this will be |
384 | /// exactly the amount of memory necessary, but in principle the allocator |
385 | /// is free to give back more than we asked for. |
386 | /// |
387 | /// If `len` exceeds `self.capacity()`, this may fail to actually allocate |
388 | /// the requested space. This is not really unsafe, but the unsafe code |
389 | /// *you* write that relies on the behavior of this function may break. |
390 | /// |
391 | /// # Panics |
392 | /// |
393 | /// Panics if the new capacity exceeds `isize::MAX` _bytes_. |
394 | /// |
395 | /// # Aborts |
396 | /// |
397 | /// Aborts on OOM. |
398 | #[cfg (not(no_global_oom_handling))] |
399 | pub fn reserve_exact(&mut self, len: usize, additional: usize) { |
400 | if let Err(err) = self.try_reserve_exact(len, additional) { |
401 | handle_error(err); |
402 | } |
403 | } |
404 | |
405 | /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. |
406 | pub fn try_reserve_exact( |
407 | &mut self, |
408 | len: usize, |
409 | additional: usize, |
410 | ) -> Result<(), TryReserveError> { |
411 | if self.needs_to_grow(len, additional) { |
412 | self.grow_exact(len, additional)?; |
413 | } |
414 | unsafe { |
415 | // Inform the optimizer that the reservation has succeeded or wasn't needed |
416 | hint::assert_unchecked(!self.needs_to_grow(len, additional)); |
417 | } |
418 | Ok(()) |
419 | } |
420 | |
421 | /// Shrinks the buffer down to the specified capacity. If the given amount |
422 | /// is 0, actually completely deallocates. |
423 | /// |
424 | /// # Panics |
425 | /// |
426 | /// Panics if the given amount is *larger* than the current capacity. |
427 | /// |
428 | /// # Aborts |
429 | /// |
430 | /// Aborts on OOM. |
431 | #[cfg (not(no_global_oom_handling))] |
432 | pub fn shrink_to_fit(&mut self, cap: usize) { |
433 | if let Err(err) = self.shrink(cap) { |
434 | handle_error(err); |
435 | } |
436 | } |
437 | } |
438 | |
439 | impl<T, A: Allocator> RawVec<T, A> { |
440 | /// Returns if the buffer needs to grow to fulfill the needed extra capacity. |
441 | /// Mainly used to make inlining reserve-calls possible without inlining `grow`. |
442 | fn needs_to_grow(&self, len: usize, additional: usize) -> bool { |
443 | additional > self.capacity().wrapping_sub(len) |
444 | } |
445 | |
446 | /// # Safety: |
447 | /// |
448 | /// `cap` must not exceed `isize::MAX`. |
449 | unsafe fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) { |
450 | // Allocators currently return a `NonNull<[u8]>` whose length matches |
451 | // the size requested. If that ever changes, the capacity here should |
452 | // change to `ptr.len() / mem::size_of::<T>()`. |
453 | self.ptr = Unique::from(ptr.cast()); |
454 | self.cap = unsafe { Cap(cap) }; |
455 | } |
456 | |
457 | // This method is usually instantiated many times. So we want it to be as |
458 | // small as possible, to improve compile times. But we also want as much of |
459 | // its contents to be statically computable as possible, to make the |
460 | // generated code run faster. Therefore, this method is carefully written |
461 | // so that all of the code that depends on `T` is within it, while as much |
462 | // of the code that doesn't depend on `T` as possible is in functions that |
463 | // are non-generic over `T`. |
464 | fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { |
465 | // This is ensured by the calling contexts. |
466 | debug_assert!(additional > 0); |
467 | |
468 | if T::IS_ZST { |
469 | // Since we return a capacity of `usize::MAX` when `elem_size` is |
470 | // 0, getting to here necessarily means the `RawVec` is overfull. |
471 | return Err(CapacityOverflow.into()); |
472 | } |
473 | |
474 | // Nothing we can really do about these checks, sadly. |
475 | let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; |
476 | |
477 | // This guarantees exponential growth. The doubling cannot overflow |
478 | // because `cap <= isize::MAX` and the type of `cap` is `usize`. |
479 | let cap = cmp::max(self.cap.0 * 2, required_cap); |
480 | let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap); |
481 | |
482 | let new_layout = Layout::array::<T>(cap); |
483 | |
484 | // `finish_grow` is non-generic over `T`. |
485 | let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; |
486 | // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items |
487 | unsafe { self.set_ptr_and_cap(ptr, cap) }; |
488 | Ok(()) |
489 | } |
490 | |
491 | // The constraints on this method are much the same as those on |
492 | // `grow_amortized`, but this method is usually instantiated less often so |
493 | // it's less critical. |
494 | fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { |
495 | if T::IS_ZST { |
496 | // Since we return a capacity of `usize::MAX` when the type size is |
497 | // 0, getting to here necessarily means the `RawVec` is overfull. |
498 | return Err(CapacityOverflow.into()); |
499 | } |
500 | |
501 | let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; |
502 | let new_layout = Layout::array::<T>(cap); |
503 | |
504 | // `finish_grow` is non-generic over `T`. |
505 | let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; |
506 | // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items |
507 | unsafe { |
508 | self.set_ptr_and_cap(ptr, cap); |
509 | } |
510 | Ok(()) |
511 | } |
512 | |
513 | #[cfg (not(no_global_oom_handling))] |
514 | fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> { |
515 | assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity" ); |
516 | |
517 | let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) }; |
518 | // See current_memory() why this assert is here |
519 | const { assert!(mem::size_of::<T>() % mem::align_of::<T>() == 0) }; |
520 | |
521 | // If shrinking to 0, deallocate the buffer. We don't reach this point |
522 | // for the T::IS_ZST case since current_memory() will have returned |
523 | // None. |
524 | if cap == 0 { |
525 | unsafe { self.alloc.deallocate(ptr, layout) }; |
526 | self.ptr = Unique::dangling(); |
527 | self.cap = Cap::ZERO; |
528 | } else { |
529 | let ptr = unsafe { |
530 | // `Layout::array` cannot overflow here because it would have |
531 | // overflowed earlier when capacity was larger. |
532 | let new_size = mem::size_of::<T>().unchecked_mul(cap); |
533 | let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); |
534 | self.alloc |
535 | .shrink(ptr, layout, new_layout) |
536 | .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })? |
537 | }; |
538 | // SAFETY: if the allocation is valid, then the capacity is too |
539 | unsafe { |
540 | self.set_ptr_and_cap(ptr, cap); |
541 | } |
542 | } |
543 | Ok(()) |
544 | } |
545 | } |
546 | |
547 | // This function is outside `RawVec` to minimize compile times. See the comment |
548 | // above `RawVec::grow_amortized` for details. (The `A` parameter isn't |
549 | // significant, because the number of different `A` types seen in practice is |
550 | // much smaller than the number of `T` types.) |
551 | #[inline (never)] |
552 | fn finish_grow<A>( |
553 | new_layout: Result<Layout, LayoutError>, |
554 | current_memory: Option<(NonNull<u8>, Layout)>, |
555 | alloc: &mut A, |
556 | ) -> Result<NonNull<[u8]>, TryReserveError> |
557 | where |
558 | A: Allocator, |
559 | { |
560 | // Check for the error here to minimize the size of `RawVec::grow_*`. |
561 | let new_layout: Layout = new_layout.map_err(|_| CapacityOverflow)?; |
562 | |
563 | alloc_guard(alloc_size:new_layout.size())?; |
564 | |
565 | let memory: Result, AllocError> = if let Some((ptr: NonNull, old_layout: Layout)) = current_memory { |
566 | debug_assert_eq!(old_layout.align(), new_layout.align()); |
567 | unsafe { |
568 | // The allocator checks for alignment equality |
569 | hint::assert_unchecked(cond:old_layout.align() == new_layout.align()); |
570 | alloc.grow(ptr, old_layout, new_layout) |
571 | } |
572 | } else { |
573 | alloc.allocate(new_layout) |
574 | }; |
575 | |
576 | memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into()) |
577 | } |
578 | |
579 | unsafe impl<#[may_dangle ] T, A: Allocator> Drop for RawVec<T, A> { |
580 | /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. |
581 | fn drop(&mut self) { |
582 | if let Some((ptr: NonNull, layout: Layout)) = self.current_memory() { |
583 | unsafe { self.alloc.deallocate(ptr, layout) } |
584 | } |
585 | } |
586 | } |
587 | |
588 | // Central function for reserve error handling. |
589 | #[cfg (not(no_global_oom_handling))] |
590 | #[cold ] |
591 | fn handle_error(e: TryReserveError) -> ! { |
592 | match e.kind() { |
593 | CapacityOverflow => capacity_overflow(), |
594 | AllocError { layout: Layout, .. } => handle_alloc_error(layout), |
595 | } |
596 | } |
597 | |
598 | // We need to guarantee the following: |
599 | // * We don't ever allocate `> isize::MAX` byte-size objects. |
600 | // * We don't overflow `usize::MAX` and actually allocate too little. |
601 | // |
602 | // On 64-bit we just need to check for overflow since trying to allocate |
603 | // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add |
604 | // an extra guard for this in case we're running on a platform which can use |
605 | // all 4GB in user-space, e.g., PAE or x32. |
606 | #[inline ] |
607 | fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> { |
608 | if usize::BITS < 64 && alloc_size > isize::MAX as usize { |
609 | Err(CapacityOverflow.into()) |
610 | } else { |
611 | Ok(()) |
612 | } |
613 | } |
614 | |