winsafe 0.0.27

Windows API and GUI in safe, idiomatic Rust.
Documentation
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
#![allow(non_snake_case)]

use crate::co;
use crate::decl::*;
use crate::guard::*;
use crate::kernel::{ffi, privs::*};

/// [`AttachConsole`](https://learn.microsoft.com/en-us/windows/console/attachconsole)
/// function.
pub fn AttachConsole(process: PidParent) -> SysResult<()> {
	BoolRet(unsafe { ffi::AttachConsole(process.as_u32()) }).to_sysresult()
}

/// [`CopyFile`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfilew)
/// function.
///
/// # Related functions
///
/// * [`DeleteFile`](crate::DeleteFile)
/// * [`MoveFile`](crate::MoveFile)
/// * [`MoveFileEx`](crate::MoveFileEx)
/// * [`ReplaceFile`](crate::ReplaceFile)
pub fn CopyFile(existing_file: &str, new_file: &str, fail_if_exists: bool) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::CopyFileW(
			WString::from_str(existing_file).as_ptr(),
			WString::from_str(new_file).as_ptr(),
			fail_if_exists as _,
		)
	})
	.to_sysresult()
}

/// [`CreateDirectory`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectoryw)
/// function.
pub fn CreateDirectory(
	path_name: &str,
	security_attributes: Option<&SECURITY_ATTRIBUTES>,
) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::CreateDirectoryW(
			WString::from_str(path_name).as_ptr(),
			security_attributes.map_or(std::ptr::null_mut(), |sa| pcvoid(sa)),
		)
	})
	.to_sysresult()
}

/// [`CreateProcess`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw)
/// function.
#[must_use]
pub fn CreateProcess(
	application_name: Option<&str>,
	command_line: Option<&str>,
	process_attrs: Option<&SECURITY_ATTRIBUTES>,
	thread_attrs: Option<&SECURITY_ATTRIBUTES>,
	inherit_handles: bool,
	creation_flags: co::CREATE,
	environment_vars: &[(&str, &str)],
	current_dir: Option<&str>,
	si: &mut STARTUPINFO,
) -> SysResult<CloseHandlePiGuard> {
	let mut buf_cmd_line = WString::from_opt_str(command_line);
	let mut pi = PROCESS_INFORMATION::default();

	let mut _env_buf = WString::new();
	let env_ptr = if environment_vars.is_empty() {
		std::ptr::null_mut()
	} else {
		let env_buf = WString::from_str_vec(
			&environment_vars
				.iter()
				.map(|(name, val)| format!("{}={}", name, val))
				.collect::<Vec<_>>(),
		);
		env_buf.as_ptr() as _
	};

	unsafe {
		BoolRet(ffi::CreateProcessW(
			WString::from_opt_str(application_name).as_ptr(),
			buf_cmd_line.as_mut_ptr(),
			pcvoid_or_null(process_attrs),
			pcvoid_or_null(thread_attrs),
			inherit_handles as _,
			(creation_flags | co::CREATE::UNICODE_ENVIRONMENT).raw(), // environment is always UTF-16
			env_ptr,
			WString::from_opt_str(current_dir).as_ptr(),
			pvoid(si),
			pvoid(&mut pi),
		))
		.to_sysresult()
		.map(|_| CloseHandlePiGuard::new(pi))
	}
}

/// [`DeleteFile`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-deletefilew)
/// function.
///
/// # Related functions
///
/// * [`CopyFile`](crate::CopyFile)
/// * [`MoveFile`](crate::MoveFile)
/// * [`MoveFileEx`](crate::MoveFileEx)
/// * [`ReplaceFile`](crate::ReplaceFile)
pub fn DeleteFile(file_name: &str) -> SysResult<()> {
	BoolRet(unsafe { ffi::DeleteFileW(WString::from_str(file_name).as_ptr()) }).to_sysresult()
}

/// [`ExitProcess`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitprocess)
/// function.
pub fn ExitProcess(exit_code: u32) {
	unsafe { ffi::ExitProcess(exit_code) }
}

/// [`ExitThread`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitthread)
/// function.
pub fn ExitThread(exit_code: u32) {
	unsafe { ffi::ExitThread(exit_code) }
}

/// [`ExpandEnvironmentStrings`](https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-expandenvironmentstringsw)
/// function.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let expanded = w::ExpandEnvironmentStrings(
///     "Os %OS%, home %HOMEPATH% and temp %TEMP%",
/// )?;
///
/// println!("{}", expanded);
/// # w::SysResult::Ok(())
/// ```
#[must_use]
pub fn ExpandEnvironmentStrings(src: &str) -> SysResult<String> {
	let wsrc = WString::from_str(src);
	let mut buf_sz =
		match unsafe { ffi::ExpandEnvironmentStringsW(wsrc.as_ptr(), std::ptr::null_mut(), 0) } {
			0 => return Err(GetLastError()),
			n => n,
		}; // includes terminating null count

	loop {
		let mut buf = WString::new_alloc_buf(buf_sz as _);
		let required_sz = match unsafe {
			ffi::ExpandEnvironmentStringsW(wsrc.as_ptr(), buf.as_mut_ptr(), buf_sz)
		} {
			0 => return Err(GetLastError()),
			n => n,
		}; // plus terminating null count

		if required_sz <= buf_sz {
			return Ok(buf.to_string());
		}

		buf_sz = required_sz; // includes terminating null count; set the new buffer size to try again
	}
}

/// [`FileTimeToSystemTime`](https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-filetimetosystemtime)
/// function.
///
/// Note that the system time is UTC. In order to convert to local time, you
/// must also pass the returned `SYSTEMTIME` to
/// [`SystemTimeToTzSpecificLocalTime`](crate::SystemTimeToTzSpecificLocalTime).
///
/// # Related functions
///
/// * [`GetLocalTime`](crate::GetLocalTime)
/// * [`GetSystemTime`](crate::GetSystemTime)
/// * [`SystemTimeToFileTime`](crate::SystemTimeToFileTime)
/// * [`SystemTimeToTzSpecificLocalTime`](crate::SystemTimeToTzSpecificLocalTime)
#[must_use]
pub fn FileTimeToSystemTime(ft: &FILETIME) -> SysResult<SYSTEMTIME> {
	let mut st = SYSTEMTIME::default();
	BoolRet(unsafe { ffi::FileTimeToSystemTime(pcvoid(ft), pvoid(&mut st)) })
		.to_sysresult()
		.map(|_| st)
}

/// [`FlushProcessWriteBuffers`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-flushprocesswritebuffers)
/// function.
pub fn FlushProcessWriteBuffers() {
	unsafe { ffi::FlushProcessWriteBuffers() }
}

