intuicio_framework_pointer/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//! Experiments with highly unsafe pointer access.
//! A.k.a. what could go wrong when trying to emulate direct pointer access in scripting.

use std::{
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

use intuicio_core::{registry::Registry, transformer::ValueTransformer};

pub type VoidPtr = Ptr<()>;

#[repr(transparent)]
pub struct Ptr<T> {
    pointer: *mut T,
}

impl<T> Default for Ptr<T> {
    fn default() -> Self {
        Self {
            pointer: std::ptr::null_mut(),
        }
    }
}

impl<T> Ptr<T> {
    pub fn is_null(self) -> bool {
        self.pointer.is_null()
    }

    pub fn to_ptr(self) -> *const T {
        self.pointer
    }

    pub fn to_ptr_mut(self) -> *mut T {
        self.pointer
    }

    /// # Safety
    pub unsafe fn as_ref(&self) -> Option<&T> {
        if self.is_null() {
            None
        } else {
            Some(&*(self.pointer as *const T))
        }
    }

    /// # Safety
    pub unsafe fn as_ref_mut(&mut self) -> Option<&mut T> {
        if self.is_null() {
            None
        } else {
            Some(&mut *self.pointer)
        }
    }

    /// # Safety
    pub unsafe fn cast<U>(self) -> Ptr<U> {
        Ptr {
            pointer: self.pointer as *mut U,
        }
    }

    /// # Safety
    pub unsafe fn into_box(self) -> Box<T> {
        Box::from_raw(self.pointer)
    }

    /// # Safety
    pub unsafe fn from_box(value: Box<T>) -> Self {
        Self {
            pointer: Box::leak(value) as *mut T,
        }
    }
}

impl<T> From<*mut T> for Ptr<T> {
    fn from(value: *mut T) -> Self {
        Self { pointer: value }
    }
}

impl<T> From<*const T> for Ptr<T> {
    fn from(value: *const T) -> Self {
        Self {
            pointer: value as *mut T,
        }
    }
}

impl<T> From<&mut T> for Ptr<T> {
    fn from(value: &mut T) -> Self {
        Self {
            pointer: value as *mut T,
        }
    }
}

impl<T> From<&T> for Ptr<T> {
    fn from(value: &T) -> Self {
        Self {
            pointer: value as *const T as *mut T,
        }
    }
}

impl<T> From<Ptr<T>> for *const T {
    fn from(value: Ptr<T>) -> Self {
        value.pointer as *const T
    }
}

impl<T> From<Ptr<T>> for *mut T {
    fn from(value: Ptr<T>) -> Self {
        value.pointer
    }
}

impl<T> Deref for Ptr<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { self.as_ref().expect("Trying to dereference null pointer!") }
    }
}

impl<T> DerefMut for Ptr<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe {
            self.as_ref_mut()
                .expect("Trying to dereference null pointer!")
        }
    }
}

impl<T> Copy for Ptr<T> {}

impl<T> Clone for Ptr<T> {
    fn clone(&self) -> Self {
        *self
    }
}

// NOTE: I know this is bad, don't kill me - again, it's for experiments only sake,
// some day it might disappear in favor of some smarter solution.
unsafe impl<T> Send for Ptr<T> where T: Send {}
unsafe impl<T> Sync for Ptr<T> where T: Sync {}

impl<T> std::fmt::Debug for Ptr<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.pointer)
    }
}

impl<T> std::fmt::Display for Ptr<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.pointer)
    }
}

pub struct PtrValueTransformer<T: Default + Clone + 'static>(PhantomData<fn() -> T>);

impl<T: Default + Clone + 'static> ValueTransformer for PtrValueTransformer<T> {
    type Type = T;
    type Borrow<'r> = &'r T;
    type BorrowMut<'r> = &'r mut T;
    type Dependency = ();
    type Owned = T;
    type Ref = Ptr<T>;
    type RefMut = Ptr<T>;

    fn from_owned(_: &Registry, value: Self::Type) -> Self::Owned {
        value
    }

    fn from_ref(_: &Registry, value: &Self::Type, _: Option<Self::Dependency>) -> Self::Ref {
        Ptr::from(value)
    }

    fn from_ref_mut(
        _: &Registry,
        value: &mut Self::Type,
        _: Option<Self::Dependency>,
    ) -> Self::RefMut {
        Ptr::from(value)
    }

    fn into_owned(value: Self::Owned) -> Self::Type {
        value
    }

    fn into_ref(value: &Self::Ref) -> Self::Borrow<'_> {
        unsafe { value.as_ref().unwrap() }
    }

    fn into_ref_mut(value: &mut Self::RefMut) -> Self::BorrowMut<'_> {
        unsafe { value.as_ref_mut().unwrap() }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use intuicio_core::prelude::*;
    use intuicio_derive::intuicio_function;

    #[test]
    fn test_async() {
        fn is_async<T: Send + Sync>() {}

        is_async::<Ptr<usize>>();
        is_async::<Ptr<Ptr<usize>>>();
    }

    #[intuicio_function(transformer = "PtrValueTransformer")]
    fn add(a: &usize, b: &mut usize) -> usize {
        *a + *b
    }

    #[test]
    fn test_raw_pointer_on_stack() {
        let mut registry = Registry::default().with_basic_types();
        registry.add_type(define_native_struct! {
            registry => struct (Ptr<usize>) {}
        });
        let add = registry.add_function(add::define_function(&registry));
        let mut context = Context::new(10240, 10240);
        let a = 40usize;
        let mut b = 2usize;
        let (r,) = add.call::<(usize,), _>(
            &mut context,
            &registry,
            (Ptr::from(&a), Ptr::from(&mut b)),
            true,
        );
        assert_eq!(r, 42);
    }

    #[test]
    fn test_allocation() {
        unsafe {
            let a = Box::new(42usize);
            let mut b = Ptr::from_box(a);
            *b.as_ref_mut().unwrap() = 10;
            let c = b.into_box();
            let d = *c;
            assert_eq!(d, 10);
        }
    }
}