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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#![allow(unused_macros)]

/// Implements `Default` trait by zeroing all fields.
macro_rules! impl_default {
	($name:ident $(, $life:lifetime)*) => {
		impl<$($life),*> Default for $name<$($life),*> {
			fn default() -> Self {
				unsafe { std::mem::zeroed::<Self>() }
			}
		}
	};
}

/// Implements `Default` trait by zeroing all fields. Also sets the size field
/// to struct size.
macro_rules! impl_default_with_size {
	($name:ident, $field:ident $(, $life:lifetime)*) => {
		impl<$($life),*> Default for $name<$($life),*> {
			fn default() -> Self {
				let mut obj = unsafe { std::mem::zeroed::<Self>() };
				obj.$field = std::mem::size_of::<Self>() as _;
				obj
			}
		}
	};
}

/// Implements `IntUnderlying`, and other needed traits.
macro_rules! impl_intunderlying {
	($name:ident, $ntype:ty) => {
		unsafe impl Send for $name {}

		impl From<$name> for $ntype {
			fn from(v: $name) -> Self {
				v.0
			}
		}

		impl AsRef<$ntype> for $name {
			fn as_ref(&self) -> &$ntype {
				&self.0
			}
		}

		impl crate::prelude::IntUnderlying for $name {
			type Raw = $ntype;

			unsafe fn as_mut(&mut self) -> &mut Self::Raw {
				&mut self.0
			}
		}

		impl $name {
			/// Constructs a new object by wrapping the given integer value.
			///
			/// # Safety
			///
			/// Be sure the given value is meaningful for the actual type.
			#[must_use]
			pub const unsafe fn from_raw(v: $ntype) -> Self {
				Self(v)
			}

			/// Returns the primitive integer underlying value.
			///
			/// This method is similar to [`Into`](std::convert::Into), but it
			/// is `const`, therefore it can be used in
			/// [const contexts](https://doc.rust-lang.org/reference/const_eval.html).
			#[must_use]
			pub const fn raw(&self) -> $ntype {
				self.0
			}
		}
	};
}

/// Implements getter and setter methods for the given `BOOL` field.
macro_rules! pub_fn_bool_get_set {
	($field:ident, $setter:ident) => {
		/// Returns the bool field.
		#[must_use]
		pub const fn $field(&self) -> bool {
			self.$field != 0
		}

		/// Sets the bool field.
		pub fn $setter(&mut self, val: bool) {
			self.$field = val as _
		}
	};
}

/// Implements getter and setter methods for the given resource ID field, stored
/// as `*mut u16`.
macro_rules! pub_fn_resource_id_get_set {
	($field:ident, $setter:ident) => {
		/// Returns the resource ID field.
		#[must_use]
		pub fn $field(&self) -> u16 {
			self.$field as _
		}

		/// Sets the resource ID field.
		pub fn $setter(&mut self, val: u16) {
			self.$field = val as _;
		}
	};
}

/// Implements getter and setter methods for the given `*mut u16` field.
macro_rules! pub_fn_string_ptr_get_set {
	($life:lifetime, $field:ident, $setter:ident) => {
		/// Returns the string field, if any.
		#[must_use]
		pub fn $field(&self) -> Option<String> {
			unsafe { self.$field.as_mut() }.map(|psz| {
				unsafe { WString::from_wchars_nullt(psz) }.to_string()
			})
		}

		/// Sets the string field.
		pub fn $setter(&mut self, buf: Option<&$life mut WString>) {
			self.$field = buf.map_or(
				std::ptr::null_mut(),
				|buf| unsafe { buf.as_mut_ptr() },
			);
		}
	};
}

/// Implements getter and setter methods for the given `*mut u16` and `u32`
/// fields, setting pointer and its actual chars length without terminating
/// null.
macro_rules! pub_fn_string_ptrlen_get_set {
	($life:lifetime, $field:ident, $setter:ident, $length:ident) => {
		/// Returns the string field, if any.
		#[must_use]
		pub fn $field(&self) -> Option<String> {
			unsafe { self.$field.as_mut() }.map(|psz| {
				WString::from_wchars_count(psz, self.$length as _).to_string()
			})
		}

		/// Sets the string field.
		pub fn $setter(&mut self, buf: Option<&$life mut WString>) {
			self.$length = buf.as_ref().map_or(0, |buf| buf.str_len() as _);
			self.$field = buf.map_or(
				std::ptr::null_mut(),
				|buf| unsafe { buf.as_mut_ptr() },
			);
		}
	};
}

/// Implements getter and setter methods for the given `[u16; N]` field.
macro_rules! pub_fn_string_arr_get_set {
	($field:ident, $setter:ident) => {
		/// Returns the string field.
		#[must_use]
		pub fn $field(&self) -> String {
			crate::kernel::decl::WString::from_wchars_slice(&self.$field).to_string()
		}

		/// Sets the string field.
		pub fn $setter(&mut self, text: &str) {
			crate::kernel::decl::WString::from_str(text).copy_to_slice(&mut self.$field);
		}
	};
}

/// Implements getter and setter methods for the given `*mut u16` and `i32`
/// fields, setting buffer and its size.
macro_rules! pub_fn_string_buf_get_set {
	($life:lifetime, $field:ident, $setter:ident, $raw:ident, $cch:ident) => {
		/// Returns the raw pointer to the string field, and its declared size.
		///
		/// This method can be used as an escape hatch to interoperate with
		/// other libraries.
		#[must_use]
		pub const fn $raw(&self) -> (*mut u16, i32) {
			(self.$field, self.$cch as _) // some u32 and usize exist
		}

		/// Returns the string field.
		#[must_use]
		pub fn $field(&self) -> Option<String> {
			unsafe { self.$field.as_mut() }.map(|psz| {
				unsafe { WString::from_wchars_nullt(psz) }.to_string()
			})
		}

		/// Sets the string field.
		pub fn $setter(&mut self, buf: Option<&$life mut WString>) {
			self.$cch = buf.as_ref().map_or(0, |buf| buf.buf_len() as _);
			self.$field = buf.map_or(std::ptr::null_mut(), |buf| {
				if buf.is_allocated() {
					unsafe { buf.as_mut_ptr() }
				} else {
					std::ptr::null_mut()
				}
			});
		}
	};
}