/// [`FormatMessage`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessagew)
/// function.
///
/// You don't need to call this function: all error types implement the
/// [`SystemError`](crate::prelude::SystemError) trait which will automatically
/// call `FormatMessage`.
///
/// # Safety
///
/// Incorrect usage of the flags and formatting string may lead to memory
/// corruption.
#[must_use]
pub unsafe fn FormatMessage(
	flags: co::FORMAT_MESSAGE,
	source: Option<*mut std::ffi::c_void>,
	message_id: u32,
	lang_id: LANGID,
	args: &[*mut std::ffi::c_void],
) -> SysResult<String> {
	let mut ptr_buf = std::ptr::null_mut::<u16>();

	let nchars = match unsafe {
		ffi::FormatMessageW(
			flags.raw(),
			source.unwrap_or(std::ptr::null_mut()),
			message_id,
			u16::from(lang_id) as _,
			&mut ptr_buf as *mut *mut _ as _, // pass pointer to pointer
			0,
			vec_ptr(args) as _,
		)
	} as _
	{
		0 => Err(GetLastError()),
		nchars => Ok(nchars),
	}?;

	let final_wstr = WString::from_wchars_count(ptr_buf, nchars as _);
	let _ = unsafe { LocalFreeGuard::new(HLOCAL::from_ptr(ptr_buf as _)) }; // free returned pointer
	Ok(final_wstr.to_string())
}

/// [`GetBinaryType`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getbinarytypew)
/// function.
#[must_use]
pub fn GetBinaryType(application_name: &str) -> SysResult<co::SCS> {
	let mut binary_type = co::SCS::default();
	BoolRet(unsafe {
		ffi::GetBinaryTypeW(WString::from_str(application_name).as_ptr(), binary_type.as_mut())
	})
	.to_sysresult()
	.map(|_| binary_type)
}

/// [`GetCommandLine`](https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getcommandlinew)
/// function.
///
/// For an example, see [`CommandLineToArgv`](crate::CommandLineToArgv).
#[must_use]
pub fn GetCommandLine() -> String {
	unsafe { WString::from_wchars_nullt(ffi::GetCommandLineW()) }.to_string()
}

/// [`GetComputerName`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcomputernamew)
/// function.
#[must_use]
pub fn GetComputerName() -> SysResult<String> {
	let mut buf = WString::new_alloc_buf(MAX_COMPUTERNAME_LENGTH + 1);
	let mut sz = buf.buf_len() as u32;

	BoolRet(unsafe { ffi::GetComputerNameW(buf.as_mut_ptr(), &mut sz) })
		.to_sysresult()
		.map(|_| buf.to_string())
}

/// [`GetCurrentDirectory`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcurrentdirectory)
/// function.
#[must_use]
pub fn GetCurrentDirectory() -> SysResult<String> {
	let mut buf_sz = match unsafe { ffi::GetCurrentDirectoryW(0, std::ptr::null_mut()) } {
		0 => return Err(GetLastError()),
		n => n,
	}; // includes terminating null count

	loop {
		let mut buf = WString::new_alloc_buf(buf_sz as _);
		let returned_chars = match unsafe { ffi::GetCurrentDirectoryW(buf_sz, buf.as_mut_ptr()) } {
			0 => return Err(GetLastError()),
			n => n,
		};

		if returned_chars < buf_sz {
			return Ok(buf.to_string());
		}

		buf_sz = returned_chars; // includes terminating null count; set the new buffer size to try again
	}
}

/// [`GetCurrentProcessId`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessid)
/// function.
#[must_use]
pub fn GetCurrentProcessId() -> u32 {
	unsafe { ffi::GetCurrentProcessId() }
}

/// [`GetCurrentThreadId`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthreadid)
/// function.
#[must_use]
pub fn GetCurrentThreadId() -> u32 {
	unsafe { ffi::GetCurrentThreadId() }
}

/// [`GetDriveType`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdrivetypew)
/// function.
#[must_use]
pub fn GetDriveType(root_path_name: Option<&str>) -> co::DRIVE {
	unsafe {
		co::DRIVE::from_raw(ffi::GetDriveTypeW(WString::from_opt_str(root_path_name).as_ptr()))
	}
}

/// [`GetDiskFreeSpaceEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)
/// function.
pub fn GetDiskFreeSpaceEx(
	directory_name: Option<&str>,
	free_bytes_available_to_caller: Option<&mut u64>,
	total_number_of_bytes: Option<&mut u64>,
	total_number_of_free_bytes: Option<&mut u64>,
) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::GetDiskFreeSpaceExW(
			WString::from_opt_str(directory_name).as_ptr(),
			free_bytes_available_to_caller.map_or(std::ptr::null_mut(), |n| n),
			total_number_of_bytes.map_or(std::ptr::null_mut(), |n| n),
			total_number_of_free_bytes.map_or(std::ptr::null_mut(), |n| n),
		)
	})
	.to_sysresult()
}

/// [`GetDiskSpaceInformation`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskspaceinformationw)
/// function.
#[must_use]
pub fn GetDiskSpaceInformation(root_path: &str) -> SysResult<DISK_SPACE_INFORMATION> {
	let mut disk_space_info = DISK_SPACE_INFORMATION::default();
	match unsafe {
		co::ERROR::from_raw(ffi::GetDiskSpaceInformationW(
			WString::from_str(root_path).as_ptr(),
			pvoid(&mut disk_space_info),
		))
	} {
		co::ERROR::SUCCESS | co::ERROR::MORE_DATA => Ok(disk_space_info),
		err => Err(err),
	}
}

/// [`GetEnvironmentStrings`](https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getenvironmentstringsw)
/// function.
///
/// Returns the parsed strings, and automatically frees the retrieved
/// environment block with
/// [`FreeEnvironmentStrings`](https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-freeenvironmentstringsw).
///
/// # Examples
///
/// Retrieving and printing the key/value pairs of all environment strings:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let env_vars = w::GetEnvironmentStrings()?;
/// for (k, v) in env_vars.iter() {
///     println!("{} = {}", k, v);
/// }
/// # w::SysResult::Ok(())
/// ```
#[must_use]
pub fn GetEnvironmentStrings() -> SysResult<Vec<(String, String)>> {
	PtrRet(unsafe { ffi::GetEnvironmentStringsW() } as _)
		.to_sysresult()
		.map(|ptr| {
			let vec_entries = unsafe { parse_multi_z_str(ptr as _, None) };
			unsafe {
				ffi::FreeEnvironmentStringsW(ptr);
			}
			vec_entries
				.iter()
				.map(|env_str| {
					let mut pair = env_str.split("="); // assumes correctly formatted pairs
					let key = pair.next().unwrap();
					let val = pair.next().unwrap();
					(key.to_owned(), val.to_owned())
				})
				.collect()
		})
}

