object_type/
object.rs

1use std::fmt::{Display, Formatter};
2
3
4
5/// Wrapper for anything type
6#[derive(Debug, Clone, Copy, PartialOrd, PartialEq)]
7pub struct Object {
8    ptr: *mut (),
9}
10
11
12impl Object {
13    pub fn new<T>(val: *mut T) -> Self {
14        Self {
15            ptr: val as *mut ()
16        }
17    }
18
19
20    /// Returns the cloned value from struct
21    /// ------------------------------------
22    /// *If (T != type of value in struct) => ???*
23    /// Example:
24    /// ```
25    /// let int_object = object_type::obj!(6982_i32);
26    /// let _ = int_object.get::<i32>(); // Ok
27    /// // let _ = int_object.get::<i64>(); => ???
28    /// ```
29    pub fn get<T: Clone>(&self) -> T {
30        unsafe { self.__get_unsafe() }
31    }
32
33    unsafe fn __get_unsafe<T: Clone>(&self) -> T {
34        (*(self.ptr as *mut T)).clone()
35    }
36
37
38    /// Returns the value pointer casted to <*T*> type
39    /// --------------------------------------------
40    /// *If (T != type of value in struct) => ???*
41    /// Example:
42    /// ```
43    /// let int_object = object_type::obj!(6982_i32);
44    /// let _ = int_object.get_ptr::<i32>(); // Ok
45    /// // let _ = int_object.get_ptr::<i64>(); => ???
46    /// ```
47    pub fn get_ptr<T>(&self) -> *mut T {
48        unsafe { self.__get_ptr_unsafe() }
49    }
50
51    unsafe fn __get_ptr_unsafe<T>(&self) -> *mut T {
52        self.ptr as *mut T
53    }
54
55
56    /// Returns the raw mutable pointer to value as unit type
57    pub fn raw(&self) -> *mut () {
58        self.ptr
59    }
60
61
62    /// Unstable? 
63    ///
64    /// Example:
65    /// ```
66    /// let int_object = object_type::obj!(2372_i16);
67    /// println!("=> {}", int_object.__value_to_string::<i16>());
68    /// ```
69    pub fn __value_to_string<T: ToString>(&self) -> String {
70        unsafe { self.__value_to_string_unsafe::<T>() }
71    }
72
73    unsafe fn __value_to_string_unsafe<T: ToString>(&self) -> String {
74        (*self.get_ptr::<T>()).to_string()
75    }
76
77
78    pub fn equals<T>(&self, other: T) -> bool
79        where T: PartialEq + Clone,
80    {
81        other.eq(&self.get::<T>())
82    }
83}
84
85
86impl Default for Object {
87    fn default() -> Self {
88        Self { ptr: std::ptr::null_mut(), }
89    }
90}
91
92
93impl Display for Object {
94    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
95        write!(f, "Object({:?})", self.ptr)
96    }
97}
98
99
100
101/// Returns an instance of Object
102/// -----------------------------
103/// Example:
104/// ```
105/// let object = object_type::obj!("str test");
106/// ```
107#[macro_export]
108macro_rules! obj {
109    ($val:expr) => {
110        $crate::Object::new(&mut $val)
111    };
112    () => {
113        $crate::Object::default()
114    }
115}
116
117
118
119
120