Crate bounded_static
source · [−]Expand description
Provides the ToBoundedStatic and IntoBoundedStatic traits and ToStatic derive macro.
As described in the Common Rust Lifetime Misconceptions:
T: 'staticshould be read as “Tis bounded by a'staticlifetime” not “Thas a'staticlifetime”.
The traits ToBoundedStatic and IntoBoundedStatic can be used to convert any suitable T and &T to an
owned T such that T: 'static. Both traits define an associated type which is bounded by 'static and provide
a method to convert to that bounded type:
pub trait ToBoundedStatic {
type Static: 'static;
fn to_static(&self) -> Self::Static;
}
pub trait IntoBoundedStatic {
type Static: 'static;
fn into_static(self) -> Self::Static;
}Implementations of ToBoundedStatic and IntoBoundedStatic are provided for the following core types:
- Primitives (no-op conversions)
- Option
Additional implementations are available by enabling the following features:
-
allocfor common types from thealloccrate: -
collectionsfor all collection types in thealloccrate: -
stdfor additional types fromstd:
Note that collections, alloc and std are enabled be default.
Examples
Given a structure which can be borrow or owned and a function which requires its argument is bounded by the
'static lifetime:
struct Foo<'a> {
bar: Cow<'a, str>,
baz: Vec<Cow<'a, str>>,
}
fn ensure_static<T: 'static>(_: T) {}We can implement ToBoundedStatic (and IntoBoundedStatic) for Foo<'_>:
struct Foo<'a> {
bar: Cow<'a, str>,
baz: Vec<Cow<'a, str>>,
}
impl ToBoundedStatic for Foo<'_> {
type Static = Foo<'static>;
fn to_static(&self) -> Self::Static {
Foo { bar: self.bar.to_static(), baz: self.baz.to_static() }
}
}This allows is to convert to an owned representation such that it is now bounded by 'static:
#[test]
fn test() {
let s = String::from("data");
let foo = Foo { bar: Cow::from(&s), baz: vec![Cow::from(&s)] };
let to_static = foo.to_static();
ensure_static(to_static);
}Derive
These traits may be automatically derived for any struct or enum that can be converted to a form that is
bounded by 'static by using the ToStatic macro. It support all struct flavors (unit, named & unnamed),
all enum variant flavors (unit, named & unnamed). It does not currently support union.
To use the ToStatic macro you must enable the derive feature:
bounded-static = { version = "0.2.0", features = [ "derive" ] }Examples
/// Named field struct
#[derive(ToStatic)]
struct Foo<'a> {
aaa: Cow<'a, str>,
bbb: &'static str,
ccc: Baz<'a>,
}
/// Unnamed field struct
#[derive(ToStatic)]
struct Bar<'a, 'b>(u128, HashMap<Cow<'a, str>, Cow<'b, str>>);
/// Unit struct
#[derive(ToStatic)]
struct Qux;
#[derive(ToStatic)]
enum Baz<'a> {
First(String, usize, Vec<Cow<'a, str>>),
Second { fst: u32, snd: &'static str },
Third,
}Traits
A trait for converting an owned T into an owned T such that T: 'static.
A trait for converting &T to an owned T such that T: 'static.
Derive Macros
Re-export for the custom derive macro ToStatic.
The ToStatic derive macro.