2021-11-03 19:47:00 +00:00
|
|
|
#![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")]
|
2018-06-15 01:36:34 +00:00
|
|
|
|
2020-09-25 03:48:26 +00:00
|
|
|
use core::alloc::LayoutError;
|
2019-02-03 07:27:44 +00:00
|
|
|
use core::cmp;
|
2020-08-20 09:55:41 +00:00
|
|
|
use core::intrinsics;
|
2022-09-23 06:12:29 +00:00
|
|
|
use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties};
|
2020-10-06 14:37:23 +00:00
|
|
|
use core::ptr::{self, NonNull, Unique};
|
2019-02-03 07:27:44 +00:00
|
|
|
use core::slice;
|
2019-02-02 09:14:40 +00:00
|
|
|
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
|
|
|
use crate::alloc::handle_alloc_error;
|
|
|
|
use crate::alloc::{Allocator, Global, Layout};
|
2019-02-03 07:27:44 +00:00
|
|
|
use crate::boxed::Box;
|
2021-07-23 15:40:43 +00:00
|
|
|
use crate::collections::TryReserveError;
|
|
|
|
use crate::collections::TryReserveErrorKind::*;
|
2015-07-10 04:57:21 +00:00
|
|
|
|
2019-08-01 22:40:56 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests;
|
|
|
|
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2020-07-28 10:41:18 +00:00
|
|
|
enum AllocInit {
|
|
|
|
/// The contents of the new memory are uninitialized.
|
|
|
|
Uninitialized,
|
|
|
|
/// The new memory is guaranteed to be zeroed.
|
|
|
|
Zeroed,
|
|
|
|
}
|
|
|
|
|
2016-08-14 04:59:43 +00:00
|
|
|
/// A low-level utility for more ergonomically allocating, reallocating, and deallocating
|
2015-07-10 04:57:21 +00:00
|
|
|
/// a buffer of memory on the heap without having to worry about all the corner cases
|
|
|
|
/// involved. This type is excellent for building your own data structures like Vec and VecDeque.
|
|
|
|
/// In particular:
|
|
|
|
///
|
2020-04-30 09:00:45 +00:00
|
|
|
/// * Produces `Unique::dangling()` on zero-sized types.
|
|
|
|
/// * Produces `Unique::dangling()` on zero-length allocations.
|
|
|
|
/// * Avoids freeing `Unique::dangling()`.
|
2019-09-05 16:15:28 +00:00
|
|
|
/// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics).
|
|
|
|
/// * Guards against 32-bit systems allocating more than isize::MAX bytes.
|
|
|
|
/// * Guards against overflowing your length.
|
2020-03-24 10:45:38 +00:00
|
|
|
/// * Calls `handle_alloc_error` for fallible allocations.
|
2019-09-05 16:15:28 +00:00
|
|
|
/// * Contains a `ptr::Unique` and thus endows the user with all related benefits.
|
2020-03-24 10:45:38 +00:00
|
|
|
/// * Uses the excess returned from the allocator to use the largest available capacity.
|
2015-07-10 04:57:21 +00:00
|
|
|
///
|
|
|
|
/// This type does not in anyway inspect the memory that it manages. When dropped it *will*
|
2019-09-05 16:15:28 +00:00
|
|
|
/// free its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec`
|
|
|
|
/// to handle the actual things *stored* inside of a `RawVec`.
|
2015-07-10 04:57:21 +00:00
|
|
|
///
|
2020-03-24 10:45:38 +00:00
|
|
|
/// Note that the excess of a zero-sized types is always infinite, so `capacity()` always returns
|
|
|
|
/// `usize::MAX`. This means that you need to be careful when round-tripping this type with a
|
2020-03-25 17:42:31 +00:00
|
|
|
/// `Box<[T]>`, since `capacity()` won't yield the length.
|
2017-06-13 22:52:59 +00:00
|
|
|
#[allow(missing_debug_implementations)]
|
2021-11-03 19:47:00 +00:00
|
|
|
pub(crate) struct RawVec<T, A: Allocator = Global> {
|
2015-07-10 04:57:21 +00:00
|
|
|
ptr: Unique<T>,
|
|
|
|
cap: usize,
|
2020-03-26 16:11:47 +00:00
|
|
|
alloc: A,
|
2017-05-24 16:06:11 +00:00
|
|
|
}
|
|
|
|
|
2018-04-03 19:15:06 +00:00
|
|
|
impl<T> RawVec<T, Global> {
|
2021-04-25 11:59:10 +00:00
|
|
|
/// HACK(Centril): This exists because stable `const fn` can only call stable `const fn`, so
|
|
|
|
/// they cannot call `Self::new()`.
|
2019-08-29 09:32:38 +00:00
|
|
|
///
|
2021-04-25 11:59:10 +00:00
|
|
|
/// If you change `RawVec<T>::new` or dependencies, please take care to not introduce anything
|
|
|
|
/// that would truly const-call something unstable.
|
2019-08-29 09:32:38 +00:00
|
|
|
pub const NEW: Self = Self::new();
|
|
|
|
|
2019-09-05 16:15:28 +00:00
|
|
|
/// Creates the biggest possible `RawVec` (on the system heap)
|
|
|
|
/// without allocating. If `T` has positive size, then this makes a
|
|
|
|
/// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a
|
|
|
|
/// `RawVec` with capacity `usize::MAX`. Useful for implementing
|
2017-05-24 16:06:11 +00:00
|
|
|
/// delayed allocation.
|
2021-10-10 05:50:06 +00:00
|
|
|
#[must_use]
|
2019-11-25 20:44:19 +00:00
|
|
|
pub const fn new() -> Self {
|
2019-11-25 21:29:57 +00:00
|
|
|
Self::new_in(Global)
|
2017-05-24 16:06:11 +00:00
|
|
|
}
|
|
|
|
|
2019-09-05 16:15:28 +00:00
|
|
|
/// Creates a `RawVec` (on the system heap) with exactly the
|
2019-04-27 19:28:40 +00:00
|
|
|
/// capacity and alignment requirements for a `[T; capacity]`. This is
|
2019-09-05 16:15:28 +00:00
|
|
|
/// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is
|
2017-05-24 16:06:11 +00:00
|
|
|
/// zero-sized. Note that if `T` is zero-sized this means you will
|
2019-09-05 16:15:28 +00:00
|
|
|
/// *not* get a `RawVec` with the requested capacity.
|
2017-05-24 16:06:11 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
2020-06-16 04:23:28 +00:00
|
|
|
/// Panics if the requested capacity exceeds `isize::MAX` bytes.
|
2017-05-24 16:06:11 +00:00
|
|
|
///
|
|
|
|
/// # Aborts
|
|
|
|
///
|
2019-09-05 16:15:28 +00:00
|
|
|
/// Aborts on OOM.
|
2021-11-03 19:47:00 +00:00
|
|
|
#[cfg(not(any(no_global_oom_handling, test)))]
|
2021-10-10 05:50:06 +00:00
|
|
|
#[must_use]
|
2017-05-24 16:06:11 +00:00
|
|
|
#[inline]
|
2019-04-27 19:28:40 +00:00
|
|
|
pub fn with_capacity(capacity: usize) -> Self {
|
2020-03-24 10:45:38 +00:00
|
|
|
Self::with_capacity_in(capacity, Global)
|
2017-05-24 16:06:11 +00:00
|
|
|
}
|
|
|
|
|
2019-09-05 16:15:28 +00:00
|
|
|
/// Like `with_capacity`, but guarantees the buffer is zeroed.
|
2021-11-03 19:47:00 +00:00
|
|
|
#[cfg(not(any(no_global_oom_handling, test)))]
|
2021-10-10 05:50:06 +00:00
|
|
|
#[must_use]
|
2017-05-24 16:06:11 +00:00
|
|
|
#[inline]
|
2019-04-27 19:28:40 +00:00
|
|
|
pub fn with_capacity_zeroed(capacity: usize) -> Self {
|
2020-03-24 10:45:38 +00:00
|
|
|
Self::with_capacity_zeroed_in(capacity, Global)
|
2017-05-24 16:06:11 +00:00
|
|
|
}
|
2020-10-06 14:37:23 +00:00
|
|
|
}
|
|
|
|
|
2020-12-04 13:47:15 +00:00
|
|
|
impl<T, A: Allocator> RawVec<T, A> {
|
2021-01-21 16:57:01 +00:00
|
|
|
// Tiny Vecs are dumb. Skip to:
|
|
|
|
// - 8 if the element size is 1, because any heap allocators is likely
|
|
|
|
// to round up a request of less than 8 bytes to at least 8 bytes.
|
|
|
|
// - 4 if elements are moderate-sized (<= 1 KiB).
|
|
|
|
// - 1 otherwise, to avoid wasting too much space for very short Vecs.
|
2021-12-20 20:58:45 +00:00
|
|
|
pub(crate) const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
|
2021-01-21 16:57:01 +00:00
|
|
|
8
|
|
|
|
} else if mem::size_of::<T>() <= 1024 {
|
|
|
|
4
|
|
|
|
} else {
|
|
|
|
1
|
|
|
|
};
|
|
|
|
|
2020-10-06 14:37:23 +00:00
|
|
|
/// Like `new`, but parameterized over the choice of allocator for
|
|
|
|
/// the returned `RawVec`.
|
|
|
|
pub const fn new_in(alloc: A) -> Self {
|
|
|
|
// `cap: 0` means "unallocated". zero-sized types are ignored.
|
|
|
|
Self { ptr: Unique::dangling(), cap: 0, alloc }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Like `with_capacity`, but parameterized over the choice of
|
|
|
|
/// allocator for the returned `RawVec`.
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2020-10-06 14:37:23 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
|
|
|
|
Self::allocate_in(capacity, AllocInit::Uninitialized, alloc)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Like `with_capacity_zeroed`, but parameterized over the choice
|
|
|
|
/// of allocator for the returned `RawVec`.
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2020-10-06 14:37:23 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self {
|
|
|
|
Self::allocate_in(capacity, AllocInit::Zeroed, alloc)
|
|
|
|
}
|
2015-07-10 04:57:21 +00:00
|
|
|
|
2020-05-31 09:19:06 +00:00
|
|
|
/// Converts the entire buffer into `Box<[MaybeUninit<T>]>` with the specified `len`.
|
|
|
|
///
|
|
|
|
/// Note that this will correctly reconstitute any `cap` changes
|
|
|
|
/// that may have been performed. (See description of type for details.)
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// * `len` must be greater than or equal to the most recently requested capacity, and
|
|
|
|
/// * `len` must be less than or equal to `self.capacity()`.
|
|
|
|
///
|
|
|
|
/// Note, that the requested capacity and `self.capacity()` could differ, as
|
|
|
|
/// an allocator could overallocate and return a greater memory block than requested.
|
2020-10-06 14:37:23 +00:00
|
|
|
pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit<T>], A> {
|
2020-05-31 09:19:06 +00:00
|
|
|
// Sanity-check one half of the safety requirement (we cannot check the other half).
|
|
|
|
debug_assert!(
|
|
|
|
len <= self.capacity(),
|
|
|
|
"`len` must be smaller than or equal to `self.capacity()`"
|
|
|
|
);
|
|
|
|
|
|
|
|
let me = ManuallyDrop::new(self);
|
2020-05-28 21:27:00 +00:00
|
|
|
unsafe {
|
|
|
|
let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit<T>, len);
|
2020-10-06 14:37:23 +00:00
|
|
|
Box::from_raw_in(slice, ptr::read(&me.alloc))
|
2020-05-28 21:27:00 +00:00
|
|
|
}
|
2020-05-31 09:19:06 +00:00
|
|
|
}
|
2020-03-26 16:11:47 +00:00
|
|
|
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2020-09-22 13:22:02 +00:00
|
|
|
fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self {
|
2022-04-05 20:06:46 +00:00
|
|
|
// Don't allocate here because `Drop` will not deallocate when `capacity` is 0.
|
2022-09-23 06:12:29 +00:00
|
|
|
if T::IS_ZST || capacity == 0 {
|
2020-03-26 16:11:47 +00:00
|
|
|
Self::new_in(alloc)
|
|
|
|
} else {
|
2020-06-29 09:08:47 +00:00
|
|
|
// We avoid `unwrap_or_else` here because it bloats the amount of
|
|
|
|
// LLVM IR generated.
|
|
|
|
let layout = match Layout::array::<T>(capacity) {
|
|
|
|
Ok(layout) => layout,
|
|
|
|
Err(_) => capacity_overflow(),
|
|
|
|
};
|
|
|
|
match alloc_guard(layout.size()) {
|
|
|
|
Ok(_) => {}
|
|
|
|
Err(_) => capacity_overflow(),
|
|
|
|
}
|
2020-07-28 10:41:18 +00:00
|
|
|
let result = match init {
|
2020-12-04 13:47:15 +00:00
|
|
|
AllocInit::Uninitialized => alloc.allocate(layout),
|
|
|
|
AllocInit::Zeroed => alloc.allocate_zeroed(layout),
|
2020-07-28 10:41:18 +00:00
|
|
|
};
|
2020-08-04 16:03:34 +00:00
|
|
|
let ptr = match result {
|
|
|
|
Ok(ptr) => ptr,
|
2020-06-29 09:08:47 +00:00
|
|
|
Err(_) => handle_alloc_error(layout),
|
|
|
|
};
|
2020-03-26 16:11:47 +00:00
|
|
|
|
2021-12-21 18:13:41 +00:00
|
|
|
// Allocators currently return a `NonNull<[u8]>` whose length
|
|
|
|
// matches the size requested. If that ever changes, the capacity
|
|
|
|
// here should change to `ptr.len() / mem::size_of::<T>()`.
|
2020-03-26 16:11:47 +00:00
|
|
|
Self {
|
2020-08-04 16:03:34 +00:00
|
|
|
ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) },
|
2021-12-21 18:13:41 +00:00
|
|
|
cap: capacity,
|
2020-03-26 16:11:47 +00:00
|
|
|
alloc,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Reconstitutes a `RawVec` from a pointer, capacity, and allocator.
|
|
|
|
///
|
2020-03-25 17:44:29 +00:00
|
|
|
/// # Safety
|
2020-03-26 16:11:47 +00:00
|
|
|
///
|
2020-08-04 15:46:14 +00:00
|
|
|
/// The `ptr` must be allocated (via the given allocator `alloc`), and with the given
|
|
|
|
/// `capacity`.
|
2020-03-25 17:44:29 +00:00
|
|
|
/// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit
|
2020-03-25 18:08:56 +00:00
|
|
|
/// systems). ZST vectors may have a capacity up to `usize::MAX`.
|
2020-08-04 15:46:14 +00:00
|
|
|
/// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is
|
|
|
|
/// guaranteed.
|
2020-03-26 16:11:47 +00:00
|
|
|
#[inline]
|
2020-08-04 15:46:14 +00:00
|
|
|
pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self {
|
|
|
|
Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap: capacity, alloc }
|
2020-03-26 16:11:47 +00:00
|
|
|
}
|
|
|
|
|
2015-07-10 04:57:21 +00:00
|
|
|
/// Gets a raw pointer to the start of the allocation. Note that this is
|
2020-04-30 09:00:45 +00:00
|
|
|
/// `Unique::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must
|
2015-07-10 04:57:21 +00:00
|
|
|
/// be careful.
|
2020-11-16 21:47:35 +00:00
|
|
|
#[inline]
|
2015-07-10 04:57:21 +00:00
|
|
|
pub fn ptr(&self) -> *mut T {
|
2017-05-04 18:48:58 +00:00
|
|
|
self.ptr.as_ptr()
|
2015-07-10 04:57:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets the capacity of the allocation.
|
|
|
|
///
|
|
|
|
/// This will always be `usize::MAX` if `T` is zero-sized.
|
2016-05-09 18:43:33 +00:00
|
|
|
#[inline(always)]
|
2019-04-27 19:28:40 +00:00
|
|
|
pub fn capacity(&self) -> usize {
|
2022-09-23 06:12:29 +00:00
|
|
|
if T::IS_ZST { usize::MAX } else { self.cap }
|
2015-07-10 04:57:21 +00:00
|
|
|
}
|
|
|
|
|
2019-09-05 16:15:28 +00:00
|
|
|
/// Returns a shared reference to the allocator backing this `RawVec`.
|
2020-12-04 13:47:15 +00:00
|
|
|
pub fn allocator(&self) -> &A {
|
2020-03-26 16:11:47 +00:00
|
|
|
&self.alloc
|
2017-05-24 16:06:11 +00:00
|
|
|
}
|
|
|
|
|
2020-03-25 20:12:12 +00:00
|
|
|
fn current_memory(&self) -> Option<(NonNull<u8>, Layout)> {
|
2022-09-23 06:12:29 +00:00
|
|
|
if T::IS_ZST || self.cap == 0 {
|
2017-08-11 23:00:09 +00:00
|
|
|
None
|
|
|
|
} else {
|
2023-01-21 18:28:56 +00:00
|
|
|
// We could use Layout::array here which ensures the absence of isize and usize overflows
|
|
|
|
// and could hypothetically handle differences between stride and size, but this memory
|
|
|
|
// has already been allocated so we know it can't overflow and currently rust does not
|
|
|
|
// support such types. So we can do better by skipping some checks and avoid an unwrap.
|
|
|
|
let _: () = const { assert!(mem::size_of::<T>() % mem::align_of::<T>() == 0) };
|
2017-08-11 23:00:09 +00:00
|
|
|
unsafe {
|
2023-01-21 18:28:56 +00:00
|
|
|
let align = mem::align_of::<T>();
|
|
|
|
let size = mem::size_of::<T>().unchecked_mul(self.cap);
|
|
|
|
let layout = Layout::from_size_align_unchecked(size, align);
|
2020-03-25 20:12:12 +00:00
|
|
|
Some((self.ptr.cast().into(), layout))
|
2017-08-11 23:00:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-20 10:45:05 +00:00
|
|
|
/// Ensures that the buffer contains at least enough space to hold `len +
|
|
|
|
/// additional` elements. If it doesn't already have enough capacity, will
|
|
|
|
/// reallocate enough space plus comfortable slack space to get amortized
|
2020-10-14 05:58:59 +00:00
|
|
|
/// *O*(1) behavior. Will limit this behavior if it would needlessly cause
|
2020-05-20 10:45:05 +00:00
|
|
|
/// itself to panic.
|
2015-07-10 04:57:21 +00:00
|
|
|
///
|
2020-05-20 10:45:05 +00:00
|
|
|
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
|
2015-07-10 04:57:21 +00:00
|
|
|
/// the requested space. This is not really unsafe, but the unsafe
|
2015-10-13 13:44:11 +00:00
|
|
|
/// code *you* write that relies on the behavior of this function may break.
|
2015-07-10 04:57:21 +00:00
|
|
|
///
|
|
|
|
/// This is ideal for implementing a bulk-push operation like `extend`.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
2020-06-16 04:23:28 +00:00
|
|
|
/// Panics if the new capacity exceeds `isize::MAX` bytes.
|
2015-07-10 04:57:21 +00:00
|
|
|
///
|
|
|
|
/// # Aborts
|
|
|
|
///
|
2019-09-05 16:15:28 +00:00
|
|
|
/// Aborts on OOM.
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2021-03-21 21:47:57 +00:00
|
|
|
#[inline]
|
2020-05-20 10:45:05 +00:00
|
|
|
pub fn reserve(&mut self, len: usize, additional: usize) {
|
2021-03-21 21:47:57 +00:00
|
|
|
// Callers expect this function to be very cheap when there is already sufficient capacity.
|
|
|
|
// Therefore, we move all the resizing and error-handling logic from grow_amortized and
|
2021-08-28 18:20:22 +00:00
|
|
|
// handle_reserve behind a call, while making sure that this function is likely to be
|
2021-03-21 21:47:57 +00:00
|
|
|
// inlined as just a comparison and a call if the comparison fails.
|
2021-03-21 23:17:07 +00:00
|
|
|
#[cold]
|
|
|
|
fn do_reserve_and_handle<T, A: Allocator>(
|
|
|
|
slf: &mut RawVec<T, A>,
|
|
|
|
len: usize,
|
|
|
|
additional: usize,
|
|
|
|
) {
|
2021-03-21 21:47:57 +00:00
|
|
|
handle_reserve(slf.grow_amortized(len, additional));
|
|
|
|
}
|
|
|
|
|
|
|
|
if self.needs_to_grow(len, additional) {
|
|
|
|
do_reserve_and_handle(self, len, additional);
|
|
|
|
}
|
2018-05-15 00:56:46 +00:00
|
|
|
}
|
2020-03-24 10:45:38 +00:00
|
|
|
|
2021-11-29 10:15:51 +00:00
|
|
|
/// A specialized version of `reserve()` used only by the hot and
|
|
|
|
/// oft-instantiated `Vec::push()`, which does its own capacity check.
|
|
|
|
#[cfg(not(no_global_oom_handling))]
|
|
|
|
#[inline(never)]
|
|
|
|
pub fn reserve_for_push(&mut self, len: usize) {
|
|
|
|
handle_reserve(self.grow_amortized(len, 1));
|
|
|
|
}
|
|
|
|
|
2020-03-24 10:45:38 +00:00
|
|
|
/// The same as `reserve`, but returns on errors instead of panicking or aborting.
|
2020-05-20 10:45:05 +00:00
|
|
|
pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
|
|
|
|
if self.needs_to_grow(len, additional) {
|
|
|
|
self.grow_amortized(len, additional)
|
2020-03-24 10:45:38 +00:00
|
|
|
} else {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-20 10:45:05 +00:00
|
|
|
/// Ensures that the buffer contains at least enough space to hold `len +
|
|
|
|
/// additional` elements. If it doesn't already, will reallocate the
|
|
|
|
/// minimum possible amount of memory necessary. Generally this will be
|
|
|
|
/// exactly the amount of memory necessary, but in principle the allocator
|
|
|
|
/// is free to give back more than we asked for.
|
2020-03-24 10:45:38 +00:00
|
|
|
///
|
2020-05-20 10:45:05 +00:00
|
|
|
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
|
|
|
|
/// the requested space. This is not really unsafe, but the unsafe code
|
|
|
|
/// *you* write that relies on the behavior of this function may break.
|
2020-03-24 10:45:38 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
2020-06-16 04:23:28 +00:00
|
|
|
/// Panics if the new capacity exceeds `isize::MAX` bytes.
|
2020-03-24 10:45:38 +00:00
|
|
|
///
|
|
|
|
/// # Aborts
|
|
|
|
///
|
|
|
|
/// Aborts on OOM.
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2020-05-20 10:45:05 +00:00
|
|
|
pub fn reserve_exact(&mut self, len: usize, additional: usize) {
|
2020-08-04 08:10:11 +00:00
|
|
|
handle_reserve(self.try_reserve_exact(len, additional));
|
2020-03-24 10:45:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
|
|
|
|
pub fn try_reserve_exact(
|
|
|
|
&mut self,
|
2020-05-20 10:45:05 +00:00
|
|
|
len: usize,
|
|
|
|
additional: usize,
|
2020-03-24 10:45:38 +00:00
|
|
|
) -> Result<(), TryReserveError> {
|
2020-05-20 10:45:05 +00:00
|
|
|
if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) }
|
2015-08-12 03:53:58 +00:00
|
|
|
}
|
|
|
|
|
2021-12-21 18:13:41 +00:00
|
|
|
/// Shrinks the buffer down to the specified capacity. If the given amount
|
2015-07-10 04:57:21 +00:00
|
|
|
/// is 0, actually completely deallocates.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if the given amount is *larger* than the current capacity.
|
|
|
|
///
|
|
|
|
/// # Aborts
|
|
|
|
///
|
|
|
|
/// Aborts on OOM.
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2021-12-21 18:13:41 +00:00
|
|
|
pub fn shrink_to_fit(&mut self, cap: usize) {
|
|
|
|
handle_reserve(self.shrink(cap));
|
2015-07-10 04:57:21 +00:00
|
|
|
}
|
2017-05-24 16:06:11 +00:00
|
|
|
}
|
2015-07-10 04:57:21 +00:00
|
|
|
|
2020-12-04 13:47:15 +00:00
|
|
|
impl<T, A: Allocator> RawVec<T, A> {
|
2020-03-24 10:45:38 +00:00
|
|
|
/// Returns if the buffer needs to grow to fulfill the needed extra capacity.
|
|
|
|
/// Mainly used to make inlining reserve-calls possible without inlining `grow`.
|
2020-05-20 10:45:05 +00:00
|
|
|
fn needs_to_grow(&self, len: usize, additional: usize) -> bool {
|
|
|
|
additional > self.capacity().wrapping_sub(len)
|
2020-03-24 10:45:38 +00:00
|
|
|
}
|
2018-05-15 00:56:46 +00:00
|
|
|
|
2021-12-21 18:13:41 +00:00
|
|
|
fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) {
|
|
|
|
// Allocators currently return a `NonNull<[u8]>` whose length matches
|
|
|
|
// the size requested. If that ever changes, the capacity here should
|
|
|
|
// change to `ptr.len() / mem::size_of::<T>()`.
|
2020-08-04 16:03:34 +00:00
|
|
|
self.ptr = unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) };
|
2021-12-21 18:13:41 +00:00
|
|
|
self.cap = cap;
|
2020-03-24 10:45:38 +00:00
|
|
|
}
|
2018-05-15 00:56:46 +00:00
|
|
|
|
2020-05-11 03:17:28 +00:00
|
|
|
// This method is usually instantiated many times. So we want it to be as
|
|
|
|
// small as possible, to improve compile times. But we also want as much of
|
|
|
|
// its contents to be statically computable as possible, to make the
|
|
|
|
// generated code run faster. Therefore, this method is carefully written
|
|
|
|
// so that all of the code that depends on `T` is within it, while as much
|
|
|
|
// of the code that doesn't depend on `T` as possible is in functions that
|
|
|
|
// are non-generic over `T`.
|
2020-05-20 10:45:05 +00:00
|
|
|
fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
|
2020-05-19 23:47:21 +00:00
|
|
|
// This is ensured by the calling contexts.
|
2020-05-20 10:45:05 +00:00
|
|
|
debug_assert!(additional > 0);
|
|
|
|
|
2022-09-23 06:12:29 +00:00
|
|
|
if T::IS_ZST {
|
2020-03-25 17:36:03 +00:00
|
|
|
// Since we return a capacity of `usize::MAX` when `elem_size` is
|
|
|
|
// 0, getting to here necessarily means the `RawVec` is overfull.
|
2021-07-23 15:40:43 +00:00
|
|
|
return Err(CapacityOverflow.into());
|
2020-03-25 17:36:03 +00:00
|
|
|
}
|
2020-03-02 23:08:24 +00:00
|
|
|
|
2020-05-11 03:17:28 +00:00
|
|
|
// Nothing we can really do about these checks, sadly.
|
2020-05-20 10:45:05 +00:00
|
|
|
let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
|
Tiny Vecs are dumb.
Currently, if you repeatedly push to an empty vector, the capacity
growth sequence is 0, 1, 2, 4, 8, 16, etc. This commit changes the
relevant code (the "amortized" growth strategy) to skip 1 and 2 in most
cases, instead using 0, 4, 8, 16, etc. (You can still get a capacity of
1 or 2 using the "exact" growth strategy, e.g. via `reserve_exact()`.)
This idea (along with the phrase "tiny Vecs are dumb") comes from the
"doubling" growth strategy that was removed from `RawVec` in #72013.
That strategy was barely ever used -- only when a `VecDeque` was grown,
oddly enough -- which is why it was removed in #72013.
(Fun fact: until just a few days ago, I thought the "doubling" strategy
was used for repeated push case. In other words, this commit makes
`Vec`s behave the way I always thought they behaved.)
This change reduces the number of allocations done by rustc itself by
10% or more. It speeds up rustc, and will also speed up any other Rust
program that uses `Vec`s a lot.
2020-05-17 19:28:14 +00:00
|
|
|
|
|
|
|
// This guarantees exponential growth. The doubling cannot overflow
|
|
|
|
// because `cap <= isize::MAX` and the type of `cap` is `usize`.
|
|
|
|
let cap = cmp::max(self.cap * 2, required_cap);
|
2021-01-21 16:57:01 +00:00
|
|
|
let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap);
|
Tiny Vecs are dumb.
Currently, if you repeatedly push to an empty vector, the capacity
growth sequence is 0, 1, 2, 4, 8, 16, etc. This commit changes the
relevant code (the "amortized" growth strategy) to skip 1 and 2 in most
cases, instead using 0, 4, 8, 16, etc. (You can still get a capacity of
1 or 2 using the "exact" growth strategy, e.g. via `reserve_exact()`.)
This idea (along with the phrase "tiny Vecs are dumb") comes from the
"doubling" growth strategy that was removed from `RawVec` in #72013.
That strategy was barely ever used -- only when a `VecDeque` was grown,
oddly enough -- which is why it was removed in #72013.
(Fun fact: until just a few days ago, I thought the "doubling" strategy
was used for repeated push case. In other words, this commit makes
`Vec`s behave the way I always thought they behaved.)
This change reduces the number of allocations done by rustc itself by
10% or more. It speeds up rustc, and will also speed up any other Rust
program that uses `Vec`s a lot.
2020-05-17 19:28:14 +00:00
|
|
|
|
2020-05-11 03:17:28 +00:00
|
|
|
let new_layout = Layout::array::<T>(cap);
|
|
|
|
|
|
|
|
// `finish_grow` is non-generic over `T`.
|
2020-08-04 16:03:34 +00:00
|
|
|
let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
|
2021-12-21 18:13:41 +00:00
|
|
|
self.set_ptr_and_cap(ptr, cap);
|
2020-05-11 03:17:28 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
// The constraints on this method are much the same as those on
|
|
|
|
// `grow_amortized`, but this method is usually instantiated less often so
|
|
|
|
// it's less critical.
|
2020-05-20 10:45:05 +00:00
|
|
|
fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
|
2022-09-23 06:12:29 +00:00
|
|
|
if T::IS_ZST {
|
2020-05-11 03:17:28 +00:00
|
|
|
// Since we return a capacity of `usize::MAX` when the type size is
|
|
|
|
// 0, getting to here necessarily means the `RawVec` is overfull.
|
2021-07-23 15:40:43 +00:00
|
|
|
return Err(CapacityOverflow.into());
|
2020-05-11 03:17:28 +00:00
|
|
|
}
|
|
|
|
|
2020-05-20 10:45:05 +00:00
|
|
|
let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
|
2020-05-11 03:17:28 +00:00
|
|
|
let new_layout = Layout::array::<T>(cap);
|
|
|
|
|
|
|
|
// `finish_grow` is non-generic over `T`.
|
2020-08-04 16:03:34 +00:00
|
|
|
let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
|
2021-12-21 18:13:41 +00:00
|
|
|
self.set_ptr_and_cap(ptr, cap);
|
2020-03-26 16:11:47 +00:00
|
|
|
Ok(())
|
2020-03-24 10:45:38 +00:00
|
|
|
}
|
2018-05-15 00:56:46 +00:00
|
|
|
|
2022-06-28 23:09:02 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2021-12-21 18:13:41 +00:00
|
|
|
fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> {
|
|
|
|
assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity");
|
2018-05-15 00:56:46 +00:00
|
|
|
|
2020-03-25 20:12:12 +00:00
|
|
|
let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) };
|
2023-01-21 18:28:56 +00:00
|
|
|
// See current_memory() why this assert is here
|
|
|
|
let _: () = const { assert!(mem::size_of::<T>() % mem::align_of::<T>() == 0) };
|
2020-08-04 16:03:34 +00:00
|
|
|
let ptr = unsafe {
|
2021-08-02 09:34:37 +00:00
|
|
|
// `Layout::array` cannot overflow here because it would have
|
2021-08-07 16:57:48 +00:00
|
|
|
// overflowed earlier when capacity was larger.
|
2023-01-21 18:28:56 +00:00
|
|
|
let new_size = mem::size_of::<T>().unchecked_mul(cap);
|
|
|
|
let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
|
2021-07-23 15:40:43 +00:00
|
|
|
self.alloc
|
|
|
|
.shrink(ptr, layout, new_layout)
|
|
|
|
.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?
|
2020-03-25 20:12:12 +00:00
|
|
|
};
|
2021-12-21 18:13:41 +00:00
|
|
|
self.set_ptr_and_cap(ptr, cap);
|
2020-03-26 16:11:47 +00:00
|
|
|
Ok(())
|
2018-05-15 00:56:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-11 03:17:28 +00:00
|
|
|
// This function is outside `RawVec` to minimize compile times. See the comment
|
|
|
|
// above `RawVec::grow_amortized` for details. (The `A` parameter isn't
|
|
|
|
// significant, because the number of different `A` types seen in practice is
|
|
|
|
// much smaller than the number of `T` types.)
|
2020-11-18 03:57:40 +00:00
|
|
|
#[inline(never)]
|
2020-05-11 03:17:28 +00:00
|
|
|
fn finish_grow<A>(
|
2020-09-25 03:48:26 +00:00
|
|
|
new_layout: Result<Layout, LayoutError>,
|
2020-05-11 03:17:28 +00:00
|
|
|
current_memory: Option<(NonNull<u8>, Layout)>,
|
|
|
|
alloc: &mut A,
|
2020-08-04 16:03:34 +00:00
|
|
|
) -> Result<NonNull<[u8]>, TryReserveError>
|
2020-05-11 03:17:28 +00:00
|
|
|
where
|
2020-12-04 13:47:15 +00:00
|
|
|
A: Allocator,
|
2020-05-11 03:17:28 +00:00
|
|
|
{
|
|
|
|
// Check for the error here to minimize the size of `RawVec::grow_*`.
|
|
|
|
let new_layout = new_layout.map_err(|_| CapacityOverflow)?;
|
|
|
|
|
|
|
|
alloc_guard(new_layout.size())?;
|
|
|
|
|
|
|
|
let memory = if let Some((ptr, old_layout)) = current_memory {
|
2020-08-19 23:01:46 +00:00
|
|
|
debug_assert_eq!(old_layout.align(), new_layout.align());
|
2020-08-20 09:55:41 +00:00
|
|
|
unsafe {
|
|
|
|
// The allocator checks for alignment equality
|
|
|
|
intrinsics::assume(old_layout.align() == new_layout.align());
|
|
|
|
alloc.grow(ptr, old_layout, new_layout)
|
|
|
|
}
|
2020-05-11 03:17:28 +00:00
|
|
|
} else {
|
2020-12-04 13:47:15 +00:00
|
|
|
alloc.allocate(new_layout)
|
2020-08-18 20:39:33 +00:00
|
|
|
};
|
2020-05-11 03:17:28 +00:00
|
|
|
|
2021-07-23 15:40:43 +00:00
|
|
|
memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into())
|
2020-05-11 03:17:28 +00:00
|
|
|
}
|
|
|
|
|
2020-12-04 13:47:15 +00:00
|
|
|
unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec<T, A> {
|
2019-09-05 16:15:28 +00:00
|
|
|
/// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
|
2017-05-24 16:06:11 +00:00
|
|
|
fn drop(&mut self) {
|
2020-03-25 20:12:12 +00:00
|
|
|
if let Some((ptr, layout)) = self.current_memory() {
|
2020-12-04 13:47:15 +00:00
|
|
|
unsafe { self.alloc.deallocate(ptr, layout) }
|
2020-03-26 16:11:47 +00:00
|
|
|
}
|
2017-05-24 16:06:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-04 08:10:11 +00:00
|
|
|
// Central function for reserve error handling.
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2020-08-04 08:10:11 +00:00
|
|
|
#[inline]
|
|
|
|
fn handle_reserve(result: Result<(), TryReserveError>) {
|
2021-07-23 15:40:43 +00:00
|
|
|
match result.map_err(|e| e.kind()) {
|
2020-08-04 08:10:11 +00:00
|
|
|
Err(CapacityOverflow) => capacity_overflow(),
|
|
|
|
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
|
|
|
|
Ok(()) => { /* yay */ }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-07-10 04:57:21 +00:00
|
|
|
// We need to guarantee the following:
|
2019-09-05 16:15:28 +00:00
|
|
|
// * We don't ever allocate `> isize::MAX` byte-size objects.
|
|
|
|
// * We don't overflow `usize::MAX` and actually allocate too little.
|
2015-07-10 04:57:21 +00:00
|
|
|
//
|
|
|
|
// On 64-bit we just need to check for overflow since trying to allocate
|
2016-05-06 13:31:11 +00:00
|
|
|
// `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
|
|
|
|
// an extra guard for this in case we're running on a platform which can use
|
2019-09-05 16:15:28 +00:00
|
|
|
// all 4GB in user-space, e.g., PAE or x32.
|
2015-07-10 04:57:21 +00:00
|
|
|
|
|
|
|
#[inline]
|
2019-06-12 18:02:01 +00:00
|
|
|
fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
|
2020-09-08 19:39:13 +00:00
|
|
|
if usize::BITS < 64 && alloc_size > isize::MAX as usize {
|
2021-07-23 15:40:43 +00:00
|
|
|
Err(CapacityOverflow.into())
|
2018-03-08 14:36:43 +00:00
|
|
|
} else {
|
|
|
|
Ok(())
|
2015-08-15 05:17:17 +00:00
|
|
|
}
|
2015-07-10 04:57:21 +00:00
|
|
|
}
|
2015-10-30 21:17:16 +00:00
|
|
|
|
2018-04-06 20:46:10 +00:00
|
|
|
// One central function responsible for reporting capacity overflows. This'll
|
|
|
|
// ensure that the code generation related to these panics is minimal as there's
|
|
|
|
// only one location which panics rather than a bunch throughout the module.
|
alloc: Add unstable Cfg feature `no-global_oom_handling`
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
2021-04-17 00:18:04 +00:00
|
|
|
#[cfg(not(no_global_oom_handling))]
|
2018-04-06 20:46:10 +00:00
|
|
|
fn capacity_overflow() -> ! {
|
2019-09-05 16:15:28 +00:00
|
|
|
panic!("capacity overflow");
|
2018-04-06 20:46:10 +00:00
|
|
|
}
|