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
use crate::*;
use bindings::Windows::Win32::Com::{CoTaskMemAlloc, CoTaskMemFree};
pub struct Array<T: RuntimeType> {
data: *mut T::DefaultType,
len: u32,
}
impl<T: RuntimeType> Default for Array<T> {
fn default() -> Self {
Array {
data: std::ptr::null_mut(),
len: 0,
}
}
}
impl<T: RuntimeType> Array<T> {
pub fn new() -> Self {
Self::default()
}
pub fn with_len(len: usize) -> Self {
assert!(len < std::u32::MAX as usize);
let bytes_amount = len
.checked_mul(std::mem::size_of::<T>())
.expect("Attempted to allocate too large an Array");
let data = unsafe { CoTaskMemAlloc(bytes_amount) as *mut T::DefaultType };
if data.is_null() {
panic!("Could not successfully allocate for Array");
}
unsafe {
std::ptr::write_bytes(data, 0, len);
}
let len = len as u32;
Self { data, len }
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn len(&self) -> usize {
self.len as usize
}
pub fn clear(&mut self) {
if self.is_empty() {
return;
}
let mut data = std::ptr::null_mut();
let mut len = 0;
std::mem::swap(&mut data, &mut self.data);
std::mem::swap(&mut len, &mut self.len);
unsafe {
std::ptr::drop_in_place(std::slice::from_raw_parts_mut(data, len as usize));
CoTaskMemFree(data as _);
}
}
#[doc(hidden)]
pub fn set_abi_len(&mut self) -> *mut u32 {
&mut self.len
}
#[doc(hidden)]
pub fn set_abi(&mut self) -> *mut *mut T::Abi {
self.clear();
&mut self.data as *mut _ as *mut _
}
#[doc(hidden)]
pub fn into_abi(self) -> (*mut T::Abi, u32) {
let abi = (self.data as *mut _, self.len);
std::mem::forget(self);
abi
}
}
impl<T: RuntimeType> std::ops::Deref for Array<T> {
type Target = [T::DefaultType];
fn deref(&self) -> &[T::DefaultType] {
if self.is_empty() {
return &[];
}
unsafe { std::slice::from_raw_parts(self.data, self.len as usize) }
}
}
impl<T: RuntimeType> std::ops::DerefMut for Array<T> {
fn deref_mut(&mut self) -> &mut [T::DefaultType] {
if self.is_empty() {
return &mut [];
}
unsafe { std::slice::from_raw_parts_mut(self.data, self.len as usize) }
}
}
impl<T: RuntimeType> Drop for Array<T> {
fn drop(&mut self) {
self.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let empty = Array::<bool>::new();
assert!(empty.is_empty());
assert!(empty.len() == 0);
}
#[test]
fn with_len() {
let empty = Array::<u32>::with_len(3);
assert!(!empty.is_empty());
assert!(empty.len() == 3);
assert!(empty[0] == 0);
assert!(empty[1] == 0);
assert!(empty[2] == 0);
}
}