pub struct Global;
allocator_api
)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>
1.0.0 · sourcepub fn new(x: T) -> Box<T, Global>
pub fn new(x: T) -> Box<T, Global>
Allocates memory on the heap and then places x
into it.
This doesn’t actually allocate if T
is zero-sized.
Examples
let five = Box::new(5);
sourcepub fn new_uninit() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
)
pub fn new_uninit() -> Box<MaybeUninit<T>, Global>
new_uninit
)Constructs a new box with uninitialized contents.
Examples
#![feature(new_uninit)]
let mut five = Box::<u32>::new_uninit();
let five = unsafe {
// Deferred initialization:
five.as_mut_ptr().write(5);
five.assume_init()
};
assert_eq!(*five, 5)
sourcepub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
🔬This is a nightly-only experimental API. (new_uninit
)
pub fn new_zeroed() -> Box<MaybeUninit<T>, Global>
new_uninit
)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)
1.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
)
pub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>
allocator_api
)Allocates memory on the heap then places x
into it,
returning an error if the allocation fails
This doesn’t actually allocate if T
is zero-sized.
Examples
#![feature(allocator_api)]
let five = Box::try_new(5)?;
sourcepub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
)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);
sourcepub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>
allocator_api
)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);
source§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
)
pub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
)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])
sourcepub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
🔬This is a nightly-only experimental API. (new_uninit
)
pub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>
new_uninit
)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])
sourcepub fn try_new_uninit_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn try_new_uninit_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
)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]);
sourcepub fn try_new_zeroed_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn try_new_zeroed_slice(
len: usize
) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>
allocator_api
)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]);
source§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) };
Manually 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);
}
Trait 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
)source§fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api
)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
)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
)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
)grow
, but also ensures that the new contents are set to zero before being
returned. Read more1.64.0 · source§impl<T> AsFd for Box<T, Global>where
T: AsFd,
impl<T> AsFd for Box<T, Global>where
T: AsFd,
source§fn as_fd(&self) -> BorrowedFd<'_>
fn as_fd(&self) -> BorrowedFd<'_>
source§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
)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
)None
if the async iterator is exhausted. Read more1.0.0 · source§impl<B> BufRead for Box<B, Global>where
B: BufRead + ?Sized,
impl<B> BufRead for Box<B, Global>where
B: BufRead + ?Sized,
source§fn fill_buf(&mut self) -> Result<&[u8], Error>
fn fill_buf(&mut self) -> Result<&[u8], Error>
source§fn consume(&mut self, amt: usize)
fn consume(&mut self, amt: usize)
amt
bytes have been consumed from the buffer,
so they should no longer be returned in calls to read
. Read moresource§fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>
0xA
byte) is reached, and append
them to the provided buffer. You do not need to clear the buffer before
appending. Read moresource§fn has_data_left(&mut self) -> Result<bool, Error>
fn has_data_left(&mut self) -> Result<bool, Error>
buf_read_has_data_left
)Read
has any data left to be read. 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: Copy,
impl<T> From<&[T]> for Box<[T], Global>where
T: Copy,
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:?}");
1.6.0 · source§impl From<&str> for Box<dyn Error + 'static, Global>
impl From<&str> for Box<dyn Error + 'static, Global>
1.0.0 · source§impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>
impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, 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}");
let unboxed = Cow::Owned("hello".to_string());
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
1.22.0 · source§impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
1.22.0 · source§impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>
impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>
source§fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a, Global>
fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + '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))
1.0.0 · source§impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where
E: 'a + Error,
impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where
E: 'a + Error,
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))
1.0.0 · source§impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where
E: 'a + Error + Send + Sync,
impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where
E: 'a + Error + Send + Sync,
source§fn from(err: E) -> Box<dyn Error + Send + Sync + 'a, Global>
fn from(err: E) -> Box<dyn Error + Send + Sync + '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))
1.6.0 · source§impl From<String> for Box<dyn Error + 'static, Global>
impl From<String> for Box<dyn Error + 'static, Global>
1.0.0 · source§impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
source§fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global>
fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, 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))
1.0.0 · source§impl<R> Read for Box<R, Global>where
R: Read + ?Sized,
impl<R> Read for Box<R, Global>where
R: Read + ?Sized,
source§fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>
source§fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read
, except that it reads into a slice of buffers. Read moresource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
)source§fn read_to_end(&mut self, buf: &mut Vec<u8, Global>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8, Global>) -> Result<usize, Error>
buf
. Read moresource§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf
. Read moresource§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf
. Read moresource§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)cursor
. Read more1.0.0 · source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read
. Read more1.0.0 · source§impl<S> Seek for Box<S, Global>where
S: Seek + ?Sized,
impl<S> Seek for Box<S, Global>where
S: Seek + ?Sized,
source§fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>
fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>
source§fn stream_position(&mut self) -> Result<u64, Error>
fn stream_position(&mut self) -> Result<u64, Error>
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);
1.0.0 · source§impl<W> Write for Box<W, Global>where
W: Write + ?Sized,
impl<W> Write for Box<W, Global>where
W: Write + ?Sized,
source§fn write(&mut self, buf: &[u8]) -> Result<usize, Error>
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>
source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)