Struct abi_stable::sabi_types::LateStaticRef[][src]

#[repr(C)]
pub struct LateStaticRef<T> { /* fields omitted */ }
Expand description

A late-initialized static reference,with fallible initialization.

As opposed to Once, this allows initialization of its static reference to happen fallibly, by returning a Result<_,_> from the try_init function, or by panicking inside either initialization function.

On Err(_) and panics,one can try initialializing the static reference again.

Example

This lazily loads a configuration file.


use abi_stable::{
    sabi_types::LateStaticRef,
    std_types::{RBox, RBoxError, RHashMap, RString},
    utils::leak_value,
};

use std::{fs, io, path::Path};

use serde::Deserialize;

#[derive(Deserialize)]
pub struct Config {
    pub user_actions: RHashMap<RString, UserAction>,
}

#[derive(Deserialize)]
pub enum UserAction {
    Include,
    Ignore,
    ReplaceWith,
}

fn load_config(file_path: &Path) -> Result<&'static Config, RBoxError> {
    static CONFIG: LateStaticRef<&Config> = LateStaticRef::new();

    CONFIG.try_init(|| {
        let file = load_file(file_path).map_err(RBoxError::new)?;
        let config =
            serde_json::from_str::<Config>(&file).map_err(RBoxError::new)?;
        Ok(leak_value(config))
    })
}

Implementations

Constructs the LateStaticRef in an uninitialized state.

Example
use abi_stable::sabi_types::LateStaticRef;

static LATE_REF: LateStaticRef<&String> = LateStaticRef::new();

Constructs LateStaticRef, initialized with value.

Example
use abi_stable::sabi_types::LateStaticRef;

static LATE_REF: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!");

Constructs LateStaticRef from a PrefixRef.

Example
use abi_stable::{
    pointer_trait::ImmutableRef,
    prefix_type::{PrefixRefTrait, PrefixTypeTrait, WithMetadata},
    sabi_types::LateStaticRef,
    StableAbi,
};

fn main() {
    assert_eq!(LATE_REF.get().unwrap().get_number()(), 100);
}

pub static LATE_REF: LateStaticRef<PersonMod_Ref> = {
    // This is how you can construct a `LateStaticRef<Foo_Ref>`,
    //  from a `Foo_Ref` at compile-time.
    //
    // If you don't need a `LateStaticRef` you can construct a `PersonMod_Ref` constant,
    // and use that.
    LateStaticRef::from_prefixref(PrefixRefTrait::PREFIX_FIELDS, MODULE.0)
};

#[repr(C)]
#[derive(StableAbi)]
#[sabi(kind(Prefix))]
pub struct PersonMod {
    /// The `#[sabi(last_prefix_field)]` attribute here means that this is
    /// the last field in this struct that was defined in the
    /// first compatible version of the library.
    /// Moving this attribute is a braeking change.
    #[sabi(last_prefix_field)]
    pub get_number: extern "C" fn() -> u32,
}

const MODULE: PersonMod_Ref = {
    const S: &WithMetadata<PersonMod> =
        &WithMetadata::new(PrefixTypeTrait::METADATA, PersonMod { get_number });

    PersonMod_Ref(S.static_as_prefix())
};

extern "C" fn get_number() -> u32 {
    100
}

Constructs LateStaticRef from a NonNull pointer.

Safety

The passed in pointer must be valid for passing to <T as ImmutableRef>::from_nonnull, it must be a valid pointer to U, and be valid to dereference for the rest of the program’s lifetime.

Example
use abi_stable::{
    pointer_trait::ImmutableRef, sabi_types::LateStaticRef, utils::ref_as_nonnull,
    StableAbi,
};

use std::ptr::NonNull;

#[derive(Copy, Clone)]
struct Foo<'a>(&'a u64);

impl<'a> Foo<'a> {
    const fn as_nonnull(self) -> NonNull<u64> {
        ref_as_nonnull(self.0)
    }
}

unsafe impl<'a> ImmutableRef for Foo<'a> {
    type Target = u64;
}

const MODULE: LateStaticRef<Foo<'static>> = {
    unsafe {
        LateStaticRef::from_custom(ImmutableRef::TARGET, Foo(&100).as_nonnull())
    }
};