/// [`GetFileAttributes`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileattributesw)
/// function.
///
/// # Examples
///
/// Checking whether a file or folder exists:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let file_exists = w::GetFileAttributes("C:\\Temp\\test.txt").is_ok();
/// ```
///
/// Retrieving various information about a file or folder path:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*, co};
///
/// let flags = w::GetFileAttributes("C:\\Temp\\test.txt")?;
///
/// let is_compressed = flags.has(co::FILE_ATTRIBUTE::COMPRESSED);
/// let is_directory  = flags.has(co::FILE_ATTRIBUTE::DIRECTORY);
/// let is_encrypted  = flags.has(co::FILE_ATTRIBUTE::ENCRYPTED);
/// let is_hidden     = flags.has(co::FILE_ATTRIBUTE::HIDDEN);
/// let is_temporary  = flags.has(co::FILE_ATTRIBUTE::TEMPORARY);
/// # w::SysResult::Ok(())
/// ```
#[must_use]
pub fn GetFileAttributes(file_name: &str) -> SysResult<co::FILE_ATTRIBUTE> {
	const INVALID: u32 = INVALID_FILE_ATTRIBUTES as u32;
	match unsafe { ffi::GetFileAttributesW(WString::from_str(file_name).as_ptr()) } {
		INVALID => Err(GetLastError()),
		flags => Ok(unsafe { co::FILE_ATTRIBUTE::from_raw(flags) }),
	}
}

/// [`GetFileAttributesEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileattributesexw)
/// function.
///
/// This function uses `GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard` flag,
/// which is the only available flag.
pub fn GetFileAttributesEx(file: &str) -> SysResult<WIN32_FILE_ATTRIBUTE_DATA> {
	let mut wfad = WIN32_FILE_ATTRIBUTE_DATA::default();
	BoolRet(unsafe {
		ffi::GetFileAttributesExW(WString::from_str(file).as_ptr(), 0, pvoid(&mut wfad))
	})
	.to_sysresult()
	.map(|_| wfad)
}

/// [`GetFirmwareType`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfirmwaretype)
/// function.
#[must_use]
pub fn GetFirmwareType() -> SysResult<co::FIRMWARE_TYPE> {
	let mut ft = co::FIRMWARE_TYPE::default();
	BoolRet(unsafe { ffi::GetFirmwareType(ft.as_mut()) })
		.to_sysresult()
		.map(|_| ft)
}

/// [`GetLargePageMinimum`](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getlargepageminimum)
/// function.
#[must_use]
pub fn GetLargePageMinimum() -> usize {
	unsafe { ffi::GetLargePageMinimum() }
}

/// [`GetLastError`](https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror)
/// function.
///
/// This function is automatically called every time a
/// [`SysResult`](crate::SysResult) evaluates to `Err`, so it's unlikely that
/// you ever need to call it.
#[must_use]
pub fn GetLastError() -> co::ERROR {
	unsafe { co::ERROR::from_raw(ffi::GetLastError()) }
}

/// [`GetLocalTime`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlocaltime)
/// function.
///
/// This function retrieves local time; for UTC time use
/// [`GetSystemTime`](crate::GetSystemTime).
///
/// # Related functions
///
/// * [`FileTimeToSystemTime`](crate::FileTimeToSystemTime)
/// * [`GetSystemTime`](crate::GetSystemTime)
/// * [`SystemTimeToFileTime`](crate::SystemTimeToFileTime)
/// * [`SystemTimeToTzSpecificLocalTime`](crate::SystemTimeToTzSpecificLocalTime)
#[must_use]
pub fn GetLocalTime() -> SYSTEMTIME {
	let mut st = SYSTEMTIME::default();
	unsafe {
		ffi::GetLocalTime(pvoid(&mut st));
	}
	st
}

/// [`GetLogicalDrives`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getlogicaldrives)
/// function.
#[must_use]
pub fn GetLogicalDrives() -> u32 {
	unsafe { ffi::GetLogicalDrives() }
}

/// [`GetLogicalDriveStrings`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getlogicaldrivestringsw)
/// function.
#[must_use]
pub fn GetLogicalDriveStrings() -> SysResult<Vec<String>> {
	let len = match unsafe { ffi::GetLogicalDriveStringsW(0, std::ptr::null_mut()) } {
		0 => Err(GetLastError()),
		len => Ok(len),
	}?;

	let mut buf = WString::new_alloc_buf(len as usize + 1); // room for terminating null

	unsafe {
		BoolRet(ffi::GetLogicalDriveStringsW(len, buf.as_mut_ptr()) as _)
			.to_sysresult()
			.map(|_| parse_multi_z_str(buf.as_ptr(), Some(buf.buf_len())))
	}
}

/// [`GetLongPathName`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getlongpathnamew)
/// function.
#[must_use]
pub fn GetLongPathName(short_path: &str) -> SysResult<String> {
	let short_path_w = WString::from_str(short_path);
	let path_sz =
		match unsafe { ffi::GetLongPathNameW(short_path_w.as_ptr(), std::ptr::null_mut(), 0) } {
			0 => return Err(GetLastError()),
			len => len,
		};

	let mut path_buf = WString::new_alloc_buf(path_sz as _);
	match unsafe { ffi::GetLongPathNameW(short_path_w.as_ptr(), path_buf.as_mut_ptr(), path_sz) } {
		0 => Err(GetLastError()),
		_ => Ok(path_buf.to_string()),
	}
}

/// [`GetNativeSystemInfo`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getnativesysteminfo)
/// function.
#[must_use]
pub fn GetNativeSystemInfo() -> SYSTEM_INFO {
	let mut si = SYSTEM_INFO::default();
	unsafe {
		ffi::GetNativeSystemInfo(pvoid(&mut si));
	}
	si
}

