-
-
Save rust-play/a4afecb3fb33f8a9cf815b124e50d8b4 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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