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
pub const fn from_prefixref<P>(
_: PointsToPrefixFields<T, P>,
ptr: PrefixRef<P>
) -> Self where
P: 'static,
pub const fn from_prefixref<P>(
_: PointsToPrefixFields<T, P>,
ptr: PrefixRef<P>
) -> Self where
P: 'static,
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
}
pub const unsafe fn from_custom<U: 'static>(
_target: ImmutableRefTarget<T, U>,
ptr: NonNull<U>
) -> Self
pub const unsafe fn from_custom<U: 'static>(
_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::{
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
type StaticEquivalent = _static_LateStaticRef<__GetStaticEquivalent<T>>
type IsNonZeroType = False
type IsNonZeroType = False
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
impl<T> Unpin for LateStaticRef<T> where
T: Unpin,
Blanket Implementations
Mutably borrows from an owned value. Read more
type ForSelf = WithMetadata_<T, T>
type ForSelf = WithMetadata_<T, T>
This is always WithMetadata_<Self, Self>
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
unsafe fn transmute_element<T>(
self
) -> <Self as CanTransmuteElement<T>>::TransmutedPtr where
Self: CanTransmuteElement<T>,
unsafe fn transmute_element<T>(
self
) -> <Self as CanTransmuteElement<T>>::TransmutedPtr where
Self: CanTransmuteElement<T>,
Transmutes the element type of this pointer.. Read more
type Type = T
type Type = T
This is always Self
.
Converts a value back to the original type.
Converts a mutable reference back to the original type.
alloc
only.Converts a box back to the original type.
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.
alloc
only.Converts a box back to the original type.
alloc
only.Converts an Arc back to the original type.
alloc
only.Converts an Rc back to the original type.