/// [`GetPrivateProfileSection`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofilesectionw)
/// function.
///
/// # Examples
///
/// Reading all key/value pairs of a section from an INI file:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let pairs = w::GetPrivateProfileSection(
///     "MySection",
///     "C:\\Temp\\foo.ini",
/// )?;
///
/// for (key, val) in pairs.iter() {
///     println!("{} = {}", key, val);
/// }
/// # w::SysResult::Ok(())
/// ```
///
/// # Related functions
///
/// * [`GetPrivateProfileSectionNames`](crate::GetPrivateProfileSectionNames)
/// * [`GetPrivateProfileString`](crate::GetPrivateProfileString)
/// * [`WritePrivateProfileString`](crate::WritePrivateProfileString)
#[must_use]
pub fn GetPrivateProfileSection(
	section_name: &str,
	file_name: &str,
) -> SysResult<Vec<(String, String)>> {
	let mut buf_sz = WString::SSO_LEN; // start with no string heap allocation
	loop {
		let mut buf = WString::new_alloc_buf(buf_sz);
		let returned_chars = unsafe {
			// Char count without terminating null.
			ffi::GetPrivateProfileSectionW(
				WString::from_str(section_name).as_ptr(),
				buf.as_mut_ptr(),
				buf.buf_len() as _,
				WString::from_str(file_name).as_ptr(),
			)
		} + 1 + 1; // plus terminating null count, plus weird extra count

		if GetLastError() == co::ERROR::FILE_NOT_FOUND {
			return Err(co::ERROR::FILE_NOT_FOUND);
		} else if (returned_chars as usize) < buf_sz {
			// to break, must have at least 1 char gap
			return Ok(unsafe { parse_multi_z_str(buf.as_ptr(), Some(buf.buf_len())) }
				.iter()
				.map(|line| match line.split_once('=') {
					Some((key, val)) => (key.to_owned(), val.to_owned()),
					None => (String::new(), String::new()),
				})
				.collect());
		}

		buf_sz *= 2; // double the buffer size to try again
	}
}

/// [`GetPrivateProfileSectionNames`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofilesectionnamesw)
/// function.
///
/// # Examples
///
/// Reading all section names from an INI file:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let sections = w::GetPrivateProfileSectionNames(
///     Some("C:\\Temp\\foo.ini"),
/// )?;
///
/// for section in sections.iter() {
///     println!("{}", section);
/// }
/// # w::SysResult::Ok(())
/// ```
///
/// # Related functions
///
/// * [`GetPrivateProfileSection`](crate::GetPrivateProfileSection)
/// * [`GetPrivateProfileString`](crate::GetPrivateProfileString)
/// * [`WritePrivateProfileString`](crate::WritePrivateProfileString)
#[must_use]
pub fn GetPrivateProfileSectionNames(file_name: Option<&str>) -> SysResult<Vec<String>> {
	let mut buf_sz = WString::SSO_LEN; // start with no string heap allocation
	loop {
		let mut buf = WString::new_alloc_buf(buf_sz);

		// Char count without terminating null.
		let returned_chars = unsafe {
			ffi::GetPrivateProfileSectionNamesW(
				buf.as_mut_ptr(),
				buf.buf_len() as _,
				WString::from_opt_str(file_name).as_ptr(),
			)
		} + 1 + 1; // plus terminating null count, plus weird extra count

		if GetLastError() == co::ERROR::FILE_NOT_FOUND {
			return Err(co::ERROR::FILE_NOT_FOUND);
		} else if (returned_chars as usize) < buf_sz {
			// To break, must have at least 1 char gap.
			return Ok(unsafe { parse_multi_z_str(buf.as_ptr(), Some(buf.buf_len())) });
		}

		buf_sz *= 2; // double the buffer size to try again
	}
}

/// [`GetPrivateProfileString`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofilestringw)
/// function.
///
/// # Examples
///
/// Reading from an INI file:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let val = w::GetPrivateProfileString(
///     "MySection",
///     "MyKey",
///     "C:\\Temp\\foo.ini",
/// )?.unwrap_or("not found!".to_owned());
///
/// println!("{}", val);
/// # w::SysResult::Ok(())
/// ```
///
/// # Related functions
///
/// * [`GetPrivateProfileSection`](crate::GetPrivateProfileSection)
/// * [`GetPrivateProfileSectionNames`](crate::GetPrivateProfileSectionNames)
/// * [`WritePrivateProfileString`](crate::WritePrivateProfileString)
#[must_use]
pub fn GetPrivateProfileString(
	section_name: &str,
	key_name: &str,
	file_name: &str,
) -> SysResult<Option<String>> {
	let mut buf_sz = WString::SSO_LEN; // start with no string heap allocation
	loop {
		let mut buf = WString::new_alloc_buf(buf_sz);
		unsafe {
			// Char count without terminating null.
			ffi::GetPrivateProfileStringW(
				WString::from_str(section_name).as_ptr(),
				WString::from_str(key_name).as_ptr(),
				std::ptr::null_mut(),
				buf.as_mut_ptr(),
				buf.buf_len() as _,
				WString::from_str(file_name).as_ptr(),
			);
		}

		match GetLastError() {
			co::ERROR::SUCCESS => {
				return Ok(Some(buf.to_string()));
			},
			co::ERROR::MORE_DATA => {
				buf_sz *= 2; // double the buffer size to try again
			},
			co::ERROR::FILE_NOT_FOUND => {
				return Ok(None);
			},
			e => {
				return Err(e);
			},
		}
	}
}

/// [`GetStartupInfo`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getstartupinfow)
/// function.
#[must_use]
pub fn GetStartupInfo<'a, 'b>() -> STARTUPINFO<'a, 'b> {
	let mut si = STARTUPINFO::default();
	unsafe {
		ffi::GetStartupInfoW(pvoid(&mut si));
	}
	si
}

/// [`GetSystemDirectory`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemdirectoryw)
/// function.
#[must_use]
pub fn GetSystemDirectory() -> SysResult<String> {
	let mut buf = WString::new_alloc_buf(MAX_PATH + 1);
	let nchars = match unsafe { ffi::GetSystemDirectoryW(buf.as_mut_ptr(), buf.buf_len() as _) } {
		0 => return Err(GetLastError()),
		n => n,
	} as usize;

	if nchars > buf.buf_len() {
		buf = WString::new_alloc_buf(nchars);
		if unsafe { ffi::GetSystemDirectoryW(buf.as_mut_ptr(), buf.buf_len() as _) } == 0 {
			return Err(GetLastError());
		}
	}

	Ok(buf.to_string())
}

/// [`GetSystemFileCacheSize`](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getsystemfilecachesize)
/// function.
///
/// Returns minimum and maximum size of file cache (in bytes), and enabled cache
/// limit flags, respectively.
#[must_use]
pub fn GetSystemFileCacheSize() -> SysResult<(usize, usize, co::FILE_CACHE)> {
	let (mut min, mut max) = (0usize, 0usize);
	let mut flags = co::FILE_CACHE::default();
	BoolRet(unsafe { ffi::GetSystemFileCacheSize(&mut min, &mut max, flags.as_mut()) })
		.to_sysresult()
		.map(|_| (min, max, flags))
}

/// [`GetSystemInfo`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsysteminfo)
/// function.
#[must_use]
pub fn GetSystemInfo() -> SYSTEM_INFO {
	let mut si = SYSTEM_INFO::default();
	unsafe {
		ffi::GetSystemInfo(pvoid(&mut si));
	}
	si
}