/// Implements getter and setter methods for the given pointer field.
macro_rules! pub_fn_ptr_get_set {
	($life:lifetime, $field:ident, $setter:ident, $ty:ty) => {
		/// Returns the pointer field.
		#[must_use]
		pub fn $field(&self) -> Option<&$life mut $ty> {
			unsafe { self.$field.as_mut() }
		}

		/// Sets the pointer field.
		pub fn $setter(&mut self, obj: Option<&$life mut $ty>) {
			self.$field = obj.map_or(std::ptr::null_mut(), |obj| obj);
		}
	};
}

/// Implements getter and setter methods for the given array + size fields,
/// setting buffer and its size.
macro_rules! pub_fn_array_buf_get_set {
	($life:lifetime, $field:ident, $setter:ident, $cch:ident, $ty:ty) => {
		/// Returns the array field.
		#[must_use]
		pub fn $field(&self) -> Option<&$life mut [$ty]> {
			unsafe {
				self.$field.as_mut().map(|p| {
					std::slice::from_raw_parts_mut(p, self.$cch as _)
				})
			}
		}

		/// Sets the array field.
		pub fn $setter(&mut self, buf: Option<&$life mut [$ty]>) {
			match buf {
				Some(buf) => {
					self.$field = buf as *mut _ as _;
					self.$cch = buf.len() as _;
				},
				None => {
					self.$field = std::ptr::null_mut();
					self.$cch = 0;
				},
			}
		}
	};
}

/// Implements getter and setter methods for the given `COMPTR` field.
macro_rules! pub_fn_comptr_get_set {
	($field:ident, $setter:ident, $trait:ident) => {
		/// Returns the COM object field, by cloning the underlying COM pointer.
		#[must_use]
		pub fn $field<T>(&self) -> Option<T>
			where T: $trait,
		{
			if self.$field.is_null() {
				None
			} else {
				let obj = std::mem::ManuallyDrop::new( // won't release the stored pointer
					unsafe { T::from_ptr(self.$field) },
				);
				let cloned = T::clone(&obj); // the cloned will release the stored pointer
				Some(cloned)
			}
		}

		/// Sets the COM object field, by cloning the underlying COM pointer.
		pub fn $setter<T>(&mut self, obj: Option<&T>)
			where T: $trait,
		{
			let _ = unsafe { T::from_ptr(self.$field) }; // if already set, call Release() immediately
			self.$field = match obj {
				Some(obj) => {
					let mut cloned = T::clone(obj);
					cloned.leak() // so the cloned pointer won't be released here
				},
				None => std::ptr::null_mut(),
			};
		}
	};
}

/// Implements `Drop` for a struct with one `COMPTR` field.
macro_rules! impl_drop_comptr {
	($field:ident, $name:ident $(, $life:lifetime)*) => {
		impl<$($life),*> Drop for $name<$($life),*> {
			fn drop(&mut self) {
				if !self.$field.is_null() {
					let _ = unsafe {
						<crate::IUnknown as crate::prelude::ole_IUnknown>
							::from_ptr(self.$field) // if pointer is present, call Release() on it
					};
				}
			}
		}
	};
}

/// Implements accessor methods over `pmem` and `sz` fields of an allocated
/// memory block.
macro_rules! pub_fn_mem_block {
	() => {
		/// Returns a pointer to the allocated memory block, or null if not
		/// allocated.
		#[must_use]
		pub const fn as_ptr(&self) -> *const std::ffi::c_void {
			self.pmem
		}

		/// Returns a mutable pointer to the allocated memory block, or null if
		/// not allocated.
		#[must_use]
		pub fn as_mut_ptr(&mut self) -> *mut std::ffi::c_void {
			self.pmem
		}

		/// Returns a slice over the allocated memory block.
		#[must_use]
		pub const fn as_slice(&self) -> &[u8] {
			unsafe { std::slice::from_raw_parts(self.pmem as _, self.sz) }
		}

		/// Returns a mutable slice over the allocated memory block.
		#[must_use]
		pub fn as_mut_slice(&mut self) -> &mut [u8] {
			unsafe { std::slice::from_raw_parts_mut(self.pmem as _, self.sz) }
		}

		/// Returns a slice over the allocated memory block, aligned to the given
		/// type.
		///
		/// # Safety
		///
		/// Make sure the alignment is correct.
		#[must_use]
		pub const unsafe fn as_slice_aligned<T>(&self) -> &[T] {
			std::slice::from_raw_parts(
				self.pmem as _,
				self.sz / std::mem::size_of::<T>(),
			)
		}

		/// Returns a mutable slice over the allocated memory block, aligned to the
		/// given type.
		///
		/// # Safety
		///
		/// Make sure the alignment is correct.
		#[must_use]
		pub unsafe fn as_mut_slice_aligned<T>(&mut self) -> &mut [T] {
			std::slice::from_raw_parts_mut(
				self.pmem as _,
				self.sz / std::mem::size_of::<T>(),
			)
		}

		/// Returns the size of the allocated memory block.
		#[must_use]
		pub const fn len(&self) -> usize {
			self.sz
		}
	};
}