[−][src]Struct abi_stable::sabi_types::LateStaticRef
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]
_: PointsToPrefixFields<T, P>,
ptr: PrefixRef<P>
) -> Self where
P: 'static,
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]
_target: ImmutableRefTarget<T, U>,
ptr: NonNull<U>
) -> Self
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]
T: ImmutableRef + 'static,
pub fn try_init<F, E>(&self, initializer: F) -> Result<T, E> where
F: FnOnce() -> Result<T, E>,
[src]
F: FnOnce() -> Result<T, E>,
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]
F: FnOnce() -> T,
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]
T: __StableAbi,
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]
T: __StableAbi,
type IsNonZeroType = False
Whether this type has a single invalid bit-pattern. Read more
pub const LAYOUT: &'static TypeLayout
[src]
pub const ABI_CONSTS: AbiConsts
[src]
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]
T: Unpin,
Blanket Implementations
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T
[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]
U: From<T>,
impl<T> SelfOps for T where
T: ?Sized,
[src]
T: ?Sized,
pub const T: PhantomData<fn() -> Self>
[src]
pub const T_D: PhantomData<Self>
[src]
pub fn assert_ty(self, _other: PhantomData<fn() -> Self>) -> Self
[src]
pub fn assert_ty_ref(&self, _other: PhantomData<fn() -> Self>) -> &Self
[src]
pub fn assert_ty_mut(&mut self, _other: PhantomData<fn() -> Self>) -> &mut Self
[src]
pub fn ty_(&self) -> PhantomData<fn() -> Self>
[src]
pub fn ty_d(&self) -> PhantomData<Self>
[src]
pub fn ty_inv(&self) -> PhantomData<fn(Self) -> Self>
[src]
pub fn ty_inv_ref(&self) -> PhantomData<Cell<&Self>>
[src]
pub fn eq_id(&self, other: &Self) -> bool
[src]
pub fn piped<F, U>(self, f: F) -> U where
F: FnOnce(Self) -> U,
[src]
F: FnOnce(Self) -> U,
pub fn piped_ref<'a, F, U>(&'a self, f: F) -> U where
F: FnOnce(&'a Self) -> U,
[src]
F: FnOnce(&'a Self) -> U,
pub fn piped_mut<'a, F, U>(&'a mut self, f: F) -> U where
F: FnOnce(&'a mut Self) -> U,
[src]
F: FnOnce(&'a mut Self) -> U,
pub fn mutated<F>(self, f: F) -> Self where
F: FnOnce(&mut Self),
[src]
F: FnOnce(&mut Self),
pub fn observe<F>(self, f: F) -> Self where
F: FnOnce(&Self),
[src]
F: FnOnce(&Self),
pub fn into_<T>(self, PhantomData<fn() -> T>) -> T where
Self: Into<T>,
[src]
Self: Into<T>,
pub fn as_ref_<T>(&self) -> &T where
Self: AsRef<T>,
T: ?Sized,
[src]
Self: AsRef<T>,
T: ?Sized,
pub fn as_mut_<T>(&mut self) -> &mut T where
Self: AsMut<T>,
T: ?Sized,
[src]
Self: AsMut<T>,
T: ?Sized,
pub fn drop_(self)
[src]
impl<This> TransmuteElement for This where
This: ?Sized,
[src]
This: ?Sized,
pub unsafe fn transmute_element<T>(self) -> Self::TransmutedPtr where
Self: CanTransmuteElement<T>,
Self::Target: Sized,
[src]
Self: CanTransmuteElement<T>,
Self::Target: Sized,
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The error type returned when the conversion fails.
pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<T> TypeIdentity for T where
T: ?Sized,
[src]
T: ?Sized,
type Type = T
The same type as Self. Read more
pub fn into_type_val(self) -> Self::Type where
Self::Type: Sized,
[src]
Self::Type: Sized,
pub fn into_type_ref(&self) -> &Self::Type
[src]
pub fn into_type_mut(&mut self) -> &mut Self::Type
[src]
pub fn into_type_box(self: Box<Self, Global>) -> Box<Self::Type, Global>
[src]
pub fn into_type_arc(this: Arc<Self>) -> Arc<Self::Type>
[src]
pub fn into_type_rc(this: Rc<Self>) -> Rc<Self::Type>
[src]
pub fn from_type_val(this: Self::Type) -> Self where
Self::Type: Sized,
[src]
Self::Type: Sized,