/// [`GetSystemTime`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtime)
/// function.
///
/// This function retrieves UTC time; for local time use
/// [`GetLocalTime`](crate::GetLocalTime).
///
/// # Related functions
///
/// * [`FileTimeToSystemTime`](crate::FileTimeToSystemTime)
/// * [`GetLocalTime`](crate::GetLocalTime)
/// * [`SystemTimeToFileTime`](crate::SystemTimeToFileTime)
/// * [`SystemTimeToTzSpecificLocalTime`](crate::SystemTimeToTzSpecificLocalTime)
#[must_use]
pub fn GetSystemTime() -> SYSTEMTIME {
	let mut st = SYSTEMTIME::default();
	unsafe {
		ffi::GetSystemTime(pvoid(&mut st));
	}
	st
}

/// [`GetSystemTimeAsFileTime`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime)
/// function.
#[must_use]
pub fn GetSystemTimeAsFileTime() -> FILETIME {
	let mut ft = FILETIME::default();
	unsafe {
		ffi::GetSystemTimeAsFileTime(pvoid(&mut ft));
	}
	ft
}

/// [`GetSystemTimePreciseAsFileTime`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime)
/// function.
#[must_use]
pub fn GetSystemTimePreciseAsFileTime() -> FILETIME {
	let mut ft = FILETIME::default();
	unsafe {
		ffi::GetSystemTimePreciseAsFileTime(pvoid(&mut ft));
	}
	ft
}

/// [`GetSystemTimes`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getsystemtimes)
/// function.
///
/// Returns idle, kernel and user times.
///
/// # Examples
///
/// Retrieving just the kernel time:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let (_, kernel_time, _) = w::GetSystemTimes()?;
/// # w::SysResult::Ok(())
/// ```
#[must_use]
pub fn GetSystemTimes() -> SysResult<(FILETIME, FILETIME, FILETIME)> {
	let mut idle_time = FILETIME::default();
	let mut kernel_time = FILETIME::default();
	let mut user_time = FILETIME::default();

	BoolRet(unsafe {
		ffi::GetSystemTimes(pvoid(&mut idle_time), pvoid(&mut kernel_time), pvoid(&mut user_time))
	})
	.to_sysresult()
	.map(|_| (idle_time, kernel_time, user_time))
}

/// [`GetTempFileName`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettempfilenamew)
/// function.
#[must_use]
pub fn GetTempFileName(path_name: &str, prefix: &str, unique: u32) -> SysResult<String> {
	let mut buf = WString::new_alloc_buf(MAX_PATH + 1);
	BoolRet(unsafe {
		ffi::GetTempFileNameW(
			WString::from_str(path_name).as_ptr(),
			WString::from_str(prefix).as_ptr(),
			unique,
			buf.as_mut_ptr(),
		)
	} as _)
	.to_sysresult()
	.map(|_| buf.to_string())
}

/// [`GetTempPath`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppathw)
/// function.
#[must_use]
pub fn GetTempPath() -> SysResult<String> {
	let mut buf = WString::new_alloc_buf(MAX_PATH + 1);
	BoolRet(unsafe { ffi::GetTempPathW(buf.buf_len() as _, buf.as_mut_ptr()) } as _)
		.to_sysresult()
		.map(|_| buf.to_string())
}

/// [`GetTickCount64`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount64)
/// function.
#[must_use]
pub fn GetTickCount64() -> u64 {
	unsafe { ffi::GetTickCount64() }
}

/// [`GetVolumeInformation`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getvolumeinformationw)
/// function.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*, co};
///
/// let mut name = String::new();
/// let mut serial_no = 0u32;
/// let mut max_comp_len = 0u32;
/// let mut sys_flags = co::FILE_VOL::default();
/// let mut sys_name = String::new();
///
/// w::GetVolumeInformation(
///     Some("C:\\"),
///     Some(&mut name),
///     Some(&mut serial_no),
///     Some(&mut max_comp_len),
///     Some(&mut sys_flags),
///     Some(&mut sys_name),
/// )?;
///
/// println!("Name: {}", name);
/// println!("Serial no: {:#010x}", serial_no);
/// println!("Max comp len: {}", max_comp_len);
/// println!("Sys flags: {:?}", sys_flags);
/// println!("Sys name: {}", sys_name);
/// # w::SysResult::Ok(())
/// ```
pub fn GetVolumeInformation(
	root_path_name: Option<&str>,
	name: Option<&mut String>,
	serial_number: Option<&mut u32>,
	max_component_len: Option<&mut u32>,
	file_system_flags: Option<&mut co::FILE_VOL>,
	file_system_name: Option<&mut String>,
) -> SysResult<()> {
	let (mut name_buf, name_buf_sz) = match name {
		None => (WString::new(), 0),
		Some(_) => (WString::new_alloc_buf(MAX_PATH + 1), MAX_PATH + 1),
	};
	let (mut sys_name_buf, sys_name_buf_sz) = match file_system_name {
		None => (WString::new(), 0),
		Some(_) => (WString::new_alloc_buf(MAX_PATH + 1), MAX_PATH + 1),
	};

	BoolRet(unsafe {
		ffi::GetVolumeInformationW(
			WString::from_opt_str(root_path_name).as_ptr(),
			match name {
				Some(_) => name_buf.as_mut_ptr(),
				None => std::ptr::null_mut(),
			},
			name_buf_sz as _,
			serial_number.map_or(std::ptr::null_mut(), |n| n),
			max_component_len.map_or(std::ptr::null_mut(), |m| m),
			file_system_flags.map_or(std::ptr::null_mut(), |f| f.as_mut()),
			match file_system_name {
				Some(_) => sys_name_buf.as_mut_ptr(),
				None => std::ptr::null_mut(),
			},
			sys_name_buf_sz as _,
		)
	})
	.to_sysresult()
	.map(|_| {
		if let Some(name) = name {
			*name = name_buf.to_string();
		}
		if let Some(sys_name) = file_system_name {
			*sys_name = sys_name_buf.to_string();
		}
	})
}

/// [`GetVolumePathName`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getvolumepathnamew)
/// function.
#[must_use]
pub fn GetVolumePathName(file_name: &str) -> SysResult<String> {
	let mut buf = WString::new_alloc_buf(MAX_PATH + 1);
	BoolRet(unsafe {
		ffi::GetVolumePathNameW(
			WString::from_str(file_name).as_ptr(),
			buf.as_mut_ptr(),
			buf.buf_len() as _,
		)
	})
	.to_sysresult()
	.map(|_| buf.to_string())
}

/// [`GlobalMemoryStatusEx`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex)
/// function.
#[must_use]
pub fn GlobalMemoryStatusEx() -> SysResult<MEMORYSTATUSEX> {
	let mut msx = MEMORYSTATUSEX::default();
	BoolRet(unsafe { ffi::GlobalMemoryStatusEx(pvoid(&mut msx)) })
		.to_sysresult()
		.map(|_| msx)
}

