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
#![allow(non_camel_case_types, non_snake_case)]

use std::marker::PhantomData;

use crate::co;
use crate::decl::*;
use crate::guard::*;
use crate::kernel::ffi_types::*;
use crate::prelude::*;

/// [`COAUTHIDENTITY`](https://learn.microsoft.com/en-us/windows/win32/api/wtypesbase/ns-wtypesbase-coauthidentity)
/// struct.
#[repr(C)]
pub struct COAUTHIDENTITY<'a, 'b, 'c> {
	User: *mut u16,
	UserLength: u32,
	Domain: *mut u16,
	DomainLength: u32,
	Password: *mut u16,
	PasswordLength: u32,
	pub Flags: co::SEC_WINNT_AUTH_IDENTITY,

	_User: PhantomData<&'a mut u16>,
	_Domain: PhantomData<&'b mut u16>,
	_Password: PhantomData<&'c mut u16>,
}

impl_default!(COAUTHIDENTITY, 'a, 'b, 'c);

impl<'a, 'b, 'c> COAUTHIDENTITY<'a, 'b, 'c> {
	pub_fn_string_ptrlen_get_set!('a, User, set_User, UserLength);
	pub_fn_string_ptrlen_get_set!('b, Domain, set_Domain, DomainLength);
	pub_fn_string_ptrlen_get_set!('c, Password, set_Password, PasswordLength);
}

/// [`COAUTHINFO`](https://learn.microsoft.com/en-us/windows/win32/api/wtypesbase/ns-wtypesbase-coauthinfo)
/// struct.
#[repr(C)]
pub struct COAUTHINFO<'a, 'b, 'c, 'd, 'e> {
	pub dwAuthnSvc: co::RPC_C_AUTHN,
	pub dwAuthzSvc: co::RPC_C_AUTHZ,
	pwszServerPrincName: *mut u16,
	pub dwAuthnLevel: co::RPC_C_AUTHN,
	pub dwImpersonationLevel: co::RPC_C_IMP_LEVEL,
	pAuthIdentityData: *mut COAUTHIDENTITY<'c, 'd, 'e>,
	pub dwCapabilities: co::RPC_C_QOS_CAPABILITIES,

	_pwszServerPrincName: PhantomData<&'a mut u16>,
	_pAuthIdentityData: PhantomData<&'b mut COAUTHIDENTITY<'c, 'd, 'e>>,
}

impl_default!(COAUTHINFO, 'a, 'b, 'c, 'd, 'e);

impl<'a, 'b, 'c, 'd, 'e> COAUTHINFO<'a, 'b, 'c, 'd, 'e> {
	pub_fn_string_ptr_get_set!('a, pwszServerPrincName, set_pwszServerPrincName);
	pub_fn_ptr_get_set!('b, pAuthIdentityData, set_pAuthIdentityData, COAUTHIDENTITY<'c, 'd, 'e>);
}

/// [`COSERVERINFO`](https://learn.microsoft.com/en-us/windows/win32/api/objidl/ns-objidl-coserverinfo)
/// struct.
#[repr(C)]
pub struct COSERVERINFO<'a, 'b, 'c, 'd, 'e, 'f, 'g> {
	dwReserved1: u32,
	pwszName: *mut u16,
	pAuthInfo: *mut COAUTHINFO<'c, 'd, 'e, 'f, 'g>,
	dwReserved2: u32,

	_pwszName: PhantomData<&'a mut u16>,
	_pAuthInfo: PhantomData<&'b COAUTHINFO<'c, 'd, 'e, 'f, 'g>>,
}

impl_default!(COSERVERINFO, 'a, 'b, 'c, 'd, 'e, 'f, 'g);

impl<'a, 'b, 'c, 'd, 'e, 'f, 'g> COSERVERINFO<'a, 'b, 'c, 'd, 'e, 'f, 'g> {
	pub_fn_string_ptr_get_set!('a, pwszName, set_pwszName);
	pub_fn_ptr_get_set!('b, pAuthInfo, set_pAuthInfo, COAUTHINFO<'c, 'd, 'e, 'f, 'g>);
}

/// [`FORMATETC`](https://learn.microsoft.com/en-us/windows/win32/api/objidl/ns-objidl-formatetc)
/// struct.
///
/// The [`Default`] trait automatically initializes `lindex` to `-1`.
#[repr(C)]
pub struct FORMATETC<'a> {
	cfFormat: u16,
	ptd: *mut DVTARGETDEVICE,
	pub dwAspect: u32,
	pub lindex: i32,
	pub tymed: co::TYMED,

	_ptd: PhantomData<&'a mut DVTARGETDEVICE>,
}

impl<'a> Default for FORMATETC<'a> {
	fn default() -> Self {
		Self {
			cfFormat: 0,
			ptd: std::ptr::null_mut(),
			dwAspect: 0,
			lindex: -1,
			tymed: co::TYMED::default(),
			_ptd: PhantomData,
		}
	}
}

impl<'a> FORMATETC<'a> {
	/// Returns the `cfFormat` field.
	#[must_use]
	pub fn cfFormat(&self) -> co::CF {
		unsafe { co::CF::from_raw(self.cfFormat as _) }
	}

	/// Sets the `cfFormat` field.
	pub fn set_cfFormat(&mut self, val: co::CF) {
		self.cfFormat = val.raw() as _;
	}

	pub_fn_ptr_get_set!('a, ptd, set_ptd, DVTARGETDEVICE);
}

/// [`DVTARGETDEVICE`](https://learn.microsoft.com/en-us/windows/win32/api/objidl/ns-objidl-dvtargetdevice)
/// struct.
#[repr(C)]
#[derive(Default)]
pub struct DVTARGETDEVICE {
	pub tdSize: u32,
	pub tdDriverNameOffset: u16,
	pub tdDeviceNameOffset: u16,
	pub tdPortNameOffset: u16,
	pub tdExtDevmodeOffset: u16,
	pub tdData: [u8; 1],
}

impl VariableSized for DVTARGETDEVICE {}

/// [`MULTI_QI`](https://learn.microsoft.com/en-us/windows/win32/api/objidl/ns-objidl-multi_qi)
/// struct.
#[repr(C)]
pub struct MULTI_QI<'a> {
	pIID: *mut co::IID,
	pItf: COMPTR,
	pub hr: co::HRESULT,

	_pIID: PhantomData<&'a mut co::IID>,
}

impl_default!(MULTI_QI, 'a);
impl_drop_comptr!(pItf, MULTI_QI, 'a);

impl<'a> MULTI_QI<'a> {
	pub_fn_ptr_get_set!('a, pIID, set_pIID, co::IID);
	pub_fn_comptr_get_set!(pItf, set_pItf, ole_IUnknown);
}

/// [`SNB`](https://learn.microsoft.com/en-us/windows/win32/stg/snb)
/// struct.
#[repr(transparent)]
pub struct SNB(*mut *mut u16);

impl_default!(SNB);

impl Drop for SNB {
	fn drop(&mut self) {
		let _ = unsafe { CoTaskMemFreeGuard::new(self.0 as _, 0) }; // size is irrelevant
	}
}

impl SNB {
	/// Creates a new `SNB` by allocating a contiguous memory block for pointers
	/// and strings.
	#[must_use]
	pub fn new(strs: &[impl AsRef<str>]) -> HrResult<Self> {
		if strs.is_empty() {
			return Ok(Self::default());
		}

		let tot_bytes_ptrs = (strs.len() + 1) * std::mem::size_of::<*mut u16>(); // plus null

		let wstrs = WString::from_str_vec(strs);
		let num_valid_chars = wstrs.as_slice() // count just the chars; important because stack alloc has zero fills
			.iter()
			.filter(|ch| **ch != 0x0000)
			.count();
		let tot_bytes_wstrs = ( num_valid_chars + strs.len() ) // plus one null for each string
			* std::mem::size_of::<u16>();

		let mut block = CoTaskMemAlloc(tot_bytes_ptrs + tot_bytes_wstrs)?; // alloc block for pointers and strings
		let ptr_block = block.as_mut_ptr() as *mut u8;
		let ptr_block_wstrs = unsafe { ptr_block.add(tot_bytes_ptrs) } as *mut u16; // start of strings block

		let mut idx_cur_wstr = 0; // current string to be copied to block
		*unsafe { block.as_mut_slice_aligned::<*mut u16>() }
			.get_mut(idx_cur_wstr).unwrap() = ptr_block_wstrs; // copy pointer to 1st string
		idx_cur_wstr += 1;

		wstrs.as_slice()
			.iter()
			.enumerate()
			.for_each(|(idx, ch)| {
				if *ch == 0x0000 && idx_cur_wstr < strs.len() {
					unsafe {
						*block.as_mut_slice_aligned::<*mut u16>() // copy pointer to subsequent strings in the block
							.get_mut(idx_cur_wstr).unwrap() = ptr_block_wstrs.add(idx + 1);
					}
					idx_cur_wstr += 1;
				}
			});

		*unsafe { block.as_mut_slice_aligned::<*mut u16>() }
			.get_mut(idx_cur_wstr).unwrap() = std::ptr::null_mut(); // null pointer after string pointers

		wstrs.copy_to_slice( // beyond pointers, copy each null-terminated string sequentially
			unsafe {
				std::slice::from_raw_parts_mut(
					ptr_block_wstrs,
					tot_bytes_wstrs / std::mem::size_of::<u16>(),
				)
			},
		);

		let (ptr, _) = block.leak();
		Ok(Self(ptr as _))
	}

	/// Returns the underlying pointer.
	#[must_use]
	pub const fn as_ptr(&self) -> *mut *mut u16 {
		self.0
	}

	/// Converts the internal UTF-16 blocks into strings.
	#[must_use]
	pub fn to_strings(&self) -> Vec<String> {
		let mut vec = Vec::<String>::new();
		if !self.0.is_null() {
			let mut idx_ptr = 0;
			loop {
				let ptr_ws = unsafe {
					let sli_ptrs = std::slice::from_raw_parts(self.0, idx_ptr + 1);
					*sli_ptrs.get_unchecked(idx_ptr) // get nth pointer to string
				};
				if ptr_ws.is_null() { // a null pointer means the end of pointers block
					break;
				}
				let ws = unsafe { WString::from_wchars_nullt(ptr_ws) };
				vec.push(ws.to_string());
				idx_ptr += 1;
			}
		}
		vec
	}
}