Struct std::alloc::Global

source ·
pub struct Global;
🔬This is a nightly-only experimental API. (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>

1.0.0 · source

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);
Run
source

pub fn new_uninit() -> Box<MaybeUninit<T>, Global>

🔬This is a nightly-only experimental API. (new_uninit #63291)

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)
Run
source

pub fn new_zeroed() -> Box<MaybeUninit<T>, Global>

🔬This is a nightly-only experimental API. (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)
Run
1.33.0 · source

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.

source

pub fn try_new(x: T) -> Result<Box<T, Global>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)

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)?;
Run
source

pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>, Global>, AllocError>

🔬This is a nightly-only experimental API. (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);
Run
source

pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>, Global>, AllocError>

🔬This is a nightly-only experimental API. (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);
Run
source§

impl<T> Box<[T], Global>

source

pub fn new_uninit_slice(len: usize) -> Box<[MaybeUninit<T>], Global>

🔬This is a nightly-only experimental API. (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])
Run
source

pub fn new_zeroed_slice(len: usize) -> Box<[MaybeUninit<T>], Global>

🔬This is a nightly-only experimental API. (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])
Run
source

pub fn try_new_uninit_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>

🔬This is a nightly-only experimental API. (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]);
Run
source

pub fn try_new_zeroed_slice( len: usize ) -> Result<Box<[MaybeUninit<T>], Global>, AllocError>

🔬This is a nightly-only experimental API. (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]);
Run
source§

impl<T> Box<T, Global>where T: ?Sized,

1.4.0 · source

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) };
Run

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);
}
Run

Trait Implementations§

source§

impl Allocator for Global

source§

fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Attempts to allocate a block of memory. Read more
source§

fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Behaves like allocate, but also ensures that the returned memory is zero-initialized. Read more
source§

unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)

