pub struct Global;
allocator_api
#32838)Expand description
The global memory allocator.
This type implements the Allocator
trait by forwarding calls
to the allocator registered with the #[global_allocator]
attribute
if there is one, or the std
crate’s default.
Note: while this type is unstable, the functionality it provides can be
accessed through the free functions in alloc
.
Implementations§
source§impl<T> Box<T, Global>
impl<T> Box<T, Global>
sourcepub fn new_uninit() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_uninit() -> Box<MaybeUninit<T>, Global>
new_uninit
#63291)sourcepub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
new_uninit
#63291)Constructs a new Box
with uninitialized contents, with the memory
being filled with 0
bytes.
See MaybeUninit::zeroed
for examples of correct and incorrect usage
of this method.
Examples
#![feature(new_uninit)]
let zero = Box::<u32>::new_zeroed();
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0)
Run1.33.0 · sourcepub fn pin(x: T) -> Pin<Box<T, Global>>
pub fn pin(x: T) -> Pin<Box<T, Global>>
Constructs a new Pin<Box<T>>
. If T
does not implement Unpin
, then
x
will be pinned in memory and unable to be moved.
Constructing and pinning of the Box
can also be done in two steps: Box::pin(x)
does the same as Box::into_pin(Box::new(x))
. Consider using
into_pin
if you already have a Box<T>
, or if you want to
construct a (pinned) Box
in a different way than with Box::new
.
sourcepub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>
allocator_api
#32838)sourcepub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
#32838)Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails
Examples
#![feature(allocator_api, new_uninit)]
let mut five = Box::<u32>::try_new_uninit()?;
let five = unsafe {
// Deferred initialization:
five.as_mut_ptr().write(5);
five.assume_init()
};
assert_eq!(*five, 5);
Runsourcepub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
#32838)Constructs a new Box
with uninitialized contents, with the memory
being filled with 0
bytes on the heap
See MaybeUninit::zeroed
for examples of correct and incorrect usage
of this method.
Examples
#![feature(allocator_api, new_uninit)]
let zero = Box::<u32>::try_new_zeroed()?;
let zero = unsafe { zero.assume_init() };
assert_eq!(*zero, 0);
Runsource§impl<T> Box<[T], Global>
impl<T> Box<[T], Global>
sourcepub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
#63291)Constructs a new boxed slice with uninitialized contents.
Examples
#![feature(new_uninit)]
let mut values = Box::<[u32]>::new_uninit_slice(3);
let values = unsafe {
// Deferred initialization:
values[0].as_mut_ptr().write(1);
values[1].as_mut_ptr().write(2);
values[2].as_mut_ptr().write(3);
values.assume_init()
};
assert_eq!(*values, [1, 2, 3])
Runsourcepub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
🔬This is a nightly-only experimental API. (new_uninit
#63291)
pub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
#63291)Constructs a new boxed slice with uninitialized contents, with the memory
being filled with 0
bytes.
See MaybeUninit::zeroed
for examples of correct and incorrect usage
of this method.
Examples
#![feature(new_uninit)]
let values = Box::<[u32]>::new_zeroed_slice(3);
let values = unsafe { values.assume_init() };
assert_eq!(*values, [0, 0, 0])
Runsourcepub fn try_new_uninit_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_uninit_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
#32838)Constructs a new boxed slice with uninitialized contents. Returns an error if the allocation fails
Examples
#![feature(allocator_api, new_uninit)]
let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
let values = unsafe {
// Deferred initialization:
values[0].as_mut_ptr().write(1);
values[1].as_mut_ptr().write(2);
values[2].as_mut_ptr().write(3);
values.assume_init()
};
assert_eq!(*values, [1, 2, 3]);
Runsourcepub fn try_new_zeroed_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
#32838)
pub fn try_new_zeroed_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
#32838)Constructs a new boxed slice with uninitialized contents, with the memory
being filled with 0
bytes. Returns an error if the allocation fails
See MaybeUninit::zeroed
for examples of correct and incorrect usage
of this method.
Examples
#![feature(allocator_api, new_uninit)]
let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
let values = unsafe { values.assume_init() };
assert_eq!(*values, [0, 0, 0]);
Runsource§impl<T> Box<T, Global>where
T: ?Sized,
impl<T> Box<T, Global>where T: ?Sized,
1.4.0 · sourcepub unsafe fn from_raw(raw: *mut T) -> Box<T, Global>
pub unsafe fn from_raw(raw: *mut T) -> Box<T, Global>
Constructs a box from a raw pointer.
After calling this function, the raw pointer is owned by the
resulting Box
. Specifically, the Box
destructor will call
the destructor of T
and free the allocated memory. For this
to be safe, the memory must have been allocated in accordance
with the memory layout used by Box
.
Safety
This function is unsafe because improper use may lead to memory problems. For example, a double-free may occur if the function is called twice on the same raw pointer.
The safety conditions are described in the memory layout section.
Examples
Recreate a Box
which was previously converted to a raw pointer
using Box::into_raw
:
let x = Box::new(5);
let ptr = Box::into_raw(x);
let x = unsafe { Box::from_raw(ptr) };
RunManually create a Box
from scratch by using the global allocator:
use std::alloc::{alloc, Layout};
unsafe {
let ptr = alloc(Layout::new::<i32>()) as *mut i32;
// In general .write is required to avoid attempting to destruct
// the (uninitialized) previous contents of `ptr`, though for this
// simple example `*ptr = 5` would have worked as well.
ptr.write(5);
let x = Box::from_raw(ptr);
}
RunTrait Implementations§
source§impl Allocator for Global
impl Allocator for Global
source§fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)source§fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)allocate
, but also ensures that the returned memory is zero-initialized. Read moresource§unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
allocator_api
#32838)ptr
. Read moresource§unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)source§unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>
allocator_api
#32838)grow
, but also ensures that the new contents are set to zero before being
returned. Read moresource§impl<S> AsyncIterator for Box<S, Global>where
S: AsyncIterator + Unpin + ?Sized,
impl<S> AsyncIterator for Box<S, Global>where S: AsyncIterator + Unpin + ?Sized,
§type Item = <S as AsyncIterator>::Item
type Item = <S as AsyncIterator>::Item
async_iterator
#79024)source§fn poll_next(
self: Pin<&mut Box<S, Global>>,
cx: &mut Context<'_>
) -> Poll<Option<<Box<S, Global> as AsyncIterator>::Item>>
fn poll_next( self: Pin<&mut Box<S, Global>>, cx: &mut Context<'_> ) -> Poll<Option<<Box<S, Global> as AsyncIterator>::Item>>
async_iterator
#79024)None
if the async iterator is exhausted. Read more1.8.0 · source§impl<T> Error for Box<T, Global>where
T: Error,
impl<T> Error for Box<T, Global>where T: Error,
source§fn description(&self) -> &str
fn description(&self) -> &str
source§fn cause(&self) -> Option<&dyn Error>
fn cause(&self) -> Option<&dyn Error>
1.17.0 · source§impl<T> From<&[T]> for Box<[T], Global>where
T: Clone,
impl<T> From<&[T]> for Box<[T], Global>where T: Clone,
source§fn from(slice: &[T]) -> Box<[T], Global>
fn from(slice: &[T]) -> Box<[T], Global>
Converts a &[T]
into a Box<[T]>
This conversion allocates on the heap
and performs a copy of slice
and its contents.
Examples
// create a &[u8] which will be used to create a Box<[u8]>
let slice: &[u8] = &[104, 101, 108, 108, 111];
let boxed_slice: Box<[u8]> = Box::from(slice);
println!("{boxed_slice:?}");
Run1.0.0 · source§impl<'a> From<&str> for Box<dyn Error + Sync + Send + 'a, Global>
impl<'a> From<&str> for Box<dyn Error + Sync + Send + 'a, Global>
1.6.0 · source§impl From<&str> for Box<dyn Error, Global>
impl From<&str> for Box<dyn Error, Global>
1.45.0 · source§impl From<Cow<'_, str>> for Box<str, Global>
impl From<Cow<'_, str>> for Box<str, Global>
source§fn from(cow: Cow<'_, str>) -> Box<str, Global>
fn from(cow: Cow<'_, str>) -> Box<str, Global>
Converts a Cow<'_, str>
into a Box<str>
When cow
is the Cow::Borrowed
variant, this
conversion allocates on the heap and copies the
underlying str
. Otherwise, it will try to reuse the owned
String
’s allocation.
Examples
use std::borrow::Cow;
let unboxed = Cow::Borrowed("hello");
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
Runlet unboxed = Cow::Owned("hello".to_string());
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
Run1.22.0 · source§impl<'a> From<Cow<'a, str>> for Box<dyn Error, Global>
impl<'a> From<Cow<'a, str>> for Box<dyn Error, Global>
1.22.0 · source§impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Sync + Send + 'a, Global>
impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Sync + Send + 'a, Global>
source§fn from(err: Cow<'b, str>) -> Box<dyn Error + Sync + Send + 'a, Global>
fn from(err: Cow<'b, str>) -> Box<dyn Error + Sync + Send + 'a, Global>
Converts a Cow
into a box of dyn Error
+ Send
+ Sync
.
Examples
use std::error::Error;
use std::mem;
use std::borrow::Cow;
let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.0.0 · source§impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where
E: Error + 'a,
impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where E: Error + 'a,
source§fn from(err: E) -> Box<dyn Error + 'a, Global>
fn from(err: E) -> Box<dyn Error + 'a, Global>
Converts a type of Error
into a box of dyn Error
.
Examples
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error>::from(an_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run1.0.0 · source§impl<'a, E> From<E> for Box<dyn Error + Sync + Send + 'a, Global>where
E: Error + Send + Sync + 'a,
impl<'a, E> From<E> for Box<dyn Error + Sync + Send + 'a, Global>where E: Error + Send + Sync + 'a,
source§fn from(err: E) -> Box<dyn Error + Sync + Send + 'a, Global>
fn from(err: E) -> Box<dyn Error + Sync + Send + 'a, Global>
Converts a type of Error
+ Send
+ Sync
into a box of
dyn Error
+ Send
+ Sync
.
Examples
use std::error::Error;
use std::fmt;
use std::mem;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
unsafe impl Send for AnError {}
unsafe impl Sync for AnError {}
let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.0.0 · source§impl From<String> for Box<dyn Error + Sync + Send, Global>
impl From<String> for Box<dyn Error + Sync + Send, Global>
source§fn from(err: String) -> Box<dyn Error + Sync + Send, Global>
fn from(err: String) -> Box<dyn Error + Sync + Send, Global>
Converts a String
into a box of dyn Error
+ Send
+ Sync
.
Examples
use std::error::Error;
use std::mem;
let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
assert!(
mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run1.6.0 · source§impl From<String> for Box<dyn Error, Global>
impl From<String> for Box<dyn Error, Global>
1.43.0 · source§impl<T, const N: usize> TryFrom<Box<[T], Global>> for Box<[T; N], Global>
impl<T, const N: usize> TryFrom<Box<[T], Global>> for Box<[T; N], Global>
source§fn try_from(
boxed_slice: Box<[T], Global>
) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Box<[T], Global>>>::Error>
fn try_from( boxed_slice: Box<[T], Global> ) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Box<[T], Global>>>::Error>
Attempts to convert a Box<[T]>
into a Box<[T; N]>
.
The conversion occurs in-place and does not require a new memory allocation.
Errors
Returns the old Box<[T]>
in the Err
variant if
boxed_slice.len()
does not equal N
.
1.66.0 · source§impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
impl<T, const N: usize> TryFrom<Vec<T, Global>> for Box<[T; N], Global>
source§fn try_from(
vec: Vec<T, Global>
) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
fn try_from( vec: Vec<T, Global> ) -> Result<Box<[T; N], Global>, <Box<[T; N], Global> as TryFrom<Vec<T, Global>>>::Error>
Attempts to convert a Vec<T>
into a Box<[T; N]>
.
Like Vec::into_boxed_slice
, this is in-place if vec.capacity() == N
,
but will require a reallocation otherwise.
Errors
Returns the original Vec<T>
in the Err
variant if
boxed_slice.len()
does not equal N
.
Examples
This can be used with vec!
to create an array on the heap:
let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
assert_eq!(state.len(), 100);
Run