Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 13, 2020 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/a4afecb3fb33f8a9cf815b124e50d8b4 to your computer and use it in GitHub Desktop.
Save rust-play/a4afecb3fb33f8a9cf815b124e50d8b4 to your computer and use it in GitHub Desktop.
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