🔬This is a nightly-only experimental API. (allocator_api #32838)
Deallocates the memory referenced by ptr. Read more
source§

unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Attempts to extend the memory block. Read more
source§

unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Behaves like grow, but also ensures that the new contents are set to zero before being returned. Read more
source§

unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api #32838)
Attempts to shrink the memory block. Read more
source§

fn by_ref(&self) -> &Selfwhere Self: Sized,

🔬This is a nightly-only experimental API. (allocator_api #32838)
Creates a “by reference” adapter for this instance of Allocator. Read more
source§

impl<S> AsyncIterator for Box<S, Global>where S: AsyncIterator + Unpin + ?Sized,

§

type Item = <S as AsyncIterator>::Item

🔬This is a nightly-only experimental API. (async_iterator #79024)
The type of items yielded by the async iterator.
source§

fn poll_next( self: Pin<&mut Box<S, Global>>, cx: &mut Context<'_> ) -> Poll<Option<<Box<S, Global> as AsyncIterator>::Item>>

🔬This is a nightly-only experimental API. (async_iterator #79024)
Attempt to pull out the next value of this async iterator, registering the current task for wakeup if the value is not yet available, and returning None if the async iterator is exhausted. Read more
source§

fn size_hint(&self) -> (usize, Option<usize>)

🔬This is a nightly-only experimental API. (async_iterator #79024)
Returns the bounds on the remaining length of the async iterator. Read more
1.29.0 · source§

impl Clone for Box<CStr, Global>

source§

fn clone(&self) -> Box<CStr, Global>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
1.3.0 · source§

impl Clone for Box<str, Global>

source§

fn clone(&self) -> Box<str, Global>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Clone for Global

source§

fn clone(&self) -> Global

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Global

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
1.0.0 · source§

impl<T> Default for Box<[T], Global>

source§

fn default() -> Box<[T], Global>

Returns the “default value” for a type. Read more
1.17.0 · source§

impl Default for Box<CStr, Global>

source§

fn default() -> Box<CStr, Global>

Returns the “default value” for a type. Read more
1.0.0 · source§

impl<T> Default for Box<T, Global>where T: Default,

source§

fn default() -> Box<T, Global>

Creates a Box<T>, with the Default value for T.

1.17.0 · source§

impl Default for Box<str, Global>

source§

fn default() -> Box<str, Global>

Returns the “default value” for a type. Read more
source§

impl Default for Global

source§

fn default() -> Global

Returns the “default value” for a type. Read more
1.8.0 · source§

impl<T> Error for Box<T, Global>where T: Error,

source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)
Provides type based access to context intended for error reports. Read more
1.17.0 · source§

impl<T> From<&[T]> for Box<[T], Global>where T: Clone,

source§

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:?}");
Run
1.17.0 · source§

impl From<&CStr> for Box<CStr, Global>

source§

fn from(s: &CStr) -> Box<CStr, Global>

Converts a &CStr into a Box<CStr>, by copying the contents into a newly allocated Box.

1.6.0 · source§

impl From<&str> for Box<dyn Error, Global>

source§

fn from(err: &str) -> Box<dyn Error, Global>

Converts a str into a box of dyn Error.

Examples
use std::error::Error;
use std::mem;

let a_str_error = "a str error";
let a_boxed_error = Box::<dyn Error>::from(a_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run
1.0.0 · source§

impl<'a> From<&str> for Box<dyn Error + Sync + Send + 'a, Global>

source§

fn from(err: &str) -> Box<dyn Error + Sync + Send + 'a, Global>

Converts a str into a box of dyn Error + Send + Sync.

Examples
use std::error::Error;
use std::mem;

let a_str_error = "a str error";
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
assert!(
    mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run
1.17.0 · source§

impl From<&str> for Box<str, Global>

source§

fn from(s: &str) -> Box<str, Global>

Converts a &str into a Box<str>

This conversion allocates on the heap and performs a copy of s.

Examples
let boxed: Box<str> = Box::from("hello");
println!("{boxed}");
Run
1.45.0 · source§

impl<T, const N: usize> From<[T; N]> for Box<[T], Global>

source§

fn from(array: [T; N]) -> Box<[T], Global>

Converts a [T; N] into a Box<[T]>

This conversion moves the array to newly heap-allocated memory.

Examples
let boxed: Box<[u8]> = Box::from([4, 2]);
println!("{boxed:?}");
Run
1.20.0 · source§

impl From<CString> for Box<CStr, Global>

source§

fn from(s: CString) -> Box<CStr, Global>

Converts a CString into a Box<CStr> without copying or allocating.

1.45.0 · source§

impl<T> From<Cow<'_, [T]>> for Box<[T], Global>where T: Clone,

source§

fn from(cow: Cow<'_, [T]>) -> Box<[T], Global>

Converts a Cow<'_, [T]> into a Box<[T]>

When cow is the Cow::Borrowed variant, this conversion allocates on the heap and copies the underlying slice. Otherwise, it will try to reuse the owned Vec’s allocation.

1.45.0 · source§

impl From<Cow<'_, CStr>> for Box<CStr, Global>

source§

fn from(cow: Cow<'_, CStr>) -> Box<CStr, Global>

Converts a Cow<'a, CStr> into a Box<CStr>, by copying the contents if they are borrowed.

1.45.0 · source§

impl From<Cow<'_, str>> for Box<str, Global>

source§

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}");
Run
let unboxed = Cow::Owned("hello".to_string());
let boxed: Box<str> = Box::from(unboxed);
println!("{boxed}");
Run
1.22.0 · source§

impl<'a> From<Cow<'a, str>> for Box<dyn Error, Global>

source§

fn from(err: Cow<'a, str>) -> Box<dyn Error, Global>

Converts a Cow into a box of dyn Error.

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>::from(a_cow_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run
1.22.0 · source§

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>

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))
Run
1.0.0 · source§

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>

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))
Run
1.0.0 · source§

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>

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))
Run
1.6.0 · source§

impl From<String> for Box<dyn Error, Global>

source§

fn from(str_err: String) -> Box<dyn Error, Global>

Converts a String into a box of dyn Error.

Examples
use std::error::Error;
use std::mem;

let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error>::from(a_string_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run
1.0.0 · source§

impl From<String> for Box<dyn Error + Sync + Send, Global>

source§

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))
Run
1.20.0 · source§

impl From<String> for Box<str, Global>

source§

fn from(s: String) -> Box<str, Global>

Converts the given String to a boxed str slice that is owned.

Examples
let s1: String = String::from("hello world");
let s2: Box<str> = Box::from(s1);
let s3: String = String::from(s2);

assert_eq!("hello world", s3)
Run
1.6.0 · source§

impl<T> From<T> for Box<T, Global>

source§

fn from(t: T) -> Box<T, Global>

Converts a T into a Box<T>

The conversion allocates on the heap and moves t from the stack into it.

Examples
let x = 5;
let boxed = Box::new(5);

assert_eq!(Box::from(x), boxed);
Run
1.32.0 · source§

impl<I> FromIterator<I> for Box<[I], Global>

source§

fn from_iter<T>(iter: T) -> Box<[I], Global>where T: IntoIterator<Item = I>,

Creates a value from an iterator. Read more
1.43.0 · source§

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>

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.

§

type Error = Box<[T], Global>

The type returned in the event of a conversion error.
1.66.0 · source§

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>

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
§

type Error = Vec<T, Global>

The type returned in the event of a conversion error.
source§

impl Copy for Global

source§

impl<T, U> DispatchFromDyn<Box<U, Global>> for Box<T, Global>where T: Unsize<U> + ?Sized, U: ?Sized,

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.