Macro kernel::try_init

source ·
macro_rules! try_init {
    ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
        $($fields:tt)*
    }) => { ... };
    ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
        $($fields:tt)*
    }? $err:ty) => { ... };
}
Expand description

Construct an in-place fallible initializer for structs.

This macro defaults the error to Error. If you need Infallible, then use init!.

The syntax is identical to try_pin_init!. If you want to specify a custom error, append ? $type after the struct initializer. The safety caveats from try_pin_init! also apply:

  • unsafe code must guarantee either full initialization or return an error and allow deallocation of the memory.
  • the fields are initialized in the order given in the initializer.
  • no references to fields are allowed to be created inside of the initializer.

Examples

use kernel::{init::{PinInit, zeroed}, error::Error};
struct BigBuf {
    big: Box<[u8; 1024 * 1024 * 1024]>,
    small: [u8; 1024 * 1024],
}

impl BigBuf {
    fn new() -> impl Init<Self, Error> {
        try_init!(Self {
            big: Box::init(zeroed())?,
            small: [0; 1024 * 1024],
        }? Error)
    }
}