Lazily initializes the LateStaticRef with initializer, returning the T if either it was already initialized,or if initalizer returned Ok(..).

If initializer returns an Err(...) this returns the error and allows the LateStaticRef to be initializer later.

If initializer panics,the panic is propagated, and the reference can be initalized later.

Example
use abi_stable::{sabi_types::LateStaticRef, utils::leak_value};

static LATE: LateStaticRef<&String> = LateStaticRef::new();

static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!");

assert_eq!(LATE.try_init(|| Err("oh no!")), Err("oh no!"));
assert_eq!(
    LATE.try_init(|| -> Result<&'static String, ()> {
        Ok(leak_value("Yay".to_string()))
    })
    .map(|s| s.as_str()),
    Ok("Yay"),
);

assert_eq!(EARLY.try_init(|| Err("oh no!")), Ok(&"Hello!"));

Lazily initializes the LateStaticRef with initializer, returning the T if either it was already initialized, or initalizer returns it without panicking.

If initializer panics,the panic is propagated, and the reference can be initalized later.

Example
use abi_stable::{sabi_types::LateStaticRef, utils::leak_value};

static LATE: LateStaticRef<&String> = LateStaticRef::new();

static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!");

let _ = std::panic::catch_unwind(|| {
    LATE.init(|| panic!());
});

assert_eq!(LATE.init(|| leak_value("Yay".to_string())), &"Yay");

assert_eq!(EARLY.init(|| panic!()), &"Hello!");

Returns Some(x:T) if the LateStaticRef was initialized, otherwise returns None.

Example
use abi_stable::{sabi_types::LateStaticRef, utils::leak_value};

static LATE: LateStaticRef<&String> = LateStaticRef::new();

static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!");

let _ = std::panic::catch_unwind(|| {
    LATE.init(|| panic!());
});

assert_eq!(LATE.get(), None);
LATE.init(|| leak_value("Yay".to_string()));
assert_eq!(LATE.get().map(|s| s.as_str()), Some("Yay"));

assert_eq!(EARLY.get(), Some(&"Hello!"));

Trait Implementations

Whether this type has a single invalid bit-pattern. Read more

The layout of the type provided by implementors.

const-equivalents of the associated types.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

This is always WithMetadata_<Self, Self>

Performs the conversion.

Gets a reference to a field, determined by offset. Read more

Gets a muatble reference to a field, determined by offset. Read more

Gets a const pointer to a field, the field is determined by offset. Read more

Gets a mutable pointer to a field, determined by offset. Read more

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more

Swaps a field (determined by offset) with the same field in right. Read more

Gets a copy of a field (determined by offset). The field is determined by offset. Read more

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more

Swaps a field (determined by offset) with the same field in right. Read more

Gets a copy of a field (determined by offset). The field is determined by offset. Read more

Compares the address of self with the address of other. Read more

Emulates the pipeline operator, allowing method syntax in more places. Read more

The same as piped except that the function takes &Self Useful for functions that take &Self instead of Self. Read more

The same as piped, except that the function takes &mut Self. Useful for functions that take &mut Self instead of Self. Read more

Mutates self using a closure taking self by mutable reference, passing it along the method chain. Read more

Observes the value of self, passing it along unmodified. Useful in long method chains. Read more

Performs a conversion with Into. using the turbofish .into_::<_>() syntax. Read more

Performs a reference to reference conversion with AsRef, using the turbofish .as_ref_::<_>() syntax. Read more

Performs a mutable reference to mutable reference conversion with AsMut, using the turbofish .as_mut_::<_>() syntax. Read more

Drops self using method notation. Alternative to std::mem::drop. Read more

Transmutes the element type of this pointer.. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

This is always Self.

Converts a value back to the original type.

Converts a reference back to the original type.

Converts a mutable reference back to the original type.

This is supported on crate feature alloc only.

Converts a box back to the original type.

This is supported on crate feature alloc only.

Converts an Arc back to the original type. Read more

This is supported on crate feature alloc only.

Converts an Rc back to the original type. Read more

Converts a value back to the original type.

Converts a reference back to the original type.

Converts a mutable reference back to the original type.

This is supported on crate feature alloc only.

Converts a box back to the original type.

This is supported on crate feature alloc only.

Converts an Arc back to the original type.

This is supported on crate feature alloc only.

Converts an Rc back to the original type.