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
use std::{
alloc::{alloc_zeroed, Layout},
convert::{TryFrom, TryInto},
fmt,
fmt::{Debug, Formatter},
ops::{Deref, DerefMut},
};
pub struct Array<T, Len: Copy + Into<usize> + TryFrom<usize>> {
ptr: std::ptr::NonNull<T>,
len: Len,
}
unsafe impl<T: Sync, Len: Copy + Into<usize> + TryFrom<usize>> Sync for Array<T, Len> {}
unsafe impl<T: Send, Len: Copy + Into<usize> + TryFrom<usize>> Send for Array<T, Len> {}
impl<T, Len: Copy + Into<usize> + TryFrom<usize>> Drop for Array<T, Len> {
fn drop(&mut self) {
unsafe {
std::ptr::drop_in_place(&mut self[..]);
Vec::from_raw_parts(self.ptr.as_ptr(), 0, self.len.into());
}
}
}
impl<T, Len: Copy + Into<usize> + TryFrom<usize>> Array<T, Len> {
pub fn zeroed(len: Len) -> Self {
unsafe {
let layout = Layout::array::<T>(len.into()).unwrap();
let ptr = alloc_zeroed(layout).cast::<T>();
Self::from_raw(ptr, len)
}
}
pub fn from_raw(raw: *mut T, len: Len) -> Self {
Self {
ptr: std::ptr::NonNull::new(raw).unwrap(),
len,
}
}
pub fn from_vec(mut v: Vec<T>) -> Self
where
<Len as TryFrom<usize>>::Error: Debug,
{
let len = v.len().try_into().unwrap();
let ptr = v.as_mut_ptr();
std::mem::forget(v);
Self::from_raw(ptr, len)
}
pub fn len(&self) -> usize {
self.len.into()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<T: Clone, Len: Copy + Into<usize> + TryFrom<usize>> Clone for Array<T, Len> {
fn clone(&self) -> Self {
unsafe {
let other = Self::zeroed(self.len);
other
.ptr
.as_ptr()
.copy_from_nonoverlapping(self.ptr.as_ptr(), self.len.into());
other
}
}
}
impl<T, Len: Copy + Into<usize> + TryFrom<usize>> Deref for Array<T, Len> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len.into()) }
}
}
impl<T, Len: Copy + Into<usize> + TryFrom<usize>> DerefMut for Array<T, Len> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len.into()) }
}
}
impl<T: Debug, Len: Copy + Into<usize> + TryFrom<usize>> Debug for Array<T, Len> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self[..], f)
}
}