/// [`HIBYTE`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms632656(v=vs.85))
/// macro.
///
/// # Related functions
///
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LODWORD`](crate::LODWORD)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn HIBYTE(v: u16) -> u8 {
	(v >> 8 & 0xff) as _
}

/// Returns the high-order `u32` of an `u64`.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LODWORD`](crate::LODWORD)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn HIDWORD(v: u64) -> u32 {
	(v >> 32 & 0xffff_ffff) as _
}

/// [`HIWORD`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms632657(v=vs.85))
/// macro.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LODWORD`](crate::LODWORD)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn HIWORD(v: u32) -> u16 {
	(v >> 16 & 0xffff) as _
}

/// [`IsDebuggerPresent`](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-isdebuggerpresent)
/// function.
#[must_use]
pub fn IsDebuggerPresent() -> bool {
	unsafe { ffi::IsDebuggerPresent() != 0 }
}

/// [`IsNativeVhdBoot`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-isnativevhdboot)
/// function.
#[must_use]
pub fn IsNativeVhdBoot() -> SysResult<bool> {
	let mut is_native = 0;
	BoolRet(unsafe { ffi::IsNativeVhdBoot(&mut is_native) })
		.to_sysresult()
		.map(|_| is_native != 0)
}

/// [`IsWindows10OrGreater`](https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindows10orgreater)
/// function.
#[must_use]
pub fn IsWindows10OrGreater() -> SysResult<bool> {
	IsWindowsVersionOrGreater(
		HIBYTE(co::WIN32::WINNT_WINTHRESHOLD.raw()) as _,
		LOBYTE(co::WIN32::WINNT_WINTHRESHOLD.raw()) as _,
		0,
	)
}

/// [`IsWindows7OrGreater`](https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindows7orgreater)
/// function.
#[must_use]
pub fn IsWindows7OrGreater() -> SysResult<bool> {
	IsWindowsVersionOrGreater(
		HIBYTE(co::WIN32::WINNT_WIN7.raw()) as _,
		LOBYTE(co::WIN32::WINNT_WIN7.raw()) as _,
		0,
	)
}

/// [`IsWindows8OrGreater`](https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindows8orgreater)
/// function.
#[must_use]
pub fn IsWindows8OrGreater() -> SysResult<bool> {
	IsWindowsVersionOrGreater(
		HIBYTE(co::WIN32::WINNT_WIN8.raw()) as _,
		LOBYTE(co::WIN32::WINNT_WIN8.raw()) as _,
		0,
	)
}

/// [`IsWindows8Point1OrGreater`](https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindows8point1orgreater)
/// function.
#[must_use]
pub fn IsWindows8Point1OrGreater() -> SysResult<bool> {
	IsWindowsVersionOrGreater(
		HIBYTE(co::WIN32::WINNT_WINBLUE.raw()) as _,
		LOBYTE(co::WIN32::WINNT_WINBLUE.raw()) as _,
		0,
	)
}

/// [`IsWindowsServer`](https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindowsserver)
/// function.
#[must_use]
pub fn IsWindowsServer() -> SysResult<bool> {
	let mut osvi = OSVERSIONINFOEX::default();
	osvi.wProductType = co::VER_NT::WORKSTATION;
	let cond_mask = VerSetConditionMask(0, co::VER_MASK::PRODUCT_TYPE, co::VER_COND::EQUAL);
	VerifyVersionInfo(&mut osvi, co::VER_MASK::PRODUCT_TYPE, cond_mask).map(|b| !b)
}

/// [`IsWindowsVersionOrGreater`](https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindowsversionorgreater)
/// function.
#[must_use]
pub fn IsWindowsVersionOrGreater(
	major_version: u16,
	minor_version: u16,
	service_pack_major: u16,
) -> SysResult<bool> {
	let mut osvi = OSVERSIONINFOEX::default();
	let cond_mask = VerSetConditionMask(
		VerSetConditionMask(
			VerSetConditionMask(0, co::VER_MASK::MAJORVERSION, co::VER_COND::GREATER_EQUAL),
			co::VER_MASK::MINORVERSION,
			co::VER_COND::GREATER_EQUAL,
		),
		co::VER_MASK::SERVICEPACKMAJOR,
		co::VER_COND::GREATER_EQUAL,
	);

	osvi.dwMajorVersion = major_version as _;
	osvi.dwMinorVersion = minor_version as _;
	osvi.wServicePackMajor = service_pack_major;

	VerifyVersionInfo(
		&mut osvi,
		co::VER_MASK::MAJORVERSION | co::VER_MASK::MINORVERSION | co::VER_MASK::SERVICEPACKMAJOR,
		cond_mask,
	)
}

/// [`IsWindowsVistaOrGreater`](https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindowsvistaorgreater)
/// function.
#[must_use]
pub fn IsWindowsVistaOrGreater() -> SysResult<bool> {
	IsWindowsVersionOrGreater(
		HIBYTE(co::WIN32::WINNT_VISTA.raw()) as _,
		LOBYTE(co::WIN32::WINNT_VISTA.raw()) as _,
		0,
	)
}

/// [`LOBYTE`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms632658(v=vs.85))
/// macro.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LODWORD`](crate::LODWORD)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn LOBYTE(v: u16) -> u8 {
	(v & 0xff) as _
}

/// Returns the low-order `u32` of an `u64`.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn LODWORD(v: u64) -> u32 {
	(v & 0xffff_ffff) as _
}

/// [`LOWORD`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms632659(v=vs.85))
/// macro.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LODWORD`](crate::LODWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn LOWORD(v: u32) -> u16 {
	(v & 0xffff) as _
}

/// Function analog to
/// [`MAKELONG`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms632660(v=vs.85)),
/// [`MAKEWPARAM`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-makewparam),
/// and
/// [`MAKELPARAM`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-makelparam)
/// macros.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LODWORD`](crate::LODWORD)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn MAKEDWORD(lo: u16, hi: u16) -> u32 {
	((lo as u32 & 0xffff) | ((hi as u32 & 0xffff) << 16)) as _
}

/// Similar to [`MAKEDWORD`](crate::MAKEDWORD), but for `u64`.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LODWORD`](crate::LODWORD)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEWORD`](crate::MAKEWORD)
#[must_use]
pub const fn MAKEQWORD(lo: u32, hi: u32) -> u64 {
	((lo as u64 & 0xffff_ffff) | ((hi as u64 & 0xffff_ffff) << 32)) as _
}

