Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created Jul 13, 2020
Embed
What would you like to do?
Code shared from the Rust Playground
use std::collections::HashMap;
use std::sync::Mutex;
use std::any::TypeId;
use once_cell::sync::OnceCell;
trait Core {
fn foo() -> &'static str;
}
trait Wrap : Core
where Self : 'static
{
fn foo() -> &'static str {
static value : OnceCell<
Mutex<HashMap<TypeId, &'static str>>>
= OnceCell::new();
let _: &'static Mutex<HashMap<TypeId, &'static str>> =
value.get_or_init(|| {
Mutex::new(HashMap::new())
});
let v: &'static str =
value
.get()
.unwrap()
.lock()
.unwrap()
.entry(TypeId::of::<Self>())
.or_insert_with(|| {
let string = format!("wrapped {}", <Self as Core>::foo());
Box::leak(string.into_boxed_str())
});
v
}
}
// using Wrap and Core
struct T {}
impl Wrap for T {}
impl Core for T {
fn foo() -> &'static str {
"T"
}
}
struct F {}
impl Wrap for F {}
impl Core for F {
fn foo() -> &'static str {
"F"
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
assert_eq!("wrapped F", <F as Wrap>::foo());
assert_eq!("F", <F as Core>::foo());
assert_eq!("T", <T as Core>::foo());
assert_eq!("wrapped T", <T as Wrap>::foo());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment