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
use std::{
fmt,
ops::{Deref, DerefMut},
};
#[repr(C)]
#[derive(Copy)]
pub struct Fixed<T> {
ptr: *const T,
}
unsafe impl<T: Send> Send for Fixed<T> {}
unsafe impl<T: Sync> Sync for Fixed<T> {}
impl<T> fmt::Debug for Fixed<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Fixed {:?}", self.ptr)
}
}
impl<T> Clone for Fixed<T> {
fn clone(&self) -> Fixed<T> {
Self { ptr: self.ptr }
}
}
impl<T> Fixed<T> {
pub fn new(data: T) -> Fixed<T> {
Self {
ptr: Box::into_raw(Box::new(data)),
}
}
pub fn from_static(data: &'static T) -> Fixed<T> {
Self { ptr: data }
}
pub fn as_ptr(&self) -> *const T {
self.ptr
}
}
impl<T, D: Deref<Target = T>> From<&'static D> for Fixed<T> {
fn from(data: &'static D) -> Fixed<T> {
Fixed { ptr: data.deref() }
}
}
impl<T> AsRef<T> for Fixed<T> {
fn as_ref(&self) -> &T {
unsafe { &*self.ptr }
}
}
impl<T> Deref for Fixed<T> {
type Target = T;
fn deref(&self) -> &T {
self.as_ref()
}
}
#[repr(C)]
pub struct MutFixed<T> {
ptr: *mut T,
}
unsafe impl<T: Send> Send for MutFixed<T> {}
impl<T> fmt::Debug for MutFixed<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MutFixed {:?}", self.ptr)
}
}
impl<T> MutFixed<T> {
pub fn new(data: T) -> MutFixed<T> {
Self {
ptr: Box::into_raw(Box::new(data)),
}
}
pub fn as_ptr(&self) -> *const T {
self.ptr
}
pub fn as_mut_ptr(&self) -> *mut T {
self.ptr
}
}
impl<T> Deref for MutFixed<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.ptr }
}
}
impl<T> DerefMut for MutFixed<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.ptr }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new() {
let data = 123u32;
let ptr = Fixed::new(data);
assert_eq!(*ptr, data);
}
}