/// [`MAKEWORD`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms632663(v=vs.85))
/// macro.
///
/// # Related functions
///
/// * [`HIBYTE`](crate::HIBYTE)
/// * [`HIDWORD`](crate::HIDWORD)
/// * [`HIWORD`](crate::HIWORD)
/// * [`LOBYTE`](crate::LOBYTE)
/// * [`LODWORD`](crate::LODWORD)
/// * [`LOWORD`](crate::LOWORD)
/// * [`MAKEDWORD`](crate::MAKEDWORD)
/// * [`MAKEQWORD`](crate::MAKEQWORD)
#[must_use]
pub const fn MAKEWORD(lo: u8, hi: u8) -> u16 {
	(lo as u16 & 0xff) | ((hi as u16 & 0xff) << 8) as u16
}

/// [`MoveFile`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefilew)
/// function.
///
/// # Related functions
///
/// * [`CopyFile`](crate::CopyFile)
/// * [`DeleteFile`](crate::DeleteFile)
/// * [`MoveFileEx`](crate::MoveFileEx)
/// * [`ReplaceFile`](crate::ReplaceFile)
pub fn MoveFile(existing_file: &str, new_file: &str) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::MoveFileW(
			WString::from_str(existing_file).as_ptr(),
			WString::from_str(new_file).as_ptr(),
		)
	})
	.to_sysresult()
}

/// [`MoveFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw)
/// function.
///
/// # Related functions
///
/// * [`CopyFile`](crate::CopyFile)
/// * [`DeleteFile`](crate::DeleteFile)
/// * [`MoveFile`](crate::MoveFile)
/// * [`ReplaceFile`](crate::ReplaceFile)
pub fn MoveFileEx(
	existing_file: &str,
	new_file: Option<&str>,
	flags: co::MOVEFILE,
) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::MoveFileExW(
			WString::from_str(existing_file).as_ptr(),
			WString::from_opt_str(new_file).as_ptr(),
			flags.raw(),
		)
	})
	.to_sysresult()
}

/// [`MulDiv`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-muldiv)
/// function.
#[must_use]
pub fn MulDiv(number: i32, numerator: i32, denominator: i32) -> i32 {
	unsafe { ffi::MulDiv(number, numerator, denominator) }
}

/// [`MultiByteToWideChar`](https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar)
/// function.
///
/// If `multi_byte_str` doesn't have a terminating null, the resulting
/// `Vec<u16>` also won't include one.
///
/// # Related functions
///
/// * [`WideCharToMultiByte`](crate::WideCharToMultiByte)
#[must_use]
pub fn MultiByteToWideChar(
	code_page: co::CP,
	flags: co::MBC,
	multi_byte_str: &[u8],
) -> SysResult<Vec<u16>> {
	let num_bytes = match unsafe {
		ffi::MultiByteToWideChar(
			code_page.raw() as _,
			flags.raw(),
			vec_ptr(multi_byte_str),
			multi_byte_str.len() as _,
			std::ptr::null_mut(),
			0,
		)
	} {
		0 => Err(GetLastError()),
		num_bytes => Ok(num_bytes),
	}?;

	let mut buf = vec![0u16; num_bytes as _];

	BoolRet(unsafe {
		ffi::MultiByteToWideChar(
			code_page.raw() as _,
			flags.raw(),
			vec_ptr(multi_byte_str),
			multi_byte_str.len() as _,
			buf.as_mut_ptr(),
			num_bytes as _,
		)
	})
	.to_sysresult()
	.map(|_| buf)
}

/// [`OutputDebugString`](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringw)
/// function.
pub fn OutputDebugString(output_string: &str) {
	unsafe { ffi::OutputDebugStringW(WString::from_str(output_string).as_ptr()) }
}

/// [`QueryPerformanceCounter`](https://learn.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter)
/// function.
///
/// # Examples
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// let freq = w::QueryPerformanceFrequency()?;
/// let t0 = w::QueryPerformanceCounter()?;
///
/// // perform some operation...
///
/// let duration_ms =
///     ((w::QueryPerformanceCounter()? - t0) as f64 / freq as f64) * 1000.0;
///
/// println!("Operation lasted {:.2} ms", duration_ms);
/// # w::SysResult::Ok(())
/// ```
///
/// # Related functions
///
/// * [`QueryPerformanceFrequency`](crate::QueryPerformanceFrequency)
#[must_use]
pub fn QueryPerformanceCounter() -> SysResult<i64> {
	let mut perf_count = 0i64;
	BoolRet(unsafe { ffi::QueryPerformanceCounter(&mut perf_count) })
		.to_sysresult()
		.map(|_| perf_count)
}

/// [`QueryPerformanceFrequency`](https://learn.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter)
/// function.
///
/// # Related functions
///
/// * [`QueryPerformanceCounter`](crate::QueryPerformanceCounter)
#[must_use]
pub fn QueryPerformanceFrequency() -> SysResult<i64> {
	let mut freq = 0i64;
	BoolRet(unsafe { ffi::QueryPerformanceFrequency(&mut freq) })
		.to_sysresult()
		.map(|_| freq)
}

/// [`QueryUnbiasedInterruptTime`](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryunbiasedinterrupttime)
/// function.
#[must_use]
pub fn QueryUnbiasedInterruptTime() -> SysResult<u64> {
	let mut t = 0u64;
	BoolRet(unsafe { ffi::QueryUnbiasedInterruptTime(&mut t) })
		.to_sysresult()
		.map(|_| t)
}

/// [`ReplaceFile`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew)
/// function.
///
/// # Related functions
///
/// * [`CopyFile`](crate::CopyFile)
/// * [`DeleteFile`](crate::DeleteFile)
/// * [`MoveFile`](crate::MoveFile)
pub fn ReplaceFile(
	replaced: &str,
	replacement: &str,
	backup: Option<&str>,
	flags: co::REPLACEFILE,
) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::ReplaceFileW(
			WString::from_str(replaced).as_ptr(),
			WString::from_str(replacement).as_ptr(),
			WString::from_opt_str(backup).as_ptr(),
			flags.raw(),
			std::ptr::null_mut(),
			std::ptr::null_mut(),
		)
	})
	.to_sysresult()
}

/// [`SetCurrentDirectory`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setcurrentdirectory)
/// function.
pub fn SetCurrentDirectory(path_name: &str) -> SysResult<()> {
	BoolRet(unsafe { ffi::SetCurrentDirectoryW(WString::from_str(path_name).as_ptr()) })
		.to_sysresult()
}

/// [`SetFileAttributes`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileattributesw)
/// function.
pub fn SetFileAttributes(file_name: &str, attributes: co::FILE_ATTRIBUTE) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::SetFileAttributesW(WString::from_str(file_name).as_ptr(), attributes.raw())
	})
	.to_sysresult()
}

