Struct avr_oxide::StaticWrap
source · pub struct StaticWrap<T: 'static> { /* private fields */ }
Expand description
In an embedded environment, we often need static references to things, for example because we are passing them on to an interrupt service routine.
We also often need to do some non-const setup on those things, something Rust makes quite ugly (mutable statics are unsafe and unpleasant to work with.)
Fortunately, we know that if our main
routine never returns (i.e. it
is declared -> !
) we will never drop any locals there, and can thus
safely get static references to them right? Well, right in that we
know that - but for ‘reasons’ (panic_unwind
, I’m glaring at you),
the Rust compiler doesn’t know that.
Thus, StaticWrap<T>
. This will wrap a variable that you know
will never be dropped, and then give you access to static references
via the [StaticWrap::static_ref()
] and [StaticWrap::static_ref_mut()
]
methods.
The contract you promise to obey is that you will indeed never drop
them of course. This is enforced at runtime - sropping a StaticWrap
is a fatal runtime error.
The normal borrowing rules - i.e. a maximum of one mutable borrow, and no mutable borrows if there are immutable borrows - for a variable placed inside a StaticWrap, are enforced at runtime.
Implementations§
source§impl<T> StaticWrap<T>
impl<T> StaticWrap<T>
sourcepub fn new(wrapping: T) -> Self
pub fn new(wrapping: T) -> Self
Create a new StaticWrap around the given variable. You may then
access static references using
[StaticWrap::static_ref()
] and [StaticWrap::static_ref_mut()
].
§Warning
You promise this instance will never be dropped. If it is, a fatal runtime error will result.
sourcepub fn borrow(&self) -> StaticRef<'static, T>
pub fn borrow(&self) -> StaticRef<'static, T>
Obtain a static reference to the contained instance
sourcepub fn borrow_mut(&mut self) -> StaticRefMut<'static, T>
pub fn borrow_mut(&mut self) -> StaticRefMut<'static, T>
Obtain a mutable static reference to the contained instance.
§SAFETY
We don’t (or rather, the borrow checker can’t) enforce the limitation that a mutual reference should be exclusive. Be careful what you wish for.