SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::any::{Any, TypeId};
  2. use std::borrow::Borrow;
  3. use std::mem;
  4.  
  5. pub struct Dynamic {
  6.     pub type_id: TypeId,
  7.     val: Box<dyn Any + Send + Sync>,
  8. }
  9.  
  10. impl<T> From<T> for Dynamic where T: Any + Send + Sync {
  11.     fn from(val: T) -> Self {
  12.         Dynamic {
  13.             type_id: TypeId::of::<T>(),
  14.             val: Box::new(val),
  15.         }
  16.     }
  17. }
  18.  
  19. impl<T: Any + Send + Sync> Dynamic {
  20.     pub fn this<T>(&self) -> (bool, &T) {
  21.         match self.val.downcast::<T>() {
  22.             Ok(val) => (true, val.borrow()),
  23.             Err(_) => (false, Box::new(unsafe { mem::zeroed() } ))
  24.         }
  25.     }
  26.  
  27.     pub fn am(&self) -> (bool, &T) {
  28.         (true, self.borrow())
  29.     }
  30. }
  31.  
  32. #[test]
  33. fn test() {
  34.     let object = Dynamic::from("test");
  35.  
  36.     assert_eq!(object.am(), object.this::<&str>())
  37. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top