/// [`SetLastError`](https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-setlasterror)
/// function.
pub fn SetLastError(err_code: co::ERROR) {
	unsafe { ffi::SetLastError(err_code.raw()) }
}

/// [`SetThreadStackGuarantee`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadstackguarantee)
/// function.
///
/// Returns the size of the previous stack.
pub fn SetThreadStackGuarantee(stack_size_in_bytes: u32) -> SysResult<u32> {
	let mut sz = stack_size_in_bytes;
	BoolRet(unsafe { ffi::SetThreadStackGuarantee(&mut sz) })
		.to_sysresult()
		.map(|_| sz)
}

/// [`Sleep`](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep)
/// function.
pub fn Sleep(milliseconds: u32) {
	unsafe { ffi::Sleep(milliseconds) }
}

/// [`SwitchToThread`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-switchtothread)
/// function.
pub fn SwitchToThread() -> SysResult<()> {
	BoolRet(unsafe { ffi::SwitchToThread() }).to_sysresult()
}

/// [`SystemTimeToFileTime`](https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-systemtimetofiletime)
/// function.
///
/// # Related functions
///
/// * [`FileTimeToSystemTime`](crate::FileTimeToSystemTime)
/// * [`GetLocalTime`](crate::GetLocalTime)
/// * [`GetSystemTime`](crate::GetSystemTime)
/// * [`SystemTimeToTzSpecificLocalTime`](crate::SystemTimeToTzSpecificLocalTime)
#[must_use]
pub fn SystemTimeToFileTime(st: &SYSTEMTIME) -> SysResult<FILETIME> {
	let mut ft = FILETIME::default();
	BoolRet(unsafe { ffi::SystemTimeToFileTime(pcvoid(st), pvoid(&mut ft)) })
		.to_sysresult()
		.map(|_| ft)
}

/// [`SystemTimeToTzSpecificLocalTime`](https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-systemtimetotzspecificlocaltime)
/// function.
///
/// # Related functions
///
/// * [`FileTimeToSystemTime`](crate::FileTimeToSystemTime)
/// * [`GetLocalTime`](crate::GetLocalTime)
/// * [`GetSystemTime`](crate::GetSystemTime)
/// * [`SystemTimeToFileTime`](crate::SystemTimeToFileTime)
#[must_use]
pub fn SystemTimeToTzSpecificLocalTime(
	time_zone: Option<&TIME_ZONE_INFORMATION>,
	universal_time: &SYSTEMTIME,
) -> SysResult<SYSTEMTIME> {
	let mut local_time = SYSTEMTIME::default();
	BoolRet(unsafe {
		ffi::SystemTimeToTzSpecificLocalTime(
			time_zone.map_or(std::ptr::null(), |lp| pcvoid(lp)),
			pcvoid(universal_time),
			pvoid(&mut local_time),
		)
	})
	.to_sysresult()
	.map(|_| local_time)
}

/// [`VerifyVersionInfo`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-verifyversioninfow)
/// function.
#[must_use]
pub fn VerifyVersionInfo(
	osvix: &mut OSVERSIONINFOEX,
	type_mask: co::VER_MASK,
	condition_mask: u64,
) -> SysResult<bool> {
	match unsafe { ffi::VerifyVersionInfoW(pvoid(osvix), type_mask.raw(), condition_mask) } {
		0 => match GetLastError() {
			co::ERROR::OLD_WIN_VERSION => Ok(false),
			err => Err(err),
		},
		_ => Ok(true),
	}
}

/// [`VerSetConditionMask`](https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-versetconditionmask)
/// function.
#[must_use]
pub fn VerSetConditionMask(
	condition_mask: u64,
	type_mask: co::VER_MASK,
	condition: co::VER_COND,
) -> u64 {
	unsafe { ffi::VerSetConditionMask(condition_mask, type_mask.raw(), condition.raw()) }
}

/// [`WideCharToMultiByte`](https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte)
/// function.
///
/// If `wide_char_str` doesn't have a terminating null, the resulting `Vec<u8>`
/// also won't include one.
///
/// # Related functions
///
/// * [`MultiByteToWideChar`](crate::MultiByteToWideChar)
#[must_use]
pub fn WideCharToMultiByte(
	code_page: co::CP,
	flags: co::WC,
	wide_char_str: &[u16],
	default_char: Option<u8>,
	used_default_char: Option<&mut bool>,
) -> SysResult<Vec<u8>> {
	let mut default_char_buf = default_char.unwrap_or_default();

	let num_bytes = match unsafe {
		ffi::WideCharToMultiByte(
			code_page.raw() as _,
			flags.raw(),
			vec_ptr(wide_char_str),
			wide_char_str.len() as _,
			std::ptr::null_mut(),
			0,
			&mut default_char_buf,
			std::ptr::null_mut(),
		)
	} {
		0 => Err(GetLastError()),
		num_bytes => Ok(num_bytes),
	}?;

	let mut u8_buf = vec![0u8; num_bytes as _];
	let mut bool_buf = 0;

	BoolRet(unsafe {
		ffi::WideCharToMultiByte(
			code_page.raw() as _,
			flags.raw(),
			vec_ptr(wide_char_str),
			wide_char_str.len() as _,
			u8_buf.as_mut_ptr() as _,
			num_bytes as _,
			&mut default_char_buf,
			&mut bool_buf,
		)
	})
	.to_sysresult()
	.map(|_| {
		if let Some(used_default_char) = used_default_char {
			*used_default_char = bool_buf != 0;
		}
		u8_buf
	})
}

/// [`WritePrivateProfileString`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-writeprivateprofilestringw)
/// function.
///
/// # Examples
///
/// Writing value into an INI file:
///
/// ```no_run
/// use winsafe::{self as w, prelude::*};
///
/// w::WritePrivateProfileString(
///     "MySection",
///     Some("MyKey"),
///     Some("new value"),
///     "C:\\Temp\\foo.ini",
/// )?;
/// # w::SysResult::Ok(())
/// ```
///
/// # Related functions
///
/// * [`GetPrivateProfileSection`](crate::GetPrivateProfileSection)
/// * [`GetPrivateProfileSectionNames`](crate::GetPrivateProfileSectionNames)
/// * [`GetPrivateProfileString`](crate::GetPrivateProfileString)
pub fn WritePrivateProfileString(
	section_name: &str,
	key_name: Option<&str>,
	new_val: Option<&str>,
	file_name: &str,
) -> SysResult<()> {
	BoolRet(unsafe {
		ffi::WritePrivateProfileStringW(
			WString::from_str(section_name).as_ptr(),
			WString::from_opt_str(key_name).as_ptr(),
			WString::from_opt_str(new_val).as_ptr(),
			WString::from_str(file_name).as_ptr(),
		)
	})
	.to_sysresult()
}