Debian Codegraph @

third_party/rust/windows-core/src/array.rs

raw
1 use super::*;
2
3 /// A WinRT array stores elements contiguously in a heap-allocated buffer.
4 pub struct Array<T: Type<T>> {
5 data: *mut T::Default,
6 len: u32,
7 }
8
9 impl<T: Type<T>> Default for Array<T> {
10 fn default() -> Self {
11 Array {
12 data: core::ptr::null_mut(),
13 len: 0,
14 }
15 }
16 }
17
18 impl<T: Type<T>> Array<T> {
19 /// Creates an empty array.
20 pub fn new() -> Self {
21 Self::default()
22 }
23
24 /// Creates an array of the given length with default values.
25 pub fn with_len(len: usize) -> Self {
26 assert!(len < u32::MAX as usize);
27 let bytes_amount = len
28 .checked_mul(core::mem::size_of::<T>())
29 .expect("Attempted to allocate too large an Array");
30
31 // WinRT arrays must be allocated with CoTaskMemAlloc.
32 // SAFETY: the call to CoTaskMemAlloc is safe to perform
33 // if len is zero and overflow was checked above.
34 // We ensured we alloc enough space by multiplying len * size_of::<T>
35 let data = unsafe { imp::CoTaskMemAlloc(bytes_amount) as *mut T::Default };
36
37 assert!(!data.is_null(), "Could not successfully allocate for Array");
38
39 // SAFETY: It is by definition safe to zero-initialize WinRT types.
40 // `write_bytes` will write 0 to (len * size_of::<T>())
41 // bytes making the entire array zero initialized. We have assured
42 // above that the data ptr is not null.
43 unsafe {
44 core::ptr::write_bytes(data, 0, len);
45 }
46
47 let len = len as u32;
48 Self { data, len }
49 }
50
51 /// Creates an array by copying the elements from the slice.
52 pub fn from_slice(values: &[T::Default]) -> Self
53 where
54 T::Default: Clone,
55 {
56 let mut array = Self::with_len(values.len());
57 array.clone_from_slice(values);
58 array
59 }
60
61 /// Creates an array from a pointer and length. The `len` argument is the number of elements, not the number of bytes.
62 /// # Safety
63 /// The `data` argument must have been allocated with `CoTaskMemAlloc`.
64 pub unsafe fn from_raw_parts(data: *mut T::Default, len: u32) -> Self {
65 Self { data, len }
66 }
67
68 /// Returns a slice containing the entire array.
69 pub fn as_slice(&self) -> &[T::Default] {
70 self
71 }
72
73 /// Returns `true` if the array is empty.
74 pub fn is_empty(&self) -> bool {
75 self.len == 0
76 }
77
78 /// Returns the length of the array.
79 pub fn len(&self) -> usize {
80 self.len as usize
81 }
82
83 /// Clears the contents of the array.
84 pub fn clear(&mut self) {
85 if self.is_empty() {
86 return;
87 }
88
89 let mut data = core::ptr::null_mut();
90 let mut len = 0;
91
92 core::mem::swap(&mut data, &mut self.data);
93 core::mem::swap(&mut len, &mut self.len);
94
95 // SAFETY: At this point, self has been reset to zero so any panics in T's destructor would
96 // only leak data not leave the array in bad state.
97 unsafe {
98 // Call the destructors of all the elements of the old array
99 // SAFETY: the slice cannot be used after the call to `drop_in_place`
100 core::ptr::drop_in_place(core::slice::from_raw_parts_mut(data, len as usize));
101 // Free the data memory where the elements were
102 // SAFETY: we have unique access to the data pointer at this point
103 // so freeing it is the right thing to do
104 imp::CoTaskMemFree(data as _);
105 }
106 }
107
108 #[doc(hidden)]
109 /// Get a mutable pointer to the array's length
110 ///
111 /// # Safety
112 ///
113 /// This function is safe but writing to the pointer is not. Calling this without
114 /// a subsequent call to `set_abi` is likely to either leak memory or cause UB
115 pub unsafe fn set_abi_len(&mut self) -> *mut u32 {
116 &mut self.len
117 }
118
119 #[doc(hidden)]
120 /// Turn the array into a pointer to its data and its length
121 pub fn into_abi(self) -> (*mut T::Abi, u32) {
122 let abi = (self.data as *mut _, self.len);
123 core::mem::forget(self);
124 abi
125 }
126 }
127
128 impl<T: Type<T>> core::ops::Deref for Array<T> {
129 type Target = [T::Default];
130
131 fn deref(&self) -> &[T::Default] {
132 if self.is_empty() {
133 return &[];
134 }
135
136 // SAFETY: data must not be null if the array is not empty
137 unsafe { core::slice::from_raw_parts(self.data, self.len as usize) }
138 }
139 }
140
141 impl<T: Type<T>> core::ops::DerefMut for Array<T> {
142 fn deref_mut(&mut self) -> &mut [T::Default] {
143 if self.is_empty() {
144 return &mut [];
145 }
146
147 // SAFETY: data must not be null if the array is not empty
148 unsafe { core::slice::from_raw_parts_mut(self.data, self.len as usize) }
149 }
150 }
151
152 impl<T: Type<T>> Drop for Array<T> {
153 fn drop(&mut self) {
154 self.clear();
155 }
156 }
157
158 #[doc(hidden)]
159 pub struct ArrayProxy<T: Type<T>> {
160 data: *mut *mut T::Default,
161 len: *mut u32,
162 temp: core::mem::ManuallyDrop<Array<T>>,
163 }
164
165 impl<T: Type<T>> ArrayProxy<T> {
166 pub fn from_raw_parts(data: *mut *mut T::Default, len: *mut u32) -> Self {
167 Self {
168 data,
169 len,
170 temp: core::mem::ManuallyDrop::new(Array::new()),
171 }
172 }
173
174 pub fn as_array(&mut self) -> &mut Array<T> {
175 &mut self.temp
176 }
177 }
178
179 impl<T: Type<T>> Drop for ArrayProxy<T> {
180 fn drop(&mut self) {
181 unsafe {
182 *self.data = self.temp.data;
183 *self.len = self.temp.len;
184 }
185 }
186 }