Guest User

Untitled

a guest
Jan 16th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. #[macro_use]
  2. extern crate lazy_static;
  3.  
  4. use std::collections::HashMap;
  5. use std::sync::Mutex;
  6. use std::fmt::Display;
  7.  
  8. trait Value: Send + Display {
  9. fn box_clone(&self) -> Box<dyn Value>;
  10. }
  11.  
  12. /*impl Value for isize {
  13. fn box_clone(&self) -> Box<dyn Value> {
  14. Box::new((*self).clone())
  15. }
  16. }
  17.  
  18. impl Value for String {
  19. fn box_clone(&self) -> Box<dyn Value> {
  20. Box::new((*self).clone())
  21. }
  22. }*/
  23.  
  24. impl<T: 'static + Send + Clone + Display> Value for T {
  25. fn box_clone(&self) -> Box<dyn Value> {
  26. Box::new((*self).clone())
  27. }
  28. }
  29.  
  30. #[derive(Clone)]
  31. struct S {
  32. value: Box<dyn Value>
  33. }
  34.  
  35. impl Clone for Box<dyn Value> {
  36. fn clone(&self) -> Box<dyn Value> {
  37. self.box_clone()
  38. }
  39. }
  40.  
  41. lazy_static! {
  42. static ref REGISTRY: Mutex<HashMap<String, S>> = {
  43. Mutex::new(HashMap::new())
  44. };
  45. }
  46.  
  47. impl REGISTRY {
  48. fn get(&self, key: &str) -> Option<S> {
  49. self.lock().unwrap().get(&String::from(key)).map(|s| s.clone())
  50. }
  51.  
  52. fn set(&self, key: &str, value: S) -> Option<S> {
  53. self.lock().unwrap().insert(String::from(key), value)
  54. }
  55. }
  56.  
  57. fn main() {
  58. REGISTRY.set("foo", S { value: Box::new(String::from("hello world")) });
  59. REGISTRY.set("bar", S { value: Box::new(123) });
  60.  
  61. println!("{}", REGISTRY.get("foo").unwrap().value);
  62. println!("{}", REGISTRY.get("bar").unwrap().value);
  63. }
Add Comment
Please, Sign In to add comment