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

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

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

impl<T> LateStaticRef<T>[src]

pub const fn new() -> Self[src]

Constructs the LateStaticRef in an uninitialized state.

Example

use abi_stable::sabi_types::LateStaticRef;

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

impl<T> LateStaticRef<&'static T>[src]

pub const fn from_ref(value: &'static T) -> Self[src]

Constructs LateStaticRef, initialized with value.

Example

use abi_stable::sabi_types::LateStaticRef;

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

impl<T: 'static> LateStaticRef<T>[src]

pub const fn from_prefixref<P>(
    _: PointsToPrefixFields<T, P>,
    ptr: PrefixRef<P>
) -> Self where
    P: 'static, 
[src]

Constructs LateStaticRef from a PrefixRef.

Example

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

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 fn get_number()->u32{
    100
}

impl<T: 'static> LateStaticRef<T>[src]

pub const unsafe fn from_custom<U: 'static>(
    _target: ImmutableRefTarget<T, U>,
    ptr: NonNull<U>
) -> Self
[src]

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::{
    StableAbi,
    pointer_trait::ImmutableRef,
    sabi_types::LateStaticRef,
    utils::ref_as_nonnull,
};
 
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(),
        ) 
    }
};

impl<T> LateStaticRef<T> where
    T: ImmutableRef + 'static, 
[src]

pub fn try_init<F, E>(&self, initializer: F) -> Result<T, E> where
    F: FnOnce() -> Result<T, E>, 
[src]

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!") );

pub fn init<F>(&self, initializer: F) -> T where
    F: FnOnce() -> T, 
[src]

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!" );

pub fn get(&self) -> Option<T>[src]

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

impl<T> GetStaticEquivalent_ for LateStaticRef<T> where
    T: __StableAbi
[src]

type StaticEquivalent = _static_LateStaticRef<__GetStaticEquivalent<T>>

impl<T> RefUnwindSafe for LateStaticRef<T>[src]

impl<T: Send> Send for LateStaticRef<T>[src]

impl<T> StableAbi for LateStaticRef<T> where
    T: __StableAbi
[src]

type IsNonZeroType = False

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

impl<T: Sync> Sync for LateStaticRef<T>[src]

impl<T> UnwindSafe for LateStaticRef<T>[src]

Auto Trait Implementations

impl<T> Unpin for LateStaticRef<T> where
    T: Unpin
[src]

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> GetWithMetadata for T[src]

type ForSelf = WithMetadata_<T, T>

This is always WithMetadata_<Self, Self>

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> SelfOps for T where
    T: ?Sized
[src]

impl<This> TransmuteElement for This where
    This: ?Sized
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The error type returned when the conversion fails.

impl<T> TypeIdentity for T where
    T: ?Sized
[src]

type Type = T

The same type as Self. Read more