oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
//! What Windows alone has: overlapped I/O, and the completion port that
//! collects it.
//!
//! On a handle opened for *overlapped* operation, a read or a write is
//! started and returns at once; it runs in the system, and its outcome is
//! told later. Three things make an interface of that:
//!
//! - **Handles for it.** A handle is overlapped or not from its creation.
//!   Those oscall makes elsewhere are not ([`fs::open`](crate::fs::open),
//!   [`io::pipe`](crate::io::pipe)): [`open`] and [`pipe`] make ones that
//!   are, as do [`open_unbuffered`], for
//!   [files without the cache](self#files-without-the-cache), and
//!   [`pipe_server`] and [`pipe_client`], for
//!   [pipes that have a name](self#named-pipes). Every socket of
//!   [`net`](crate::net) is.
//! - **A [`CompletionPort`]**: a queue of the system's, which a handle is
//!   [associated](CompletionPort::associate) with once, for good. Each
//!   operation that completes on the handle queues a [`Completion`] there,
//!   and any number of threads [wait](CompletionPort::wait) for them.
//! - **An [`Operation`]** (with the `alloc` feature): the memory the system
//!   writes to while an operation runs — the `OVERLAPPED` structure and
//!   the buffer — owned by one object, which starts operations, tells
//!   their outcome and hands the buffer back. What it starts: reads and
//!   writes of files and pipes, into one buffer or into pages; receives
//!   and sends on sockets, with one buffer or several, with or without
//!   an address; accepting and making connections; sending a file on a
//!   socket; waiting for the client of a named pipe; and waiting for
//!   changes in a directory.
//!
//! ```no_run
//! # #[cfg(feature = "alloc")]
//! # fn main() -> oscall::Result<()> {
//! use oscall::fs::OpenOptions;
//! use oscall::io::windows::{self, Completion, CompletionPort, Operation};
//!
//! let file = windows::open("data", &OpenOptions::new().read(true))?;
//! let port = CompletionPort::new()?;
//! port.associate(&file, 1)?;
//!
//! let mut read = Operation::new()?;
//! read.read(&file, Vec::with_capacity(4096), Some(0))?;
//! let mut completions = [Completion::EMPTY; 8];
//! let count = port.wait(&mut completions, None)?;
//! for completion in &completions[..count] {
//!     if completion.id() == read.id() {
//!         let data = read.take_buffer().expect("the read is complete");
//!         assert_eq!(data.len(), completion.result()?);
//!     }
//! }
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "alloc"))]
//! # fn main() {}
//! ```
//!
//! # Whose memory it is
//!
//! The system writes the status of an operation, and what it reads, when
//! the operation completes, wherever the program has gone by then. An
//! [`Operation`] makes that sound without `unsafe`:
//!
//! - it owns the `OVERLAPPED` and the buffer, on the heap: moving the
//!   `Operation`, or forgetting it, moves or frees neither;
//! - while its operation is in flight it lends nothing out
//!   ([`take_buffer`](Operation::take_buffer) returns `None`) and starts
//!   nothing else ([`ResourceBusy`](ErrorKind::ResourceBusy));
//! - **dropped in flight, it cancels the operation (`CancelIoEx`) and
//!   waits for the system to say it is over** before the memory is freed.
//!   Cancelling is quick but not instant, and a driver may take its time:
//!   if the operation is still not over after a few seconds, the memory is
//!   leaked instead, never freed under the system.
//!
//! That wait is why each `Operation` has an event of its own, and it
//! matters more than it seems. Given an event, the system writes the
//! status of an operation when the operation completes, then sets the
//! event, then queues the packet to the port, and never touches the
//! structure again. Given none, on a handle that has a port, it writes the
//! status *when the packet is taken from the port*, by whoever takes it,
//! however much later: into memory that must still be there. (Both
//! measured.) An `OVERLAPPED` with no event can therefore not be freed
//! before its packet has been seen; one with an event can, as soon as the
//! status says so.
//!
//! An operation can also be given memory the caller keeps, in the place
//! of a buffer to own (`Operation::read_kept` and the like): a part of
//! something larger, whole pages, memory that is not a `Vec`. Those are
//! `unsafe`: the caller answers for the memory until the operation is
//! complete, which dropping the `Operation` does not promise once its
//! patience is out. The `OVERLAPPED`, and what else the system writes
//! (the address a datagram came from), stay the `Operation`'s own.
//!
//! A [`Completion`] is two numbers and a status, copied out of the port:
//! taking one touches no memory of an operation, so it does not matter to
//! soundness what a port is handed, by whom. The price is that a
//! completion names its operation by [number](Operation::id) (the address
//! of its `OVERLAPPED`), and that **a completion can outlive its
//! operation**: one dropped in flight still has its packet queued, and the
//! number can since belong to a new `Operation`. What tells is the
//! operation itself: [`Operation::result`] is `None` until *its* operation
//! is complete, whatever a completion said.
//!
//! # What a port tells, and what it does not
//!
//! - A completion is queued for every operation that was started, also one
//!   that was complete by the time the call that started it returned,
//!   unless the handle was told otherwise: see
//!   [below](self#operations-that-are-over-at-once). None is queued when
//!   the start itself fails: [`Operation::read`] and the others then
//!   return the error.
//! - A handle has one port, for as long as it lives; associating it again
//!   fails with [`InvalidInput`](ErrorKind::InvalidInput), as does a
//!   handle that is not overlapped.
//! - The port does not own the handles: closing one cancels its operations
//!   (when it is the last handle of the file), which complete with
//!   [`Canceled`](ErrorKind::Canceled).
//! - **An operation belongs to the thread that started it**: when that
//!   thread ends, the system cancels what it still has in flight, which
//!   completes with [`Canceled`](ErrorKind::Canceled). (The system spares
//!   the operations of a handle that has a port, but only those that have
//!   no event, which an [`Operation`]'s always has: see above.) Start
//!   operations from threads that live as long as the operations may.
//! - A port is not something a
//!   [`Poller`](crate::event::Poller) can wait for:
//!   [`event::windows::register`](crate::event::windows::register) refuses
//!   its handle. A program waits on one or on the other, or wakes one from
//!   a thread that waits on the other.
//!
//! # Operations that are over at once
//!
//! Much of what is started is complete when the call that starts it
//! returns: a read of a pipe that has data, a receive of a datagram that
//! waits, a send the system had room for. The system queues a completion
//! for those too, which a program that already has the outcome then takes
//! from the port for nothing. [`set_completion_modes`] with
//! [`SKIP_PORT_ON_SUCCESS`](CompletionModes::SKIP_PORT_ON_SUCCESS) tells
//! the system not to, for one handle, for good; and then
//! [`Operation::completed_at_start`] is what tells the two kinds of
//! operation apart:
//!
//! - `true`: the call that started the operation returned with it
//!   complete. Its outcome is there, and **no completion is queued** for
//!   it on a handle that skips its port (one is on any other).
//! - `false`: the call returned with the operation pending. Its
//!   completion is queued, on every handle, also if the operation was
//!   over an instant later.
//!
//! It is what the call returned that decides, not what the operation is
//! by the time anybody looks, which is why an `Operation` remembers it.
//! Four things were measured that are not what one would guess (on
//! x86_64, aarch64 and 32-bit x86):
//!
//! - **A read of a file is reported as pending**, through the cache or
//!   without it, 4096 bytes or 32 MiB, also when the work was done before
//!   the call returned; so is a write without the cache. A write of 4096
//!   bytes through the cache was reported complete on x86_64 and pending
//!   on aarch64. A file queues a completion for nearly every operation,
//!   whatever its modes: what the mode saves, it saves on pipes and
//!   sockets.
//! - **What completes at once with a warning is reported as pending**,
//!   and has its completion queued, also on a handle that skips its port:
//!   the start of a message of a pipe that is longer than the buffer, and
//!   the start of a datagram that is. Both complete with the status
//!   `0x80000005`, which is not a failure: the outcome is the count.
//! - A write that extends a file opened without the cache is done in
//!   the call that starts it, and reported as pending like the others:
//!   see [below](self#files-without-the-cache).
//! - A watch of a directory that has changes waiting is reported as
//!   pending too, and completes at once.
//!
//! An operation whose start fails has started nothing, here as
//! everywhere. The other mode,
//! [`SKIP_EVENT_ON_HANDLE`](CompletionModes::SKIP_EVENT_ON_HANDLE),
//! changes nothing to an `Operation`, which waits on an event of its own.
//!
//! # Files without the cache
//!
//! On a file opened by [`open`], which goes through the system's cache,
//! the system does what it can in the call that starts an operation: a
//! write is copied to the cache there and then (256 MB took 0.7 to 1 s
//! *to start*, and were written when the start returned), and so is a
//! read of what the cache holds. A read of what it does not hold is
//! pending while the storage is read (32 MiB: 2 to 4 ms to start, 15 to
//! 340 ms to complete).
//!
//! On a file opened by [`open_unbuffered`] an operation goes to the
//! storage, and the call that starts it returns before it is done. As
//! measured with 32 MiB on the runners of GitHub, whose disks are
//! virtual and differ from one run to the next (two runs each of x86_64,
//! aarch64 and 32-bit x86):
//!
//! | | the start took | complete after |
//! |---|---|---|
//! | a write over what the file has | 0.3 to 0.8 ms | 5 to 120 ms |
//! | a read | 2.6 to 5.9 ms | 8 to 528 ms |
//! | **a write that extends the file** | 7.6 to 119 ms | the same |
//!
//! The last line is the one exception: the file system does a write past
//! the end of a file before it returns, whatever the handle, each of the
//! six times. Every one of these calls returned with the operation
//! pending, that one included, and queued its completion.
//!
//! The rules of such a file are those of the storage, and what breaks
//! one is refused when the operation is started
//! ([`InvalidInput`](ErrorKind::InvalidInput), as measured for each):
//! the offset, the length and the address of the memory are multiples of
//! the size of a sector ([`sector_size`]: 512 bytes on those runners). A
//! `Vec<u8>` promises no such address, so that these operations are the
//! ones on memory the caller keeps: `Operation::read_kept` and
//! `Operation::write_kept` with whole pages, or
//! `Operation::read_scatter` and `Operation::write_gather`, which take
//! the pages one by one, in any order, and which the system has for
//! these files alone. A file is read short at its end.
//!
//! # Named pipes
//!
//! [`pipe`] is a pipe both ends of which one process holds. A pipe with a
//! name is how two processes that share nothing find each other: a
//! server creates an *instance* of it ([`pipe_server`]), a client opens
//! the name ([`pipe_client`]) and has the other end of that instance.
//! Each instance serves one client at a time, and goes through these
//! states, as measured:
//!
//! - **New**, it takes a client at once, also before the server waits
//!   for one: `Operation::connect_pipe` then answers `Ok(false)`, a
//!   client is there, and starts nothing.
//! - **Waiting** (`Operation::connect_pipe` answered `Ok(true)`): the
//!   operation completes when a client opens the pipe.
//! - **Connected**: read and written like any pipe, by operations or by
//!   the functions of [`io`](crate::io). Another client finds the pipe
//!   busy ([`ResourceBusy`](ErrorKind::ResourceBusy); [`wait_pipe`]
//!   waits for an instance), and waiting for a client again answers
//!   `Ok(false)`.
//! - **Left by its client**: reads tell the end of the stream, and
//!   waiting for another client fails
//!   ([`BrokenPipe`](ErrorKind::BrokenPipe)) until the server has ended
//!   the connection on its side: [`disconnect_pipe`].
//! - **Disconnected**: it takes no client (the pipe is busy to them)
//!   until the server waits for one again. A client that still has the
//!   other end finds it not connected.
//!
//! A server that talks to several clients at once keeps one instance
//! waiting, and creates another when that one gets its client.
//!
//! # The synchronous functions on these handles
//!
//! [`io::read_at`](crate::io::read_at), [`io::write_at`](crate::io::write_at)
//! and the rest of [`io`](crate::io) and [`fs`](crate::fs) work on an
//! overlapped handle, also one associated with a port: they wait for their
//! own operation, however long it takes, and queue nothing. So do the
//! functions of [`net`](crate::net) on a socket that has a port. A file
//! opened by [`open`] has no
//! position: [`io::read()`](crate::io::read()) and
//! [`io::write()`](crate::io::write()) fail on it with
//! [`InvalidInput`](ErrorKind::InvalidInput), and an [`Operation`] must
//! say where it reads or writes. A pipe has none to say.

use core::fmt;
use core::time::Duration;

use crate::fs::OpenOptions;
use crate::macros::flags;
use crate::net::AsSocket;
use crate::sys::io::OverlappedEntry;
use crate::sys::overlapped as sys;
use crate::{AsHandle, AsPath, BorrowedHandle, ErrorKind, OwnedHandle, Result};

/// Opens a file as [`fs::open`](crate::fs::open) does, for overlapped
/// operation (`FILE_FLAG_OVERLAPPED`): what an [`Operation`] and a
/// [`CompletionPort`] need.
///
/// The handle has no position, and every read or write says its offset:
/// see the [module documentation](self#the-synchronous-functions-on-these-handles).
///
/// The file goes through the system's cache, as every file oscall opens
/// does, and on such a file **the system does a read or a write inside
/// the call that starts it**: a write of 256 MB took its 0.7 to 1 s in
/// [`Operation::write`] and was complete when it returned, and no
/// operation on a file was seen pending (measured on x86_64 and aarch64).
/// The completion is queued all the same. What is gained on a file is one
/// way of waiting for files, pipes and sockets, not time.
pub fn open<P: AsPath + ?Sized>(path: &P, options: &OpenOptions) -> Result<OwnedHandle> {
    options.check()?;
    crate::sys::fs::open_with(
        path.as_path_bytes(),
        options,
        crate::sys::fs::FILE_FLAG_OVERLAPPED,
    )
}

/// Creates a pipe as [`io::pipe`](crate::io::pipe) does, both ends of
/// which are open for overlapped operation: the read end, then the write
/// end. They are private to the process.
///
/// The pipes of `CreatePipe` cannot be: this one is a named pipe of a
/// single instance, under a name of the process and of random bits, to
/// which the write end is connected (as `std` does for the pipes of a
/// child process). What [`io`](crate::io) does with a pipe works on it,
/// with one exception: the read end cannot be made
/// [non-blocking](crate::io::set_nonblocking), a change of mode the system
/// gives it no right to
/// ([`PermissionDenied`](ErrorKind::PermissionDenied)). The write end can.
pub fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
    sys::pipe()
}

/// An I/O completion port: the queue to which the operations of the
/// handles [associated](Self::associate) with it report.
///
/// It is `Send` and `Sync`: any thread may associate, post and wait, and
/// several may wait at once, each completion going to one of them (the
/// system wakes the thread that waited last, and as many at a time as
/// there are processors). Dropping it closes the port; the handles are
/// untouched, and their operations then complete without being told to
/// anybody.
pub struct CompletionPort(OwnedHandle);

/// What a [`CompletionPort`] reports: an operation that completed, or what
/// [`CompletionPort::post`] queued.
///
/// It is the system's own structure (`OVERLAPPED_ENTRY`), which a slice of
/// is filled by the system directly. It holds numbers only.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Completion(OverlappedEntry);

// SAFETY: the pointer of the entry is a number here: it is never
// dereferenced.
unsafe impl Send for Completion {}
// SAFETY: as above.
unsafe impl Sync for Completion {}

impl Completion {
    /// A completion that says nothing, to make the buffer
    /// [`CompletionPort::wait`] fills.
    pub const EMPTY: Self = Self(OverlappedEntry::EMPTY);

    /// The key the handle of the operation was
    /// [associated](CompletionPort::associate) with, or the one given to
    /// [`post`](CompletionPort::post).
    #[inline]
    pub fn key(&self) -> usize {
        self.0.key
    }

    /// The number of the operation ([`Operation::id`]: the address of its
    /// `OVERLAPPED`), or the one given to [`post`](CompletionPort::post).
    ///
    /// The operation may be gone, and its number reused: see the
    /// [module documentation](self#whose-memory-it-is).
    #[inline]
    pub fn id(&self) -> usize {
        self.0.overlapped.addr()
    }

    /// How many bytes the operation transferred, or the count given to
    /// [`post`](CompletionPort::post).
    #[inline]
    pub fn bytes(&self) -> u32 {
        self.0.bytes
    }

    /// The status of the operation as the system reports it, an
    /// `NTSTATUS`: negative for a failure, 0 for what was posted.
    #[inline]
    pub fn status(&self) -> i32 {
        self.0.internal as i32
    }

    /// The outcome of the operation: the count of bytes, or its error (the
    /// Win32 code of its status, as everywhere in oscall).
    ///
    /// A message of a pipe that was longer than the buffer is not a
    /// failure: its start was read, and the rest is for the next read.
    pub fn result(&self) -> Result<usize> {
        outcome(self.status(), self.0.bytes as usize)
    }
}

impl Default for Completion {
    fn default() -> Self {
        Self::EMPTY
    }
}

impl fmt::Debug for Completion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Completion")
            .field("key", &self.key())
            .field("id", &self.id())
            .field("result", &self.result())
            .finish()
    }
}

/// The buffer was too small for a whole message: it holds the start of it.
const STATUS_BUFFER_OVERFLOW: i32 = 0x8000_0005u32 as i32;

fn outcome(status: i32, bytes: usize) -> Result<usize> {
    if status >= 0 || status == STATUS_BUFFER_OVERFLOW {
        Ok(bytes)
    } else {
        Err(sys::status_error(status))
    }
}

impl CompletionPort {
    /// Creates a port with nothing associated.
    ///
    /// `CreateIoCompletionPort`. The handle is not inheritable.
    pub fn new() -> Result<Self> {
        sys::port_new().map(Self)
    }

    /// Associates `handle` with the port: from now on every overlapped
    /// operation that completes on it queues a [`Completion`] with `key`,
    /// which is any number the caller likes.
    ///
    /// The association is the handle's for as long as it lives (its
    /// [duplicates](crate::io::duplicate) share it), and it has one:
    /// fails with [`InvalidInput`](ErrorKind::InvalidInput) for a handle
    /// that is associated already, or that is not open for overlapped
    /// operation (see [`open`] and [`pipe`]).
    pub fn associate(&self, handle: impl AsHandle, key: usize) -> Result<()> {
        sys::port_associate(self.0.as_handle(), handle.as_handle().as_raw(), key)
    }

    /// [`associate`](Self::associate) for a socket. Every socket of
    /// [`net`](crate::net) is open for overlapped operation.
    ///
    /// This does not get in the way of an
    /// [`event::Poller`](crate::event::Poller) the socket is registered
    /// with, which works through handles of its own.
    pub fn associate_socket(&self, socket: impl AsSocket, key: usize) -> Result<()> {
        let socket = socket.as_socket().as_raw();
        sys::port_associate(self.0.as_handle(), socket as *mut _, key)
    }

    /// Queues a [`Completion`] made of the three numbers given, which no
    /// operation stands behind: the way to wake a thread that waits, or to
    /// hand it work. Its status is 0.
    ///
    /// `PostQueuedCompletionStatus`.
    pub fn post(&self, key: usize, id: usize, bytes: u32) -> Result<()> {
        sys::port_post(self.0.as_handle(), key, id, bytes)
    }

    /// Waits until the port has completions or `timeout` passes. They are
    /// written at the start of `completions` and their count is returned:
    /// zero means the timeout passed.
    ///
    /// At most `completions.len()` are taken; the others stay queued. An
    /// empty buffer fails with [`InvalidInput`](ErrorKind::InvalidInput).
    /// Completions come in the order operations completed, which is not
    /// the order they were started in.
    ///
    /// `timeout` is measured on the clock
    /// [`Clock::Monotonic`](crate::time::Clock::Monotonic) reads, and never
    /// ends early; `None` waits for as long as it takes, zero only takes
    /// what is there.
    ///
    /// `GetQueuedCompletionStatusEx`, called again for the time that is
    /// left when it gives up before the timeout (it counts in timer
    /// ticks).
    pub fn wait(&self, completions: &mut [Completion], timeout: Option<Duration>) -> Result<usize> {
        if completions.is_empty() {
            return Err(ErrorKind::InvalidInput.into());
        }
        // SAFETY: `Completion` is a transparent wrapper of the entry.
        let entries = unsafe {
            core::slice::from_raw_parts_mut(
                completions.as_mut_ptr().cast::<OverlappedEntry>(),
                completions.len(),
            )
        };
        sys::port_wait(self.0.as_handle(), entries, timeout)
    }
}

impl AsHandle for CompletionPort {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        self.0.as_handle()
    }
}

impl fmt::Debug for CompletionPort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("CompletionPort").field(&self.0).finish()
    }
}

/// Opens a file as [`open`] does, for overlapped operation **without the
/// system's cache** (`FILE_FLAG_NO_BUFFERING`): the one kind of file whose
/// reads and writes the system really does later. See the
/// [module documentation](self#files-without-the-cache) for what was
/// measured of that.
///
/// The price is in what an operation may ask:
///
/// - its offset and its length are multiples of the size of a sector of
///   the volume ([`sector_size`]: 512 or 4096 bytes on the disks of
///   today). A read may come back short at the end of the file; a file
///   whose length is not such a multiple is written whole sectors and
///   then cut ([`fs::set_len`](crate::fs::set_len));
/// - its memory starts at an address that is a multiple of that size too,
///   which a `Vec<u8>` does not promise: whole pages do
///   ([`mem::map_anonymous`](crate::mem::map_anonymous)), given to
///   `Operation::read_kept`, `Operation::write_kept`,
///   `Operation::read_scatter` or `Operation::write_gather`.
///
/// What breaks a rule is refused when the operation is started
/// ([`InvalidInput`](ErrorKind::InvalidInput)). The synchronous functions
/// of [`io`](crate::io) work on the handle under the same rules.
pub fn open_unbuffered<P: AsPath + ?Sized>(path: &P, options: &OpenOptions) -> Result<OwnedHandle> {
    options.check()?;
    crate::sys::fs::open_with(
        path.as_path_bytes(),
        options,
        crate::sys::fs::FILE_FLAG_OVERLAPPED | crate::sys::fs::FILE_FLAG_NO_BUFFERING,
    )
}

/// The size in bytes of a sector of the volume the file of `handle` is
/// on: what the offsets, the lengths and the addresses of the operations
/// on a file opened by [`open_unbuffered`] are multiples of.
///
/// `NtQueryVolumeInformationFile`, as `GetDiskFreeSpaceW` does.
pub fn sector_size(handle: impl AsHandle) -> Result<usize> {
    crate::sys::fs::sector_size(handle.as_handle()).map(|size| size as usize)
}

flags! {
    /// What the system leaves out when an operation completes on a
    /// handle: see [`set_completion_modes`].
    pub struct CompletionModes: u32 {
        /// An operation that is complete when the call that starts it
        /// returns queues no completion to the port of the handle
        /// (`FILE_SKIP_COMPLETION_PORT_ON_SUCCESS`): its outcome is
        /// there at once, and `Operation::completed_at_start` says so.
        const SKIP_PORT_ON_SUCCESS = 1;
        /// The handle itself is not signalled when an operation
        /// completes on it (`FILE_SKIP_SET_EVENT_ON_HANDLE`), which
        /// saves the system a little for every operation. An
        /// `Operation` has an event of its own and loses nothing.
        const SKIP_EVENT_ON_HANDLE = 2;
    }
}

/// Sets what the system leaves out when an operation completes on
/// `handle`, **for as long as the handle lives**: a mode that was set
/// cannot be cleared, and setting others adds to it.
///
/// With [`SKIP_PORT_ON_SUCCESS`](CompletionModes::SKIP_PORT_ON_SUCCESS) a
/// program that waits on a port must look at every operation it starts:
/// one that completed at once is told by nothing but
/// `Operation::completed_at_start`, and its outcome is there to take. See
/// the [module documentation](self#operations-that-are-over-at-once).
///
/// With [`SKIP_EVENT_ON_HANDLE`](CompletionModes::SKIP_EVENT_ON_HANDLE)
/// the synchronous functions of [`io`](crate::io) still work on the
/// handle, and learn that an operation of theirs that had to wait is over
/// by looking at intervals, of a millisecond to twenty, rather than by
/// being told: a read that waited 100 ms for its data returned 0.2 to
/// 27 ms after it (measured).
///
/// Fails with [`InvalidInput`](ErrorKind::InvalidInput) for a handle that
/// is not open for overlapped operation.
///
/// `SetFileCompletionNotificationModes`.
pub fn set_completion_modes(handle: impl AsHandle, modes: CompletionModes) -> Result<()> {
    sys::set_completion_modes(handle.as_handle().as_raw(), modes.bits() as u8)
}

/// [`set_completion_modes`] for a socket.
pub fn set_socket_completion_modes(socket: impl AsSocket, modes: CompletionModes) -> Result<()> {
    let socket = socket.as_socket().as_raw();
    sys::set_completion_modes(socket as *mut _, modes.bits() as u8)
}

/// How a named pipe is created or opened: see [`pipe_server`] and
/// [`pipe_client`].
///
/// ```
/// use oscall::io::windows::PipeOptions;
///
/// // Both ways, in whole messages, and the first of its name.
/// const OPTIONS: PipeOptions = PipeOptions::new()
///     .read(true)
///     .write(true)
///     .message(true)
///     .first_instance(true);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PipeOptions {
    read: bool,
    write: bool,
    message: bool,
    first: bool,
    remote: bool,
    instances: u8,
    buffer: u32,
}

impl PipeOptions {
    /// Options that open nothing yet: at least one of
    /// [`read`](Self::read) and [`write`](Self::write) must be set.
    #[inline]
    pub const fn new() -> Self {
        Self {
            read: false,
            write: false,
            message: false,
            first: false,
            remote: false,
            instances: 0,
            buffer: 64 * 1024,
        }
    }

    /// Whether this end reads from the pipe. For a server that is the
    /// direction of every instance of the pipe (`PIPE_ACCESS_INBOUND`):
    /// a client opens the other one, or both for a pipe that goes both
    /// ways.
    #[inline]
    pub const fn read(mut self, read: bool) -> Self {
        self.read = read;
        self
    }

    /// Whether this end writes to the pipe (`PIPE_ACCESS_OUTBOUND` for a
    /// server).
    #[inline]
    pub const fn write(mut self, write: bool) -> Self {
        self.write = write;
        self
    }

    /// Whether the pipe carries messages rather than a stream of bytes:
    /// each write is one message, and a read takes one message, or the
    /// start of it if the buffer is shorter, the rest being for the next
    /// read. Without it a pipe is a stream, like any other.
    ///
    /// For a server, `PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE`, which
    /// every instance of the pipe must agree on. A client that reads
    /// sets its own end to read whole messages
    /// (`SetNamedPipeHandleState`), which the pipe must have been created
    /// to carry ([`InvalidInput`](ErrorKind::InvalidInput) otherwise).
    #[inline]
    pub const fn message(mut self, message: bool) -> Self {
        self.message = message;
        self
    }

    /// For a server: fail with
    /// [`PermissionDenied`](ErrorKind::PermissionDenied) if the pipe
    /// exists already (`FILE_FLAG_FIRST_PIPE_INSTANCE`). A server that
    /// creates its pipe asks for this, so as not to become one more
    /// instance of a pipe somebody else made under its name.
    #[inline]
    pub const fn first_instance(mut self, first: bool) -> Self {
        self.first = first;
        self
    }

    /// For a server: how many instances the pipe may have at a time, from
    /// 1 to 254, or 0 for as many as the system has room for, which is
    /// the default. Every instance must say the same. Creating one more
    /// fails with [`ResourceBusy`](ErrorKind::ResourceBusy)
    /// (`ERROR_PIPE_BUSY`).
    #[inline]
    pub const fn instances(mut self, instances: u8) -> Self {
        self.instances = instances;
        self
    }

    /// For a server: whether clients on other machines may connect.
    /// Unless this is set they are refused
    /// (`PIPE_REJECT_REMOTE_CLIENTS`).
    #[inline]
    pub const fn accept_remote(mut self, remote: bool) -> Self {
        self.remote = remote;
        self
    }

    /// For a server: the size in bytes the system is asked to give the
    /// buffers of the instance, in each direction; 64 KiB by default. A
    /// write of more than fits waits for the reader.
    #[inline]
    pub const fn buffer_size(mut self, bytes: u32) -> Self {
        self.buffer = bytes;
        self
    }

    fn settings(&self) -> Result<sys::PipeSettings> {
        if !(self.read || self.write) {
            return Err(ErrorKind::InvalidInput.into());
        }
        Ok(sys::PipeSettings {
            read: self.read,
            write: self.write,
            message: self.message,
            first: self.first,
            remote: self.remote,
            instances: self.instances,
            buffer: self.buffer,
        })
    }
}

impl Default for PipeOptions {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Creates an instance of the named pipe `name`, the first or one more,
/// and returns the server's end of it, open for overlapped operation and
/// private to the process.
///
/// `name` is the whole name, `\\.\pipe\` and what the program chose: up
/// to 256 characters in all, without a backslash after the prefix. Pipes
/// live in a namespace of their own, not in a directory, and a pipe is
/// gone when the last handle of its last instance is closed.
///
/// An instance serves one client at a time: it waits for one
/// (`Operation::connect_pipe`), is read and written like any pipe, and is
/// made ready for the next ([`disconnect_pipe`]) or closed. A server that
/// talks to several clients at once creates an instance for each.
///
/// The pipe has the access list the system gives by default: by
/// Microsoft's documentation, its creator, the administrators and the
/// system may do everything, and everyone may read from it.
///
/// Fails with [`InvalidInput`](ErrorKind::InvalidInput) for options that
/// neither read nor write. `CreateNamedPipeW`.
pub fn pipe_server<P: AsPath + ?Sized>(name: &P, options: &PipeOptions) -> Result<OwnedHandle> {
    let settings = options.settings()?;
    crate::path::with_wide(name.as_path_bytes(), |name| {
        sys::pipe_server(name, settings)
    })
}

/// Opens the client's end of the named pipe `name`, for overlapped
/// operation and private to the process: it is connected when this
/// returns.
///
/// Fails with [`NotFound`](ErrorKind::NotFound) if there is no such pipe,
/// and with [`ResourceBusy`](ErrorKind::ResourceBusy) (`ERROR_PIPE_BUSY`)
/// if every instance of it has a client, or is not waiting for one:
/// [`wait_pipe`] waits until one is.
///
/// The server may learn who the client is and may not act in its name
/// (`SECURITY_IDENTIFICATION`), which is not what `CreateFileW` gives a
/// client by default.
///
/// `CreateFileW`.
pub fn pipe_client<P: AsPath + ?Sized>(name: &P, options: &PipeOptions) -> Result<OwnedHandle> {
    let settings = options.settings()?;
    crate::path::with_wide(name.as_path_bytes(), |name| {
        sys::pipe_client(name, settings)
    })
}

/// Waits until an instance of the named pipe `name` waits for a client,
/// or `timeout` passes: whether one does. `None` waits for as long as it
/// takes.
///
/// It is a hint: another client may take the instance before
/// [`pipe_client`] is called, which then fails as before. Fails with
/// [`NotFound`](ErrorKind::NotFound) if there is no such pipe.
///
/// This blocks the calling thread, and counts in milliseconds: a timeout
/// of less than one is one. `timeout` is measured on the clock
/// [`Clock::Monotonic`](crate::time::Clock::Monotonic) reads, and never
/// ends early.
///
/// `WaitNamedPipeW`, called again for the time that is left when it gives
/// up before the timeout, which it does.
pub fn wait_pipe<P: AsPath + ?Sized>(name: &P, timeout: Option<Duration>) -> Result<bool> {
    crate::path::with_wide(name.as_path_bytes(), |name| sys::wait_pipe(name, timeout))
}

/// Ends the connection of the server's end `server` of a named pipe: its
/// client, if it still has the pipe open, finds it not connected
/// ([`NotConnected`](ErrorKind::NotConnected)), and what was written and
/// not read is lost.
///
/// The instance then takes no client, to whom the pipe is busy, until the
/// server waits for one again (`Operation::connect_pipe`): see the
/// [module documentation](self#named-pipes).
///
/// `DisconnectNamedPipe`.
pub fn disconnect_pipe(server: impl AsHandle) -> Result<()> {
    sys::disconnect_pipe(server.as_handle().as_raw())
}

flags! {
    /// Which changes a watch of a directory is told of: see
    /// `Operation::watch`.
    pub struct Watch: u32 {
        /// Files that are created, removed or renamed
        /// (`FILE_NOTIFY_CHANGE_FILE_NAME`).
        const FILE_NAMES = 0x1;
        /// Directories that are created, removed or renamed
        /// (`FILE_NOTIFY_CHANGE_DIR_NAME`).
        const DIR_NAMES = 0x2;
        /// Attributes that change (`FILE_NOTIFY_CHANGE_ATTRIBUTES`).
        const ATTRIBUTES = 0x4;
        /// Sizes that change, as the system comes to write them
        /// (`FILE_NOTIFY_CHANGE_SIZE`).
        const SIZE = 0x8;
        /// Times of last write that change
        /// (`FILE_NOTIFY_CHANGE_LAST_WRITE`).
        const LAST_WRITE = 0x10;
        /// Times of last access that change
        /// (`FILE_NOTIFY_CHANGE_LAST_ACCESS`).
        const LAST_ACCESS = 0x20;
        /// Times of creation that change
        /// (`FILE_NOTIFY_CHANGE_CREATION`).
        const CREATION = 0x40;
        /// Owners and access lists that change
        /// (`FILE_NOTIFY_CHANGE_SECURITY`).
        const SECURITY = 0x100;
    }
}

/// What happened to a file or a directory in a watched directory: see
/// [`Change`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChangeKind {
    /// It was created, or moved into the directory.
    Added,
    /// It was removed, or moved out of the directory.
    Removed,
    /// Its data, its attributes or its times changed.
    Modified,
    /// It was renamed: this is the name it had. The name it has now
    /// follows.
    RenamedFrom,
    /// It was renamed: this is the name it has now.
    RenamedTo,
}

/// One change in a watched directory: see `Operation::changes`.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Change<'a> {
    kind: ChangeKind,
    name: &'a [u16],
}

impl<'a> Change<'a> {
    /// What happened.
    #[inline]
    pub fn kind(&self) -> ChangeKind {
        self.kind
    }

    /// The name of what changed, relative to the watched directory, in
    /// the UTF-16 of the system and without a NUL: a path with
    /// backslashes for what is in a directory below.
    ///
    /// It may be the short name of a file (`LONGFI~1.TXT`) when the
    /// program that changed it used that.
    #[inline]
    pub fn name_wide(&self) -> &'a [u16] {
        self.name
    }

    /// [`name_wide`](Self::name_wide) as a path oscall takes: UTF-8, or
    /// WTF-8 for a name that is not valid UTF-16.
    #[cfg(feature = "alloc")]
    pub fn name(&self) -> alloc::vec::Vec<u8> {
        let mut name = alloc::vec![0; self.name.len() * 3];
        let len = crate::path::wide_to_wtf8(self.name, &mut name).unwrap_or(0);
        name.truncate(len);
        name
    }
}

impl fmt::Debug for Change<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("Change");
        debug.field("kind", &self.kind);
        struct Name<'a>(&'a [u16]);
        impl fmt::Debug for Name<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("\"")?;
                for unit in char::decode_utf16(self.0.iter().copied()) {
                    let unit = unit.unwrap_or(char::REPLACEMENT_CHARACTER);
                    fmt::Display::fmt(&unit.escape_debug(), f)?;
                }
                f.write_str("\"")
            }
        }
        debug.field("name", &Name(self.name)).finish()
    }
}

/// The changes a watch of a directory was told of: an iterator of
/// [`Change`]s, in the order they happened. See `Operation::changes`.
#[derive(Clone, Debug)]
pub struct Changes<'a> {
    /// The records the system wrote, which are aligned as `u32`s.
    records: &'a [u32],
    /// Where the next record starts, in bytes; past the end when there is
    /// none.
    next: usize,
}

/// The fixed part of `FILE_NOTIFY_INFORMATION`: the offset of the next
/// record, the action and the length of the name in bytes.
const NOTIFY_HEADER: usize = 12;

impl<'a> Iterator for Changes<'a> {
    type Item = Change<'a>;

    fn next(&mut self) -> Option<Change<'a>> {
        loop {
            let bytes = self.records.len() * 4;
            let start = self.next;
            if !start.is_multiple_of(4) || start.checked_add(NOTIFY_HEADER)? > bytes {
                return None;
            }
            let [next, action, name_len] = self.records[start / 4..start / 4 + 3] else {
                return None;
            };
            let name_len = name_len as usize;
            let name_start = start + NOTIFY_HEADER;
            if !name_len.is_multiple_of(2) || name_start.checked_add(name_len)? > bytes {
                return None;
            }
            // The last record says so with an offset of zero.
            self.next = match next as usize {
                0 => usize::MAX,
                next => start.saturating_add(next),
            };
            // SAFETY: the range is within the records, as just checked,
            // and starts at a multiple of four bytes of memory that is
            // aligned as `u32`s: it is aligned for `u16`s, which have no
            // invalid value.
            let name = unsafe {
                let name = self.records.as_ptr().cast::<u8>().add(name_start);
                core::slice::from_raw_parts(name.cast::<u16>(), name_len / 2)
            };
            let kind = match action {
                1 => ChangeKind::Added,
                2 => ChangeKind::Removed,
                3 => ChangeKind::Modified,
                4 => ChangeKind::RenamedFrom,
                5 => ChangeKind::RenamedTo,
                // What this version does not know of is passed over.
                _ => continue,
            };
            return Some(Change { kind, name });
        }
    }
}

#[cfg(feature = "alloc")]
pub use operation::Operation;

#[cfg(feature = "alloc")]
mod operation {
    use alloc::boxed::Box;
    use alloc::vec::Vec;
    use core::ffi::c_void;
    use core::fmt;
    use core::num::NonZeroU32;
    use core::ptr::{self, NonNull};
    use core::time::Duration;

    use super::{Changes, Watch, outcome, sys};
    use crate::net::{Address, AsSocket, OwnedSocket, RawAddr, RecvFlags, SendFlags, UnixAddr};
    use crate::sys::io::{Overlapped, RawIoSlice, STATUS_PENDING};
    use crate::sys::net::{self as sys_net, ACCEPT_ADDR};
    use crate::{AsHandle, Error, ErrorKind, OwnedHandle, Result};

    /// How long a dropped operation is waited for, once cancelled, before
    /// its memory is given up for lost.
    const DROP_PATIENCE: Duration = Duration::from_secs(5);

    /// What an operation was started as, which says what its completion
    /// leaves to do.
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum Kind {
        /// Nothing was started.
        Idle,
        /// Bytes that went one way or the other, or nothing at all:
        /// nothing is left to do.
        Transfer,
        Accept,
        Connect,
        /// The records of the changes in a directory are to be read.
        Watch,
    }

    /// The memory an operation is given to keep.
    enum Memory {
        /// None: the operation has none, or the caller keeps it.
        None,
        One(Vec<u8>),
        Many(Vec<Vec<u8>>),
    }

    /// What the system refers to while an operation runs. It lives on the
    /// heap, at an address that does not change, until no operation is in
    /// flight.
    #[repr(C)]
    struct Inner {
        /// First: its address is the operation's, to the system.
        overlapped: Overlapped,
        /// Signaled by the system when the operation is complete, after it
        /// has written the status.
        event: OwnedHandle,
        kind: Kind,
        /// Whether the call that started the operation returned with the
        /// operation complete.
        at_start: bool,
        /// Whether `finish` has run for the operation that completed.
        finished: bool,
        /// Whether `finish_connect` has told the outcome.
        connect_taken: bool,
        /// The handle or the socket the operation was started on, as the
        /// handle `CancelIoEx` takes.
        target: *mut c_void,
        buf: Vec<u8>,
        /// Whether `buf` is a buffer the caller gave and has not taken
        /// back.
        has_buf: bool,
        /// The buffers of a vectored operation.
        bufs: Vec<Vec<u8>>,
        /// Whether `bufs` are buffers the caller gave and has not taken
        /// back.
        has_bufs: bool,
        /// Whether the system writes the buffers: their length is then
        /// the count.
        fills: bool,
        /// The socket a connection is accepted on.
        socket: Option<OwnedSocket>,
        /// What finishing an accept or a connect failed with.
        finish_error: Option<Error>,
        /// Where `AcceptEx` writes the two addresses.
        addresses: [u8; 2 * ACCEPT_ADDR],
        /// The address a datagram goes to, or where the system writes the
        /// one it came from, and its length, when the operation
        /// completes.
        addr: RawAddr,
        /// Whether `addr` is for the system to write.
        has_source: bool,
        /// The pages of a scattered read or a gathered write, and a zero.
        segments: Vec<u64>,
        /// Where the system writes the changes in a directory: records
        /// that are aligned as `u32`s.
        records: Vec<u32>,
    }

    /// The memory of one overlapped operation at a time, and the means to
    /// start it, to know its outcome and to cancel it. See the
    /// [module documentation](super#whose-memory-it-is).
    ///
    /// An `Operation` is made once and used again and again: starting an
    /// operation takes `&mut self` and fails with
    /// [`ResourceBusy`](ErrorKind::ResourceBusy) while the previous one is
    /// in flight. It holds one event and one allocation for its lifetime.
    ///
    /// The handle an operation is started on is not borrowed: it should
    /// stay open until the operation is complete, or the `Operation` may
    /// not be able to cancel it when dropped, and then waits for it.
    /// (Closing the last handle of a pipe or of a socket ends its
    /// operations by itself.)
    ///
    /// An operation is cancelled by the system if the thread that started
    /// it ends first: see the
    /// [module documentation](super#what-a-port-tells-and-what-it-does-not).
    pub struct Operation(NonNull<Inner>);

    // SAFETY: the memory is owned, and the system does not care which
    // thread started an operation or looks at it.
    unsafe impl Send for Operation {}
    // SAFETY: what `&self` gives is reads of a status the system writes
    // once and of what it wrote before that, and a request to cancel.
    unsafe impl Sync for Operation {}

    impl Operation {
        /// Makes an operation that has not started anything.
        ///
        /// `CreateEventW`, for the event that tells when an operation is
        /// over.
        pub fn new() -> Result<Self> {
            let event = sys::event_new()?;
            let inner = Box::new(Inner {
                overlapped: Overlapped {
                    internal: 0,
                    internal_high: 0,
                    offset: 0,
                    offset_high: 0,
                    event: event.as_raw(),
                },
                event,
                kind: Kind::Idle,
                at_start: false,
                finished: false,
                connect_taken: false,
                target: ptr::null_mut(),
                buf: Vec::new(),
                has_buf: false,
                bufs: Vec::new(),
                has_bufs: false,
                fills: false,
                socket: None,
                finish_error: None,
                addresses: [0; 2 * ACCEPT_ADDR],
                addr: RawAddr::new(),
                has_source: false,
                segments: Vec::new(),
                records: Vec::new(),
            });
            Ok(Self(NonNull::from(Box::leak(inner))))
        }

        /// The number that names this operation in a
        /// [`Completion`](super::Completion): the address of its
        /// `OVERLAPPED`, which is the same for as long as the `Operation`
        /// lives.
        #[inline]
        pub fn id(&self) -> usize {
            self.0.as_ptr().addr()
        }

        fn overlapped(&self) -> *mut Overlapped {
            // The structure is the first member.
            self.0.as_ptr().cast()
        }

        /// The status of the operation, which the system writes when it
        /// completes.
        fn status(&self) -> i32 {
            // SAFETY: the allocation lives; the system writes the status
            // from outside of what the compiler sees.
            (unsafe { ptr::read_volatile(&raw const (*self.overlapped()).internal) }) as i32
        }

        fn kind(&self) -> Kind {
            // SAFETY: the allocation lives, and the system knows nothing
            // of this member.
            unsafe { (*self.0.as_ptr()).kind }
        }

        /// Whether an operation was started and is not complete yet: the
        /// system may still write to the buffer.
        #[inline]
        pub fn is_pending(&self) -> bool {
            self.kind() != Kind::Idle && self.status() == STATUS_PENDING
        }

        /// Whether the operation was complete when the call that started
        /// it returned: `false` for one that had to wait, and when
        /// nothing was started.
        ///
        /// It matters for a handle that was told to skip its port for
        /// such operations
        /// ([`SKIP_PORT_ON_SUCCESS`](super::CompletionModes::SKIP_PORT_ON_SUCCESS)):
        /// no completion is queued for them, and whoever started the
        /// operation deals with its outcome there and then. On any other
        /// handle the completion comes whatever this says. Unlike
        /// [`is_pending`](Self::is_pending) it does not change while the
        /// operation runs: an operation that was pending when the call
        /// returned, and is over an instant later, has its completion
        /// queued.
        #[inline]
        pub fn completed_at_start(&self) -> bool {
            // SAFETY: the allocation lives, and the system knows nothing
            // of these members.
            self.kind() != Kind::Idle && unsafe { (*self.0.as_ptr()).at_start }
        }

        /// What the system does not touch, for an operation that is not
        /// in flight.
        fn idle(&mut self) -> Result<&mut Inner> {
            if self.is_pending() {
                return Err(ErrorKind::ResourceBusy.into());
            }
            // SAFETY: nothing is in flight: the system has no use of the
            // allocation, and `self` is borrowed mutably.
            Ok(unsafe { self.0.as_mut() })
        }

        /// Gets ready to start an operation on `target`, with the memory
        /// it is given to keep.
        fn prepare(&mut self, target: *mut c_void, memory: Memory) -> Result<&mut Inner> {
            let inner = self.idle()?;
            inner.kind = Kind::Idle;
            inner.at_start = false;
            inner.finished = false;
            inner.connect_taken = false;
            inner.finish_error = None;
            inner.socket = None;
            inner.fills = false;
            inner.has_source = false;
            (inner.has_buf, inner.has_bufs) = match memory {
                Memory::None => {
                    inner.buf = Vec::new();
                    inner.bufs = Vec::new();
                    (false, false)
                }
                Memory::One(buf) => {
                    inner.buf = buf;
                    inner.bufs = Vec::new();
                    (true, false)
                }
                Memory::Many(bufs) => {
                    inner.buf = Vec::new();
                    inner.bufs = bufs;
                    (false, true)
                }
            };
            inner.target = target;
            inner.overlapped.internal = STATUS_PENDING as usize;
            inner.overlapped.internal_high = 0;
            inner.overlapped.offset = 0;
            inner.overlapped.offset_high = 0;
            Ok(inner)
        }

        /// Records that the operation of `kind` was started, complete
        /// already or not, or that it was not started.
        fn started(&mut self, kind: Kind, started: Result<bool>) -> Result<()> {
            let inner = self.0.as_ptr();
            // SAFETY: only these members are touched, which the system
            // knows nothing of.
            unsafe {
                match started {
                    Ok(at_start) => {
                        (*inner).at_start = at_start;
                        (*inner).kind = kind;
                        Ok(())
                    }
                    Err(error) => {
                        (*inner).kind = Kind::Idle;
                        (*inner).fills = false;
                        Err(error)
                    }
                }
            }
        }

        fn started_status(&mut self, kind: Kind, status: i32) -> Result<()> {
            let started = if sys::failed_to_start(status) {
                Err(sys::status_error(status))
            } else {
                Ok(status != STATUS_PENDING)
            };
            self.started(kind, started)
        }

        /// Starts reading from `handle` into `buf`: up to its capacity,
        /// replacing what it holds. `offset` is where in the file, and
        /// `None` for a handle that has no positions (a pipe).
        ///
        /// Once the operation is complete, [`result`](Self::result) has
        /// the count and [`take_buffer`](Self::take_buffer) the buffer,
        /// whose length is that count.
        ///
        /// The end is an error here, as it is to the system: reading at or
        /// past the end of a file fails with the code of
        /// `ERROR_HANDLE_EOF` (38), and reading a pipe whose write end is
        /// closed with [`BrokenPipe`](ErrorKind::BrokenPipe), either at
        /// once or as the outcome of the operation.
        ///
        /// On an error nothing was started, no completion will come, and
        /// the buffer can be taken back. Fails with
        /// [`ResourceBusy`](ErrorKind::ResourceBusy) if the previous
        /// operation is still in flight, and then leaves `buf` to be
        /// dropped.
        ///
        /// On a handle that is not open for overlapped operation this is a
        /// plain read: it is complete when the call returns.
        ///
        /// `NtReadFile`, which `ReadFile` is made of.
        pub fn read(
            &mut self,
            handle: impl AsHandle,
            mut buf: Vec<u8>,
            offset: Option<u64>,
        ) -> Result<()> {
            let handle = handle.as_handle().as_raw();
            let offset = file_offset(offset)?;
            buf.clear();
            let inner = self.prepare(handle, Memory::One(buf))?;
            inner.fills = true;
            let (ptr, len) = (inner.buf.as_mut_ptr(), len32(inner.buf.capacity()));
            // SAFETY: the structure and the buffer are owned by the
            // allocation, which lives until the operation is complete.
            let status = unsafe { sys::read(handle, self.overlapped(), ptr, len, offset) };
            self.started_status(Kind::Transfer, status)
        }

        /// [`read`](Self::read) into memory the caller keeps: up to `len`
        /// bytes at `ptr` (at most `u32::MAX` of them at once). There is
        /// no buffer to take back; the outcome is the count of bytes the
        /// system wrote there.
        ///
        /// # Safety
        ///
        /// The `len` bytes at `ptr` must be writable, and nothing else may
        /// read or write them, from this call until the operation is
        /// complete: until [`is_pending`](Self::is_pending) is false, or
        /// this returned an error. Dropping the `Operation` does not end
        /// that: dropped in flight it cancels its operation and waits for
        /// it, but for a few seconds only (see the
        /// [module documentation](super#whose-memory-it-is)), after which
        /// the system may still write. Memory that can go away is waited
        /// for with [`wait`](Self::wait) first.
        pub unsafe fn read_kept(
            &mut self,
            handle: impl AsHandle,
            ptr: *mut u8,
            len: usize,
            offset: Option<u64>,
        ) -> Result<()> {
            let handle = handle.as_handle().as_raw();
            let offset = file_offset(offset)?;
            self.prepare(handle, Memory::None)?;
            // SAFETY: the structure is owned by the allocation, which
            // lives until the operation is complete; the memory is the
            // caller's to keep until then.
            let status = unsafe { sys::read(handle, self.overlapped(), ptr, len32(len), offset) };
            self.started_status(Kind::Transfer, status)
        }

        /// Starts writing `buf` to `handle`, at `offset` in a file (the
        /// end of it, whatever the offset, for one opened for appending),
        /// with `None` for a handle that has no positions.
        ///
        /// The outcome is the count of bytes written. Errors are as for
        /// [`read`](Self::read).
        ///
        /// `NtWriteFile`, which `WriteFile` is made of.
        pub fn write(
            &mut self,
            handle: impl AsHandle,
            buf: Vec<u8>,
            offset: Option<u64>,
        ) -> Result<()> {
            let handle = handle.as_handle().as_raw();
            let offset = file_offset(offset)?;
            let inner = self.prepare(handle, Memory::One(buf))?;
            let (ptr, len) = (inner.buf.as_ptr(), len32(inner.buf.len()));
            // SAFETY: as in `read`.
            let status = unsafe { sys::write(handle, self.overlapped(), ptr, len, offset) };
            self.started_status(Kind::Transfer, status)
        }

        /// [`write`](Self::write) from memory the caller keeps: the `len`
        /// bytes at `ptr`.
        ///
        /// # Safety
        ///
        /// The `len` bytes at `ptr` must be readable, and nothing may
        /// write them, from this call until the operation is complete, as
        /// for [`read_kept`](Self::read_kept).
        pub unsafe fn write_kept(
            &mut self,
            handle: impl AsHandle,
            ptr: *const u8,
            len: usize,
            offset: Option<u64>,
        ) -> Result<()> {
            let handle = handle.as_handle().as_raw();
            let offset = file_offset(offset)?;
            self.prepare(handle, Memory::None)?;
            // SAFETY: as in `read_kept`.
            let status = unsafe { sys::write(handle, self.overlapped(), ptr, len32(len), offset) };
            self.started_status(Kind::Transfer, status)
        }

        /// The addresses of `pages` as the system takes them, ended by a
        /// zero, in memory that lives as long as the operation; and how
        /// many bytes they are.
        fn segments(
            &mut self,
            handle: *mut c_void,
            pages: impl ExactSizeIterator<Item = usize>,
        ) -> Result<(*const u64, u32)> {
            let count = pages.len();
            let len = count
                .checked_mul(crate::mem::page_size())
                .and_then(|len| u32::try_from(len).ok())
                .filter(|&len| len != 0)
                .ok_or(ErrorKind::InvalidInput)?;
            let inner = self.prepare(handle, Memory::None)?;
            inner.segments.clear();
            inner
                .segments
                .try_reserve(count + 1)
                .map_err(|_| ErrorKind::OutOfMemory)?;
            // An address is a number to the system, which is given it as
            // one, zero-extended.
            inner.segments.extend(pages.map(|page| page as u64));
            inner.segments.push(0);
            Ok((inner.segments.as_ptr(), len))
        }

        /// Starts reading from the file of `handle`, at `offset`, into
        /// the pages at `pages`, one after the other: as many whole pages
        /// ([`mem::page_size`](crate::mem::page_size)) as there are
        /// addresses, each of which is the start of a page. The outcome
        /// is the count of bytes read.
        ///
        /// **The file must have been opened without the system's cache**
        /// ([`open_unbuffered`](super::open_unbuffered)), whose rules
        /// apply: an offset that is a multiple of the size of a sector.
        /// On any other handle, and for no page or more than `u32::MAX`
        /// bytes of them, this fails with
        /// [`InvalidInput`](ErrorKind::InvalidInput).
        ///
        /// `ReadFileScatter` (`NtReadFileScatter`).
        ///
        /// # Safety
        ///
        /// Every address of `pages` must be the start of a page that is
        /// writable, and that nothing else reads or writes, from this
        /// call until the operation is complete, as for
        /// [`read_kept`](Self::read_kept).
        pub unsafe fn read_scatter(
            &mut self,
            handle: impl AsHandle,
            pages: &[*mut u8],
            offset: u64,
        ) -> Result<()> {
            let handle = handle.as_handle().as_raw();
            let offset = i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput)?;
            let pages = pages.iter().map(|page| page.expose_provenance());
            let (segments, len) = self.segments(handle, pages)?;
            // SAFETY: the structure and the array of pages are owned by
            // the allocation, which lives until the operation is
            // complete; the pages are the caller's to keep until then.
            let status =
                unsafe { sys::read_scatter(handle, self.overlapped(), segments, len, offset) };
            self.started_status(Kind::Transfer, status)
        }

        /// Starts writing the pages at `pages`, one after the other, to
        /// the file of `handle` at `offset`: the counterpart of
        /// [`read_scatter`](Self::read_scatter), with the same demands.
        ///
        /// `WriteFileGather` (`NtWriteFileGather`).
        ///
        /// # Safety
        ///
        /// Every address of `pages` must be the start of a page that is
        /// readable, and that nothing writes, from this call until the
        /// operation is complete, as for
        /// [`read_kept`](Self::read_kept).
        pub unsafe fn write_gather(
            &mut self,
            handle: impl AsHandle,
            pages: &[*const u8],
            offset: u64,
        ) -> Result<()> {
            let handle = handle.as_handle().as_raw();
            let offset = i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput)?;
            let pages = pages.iter().map(|page| page.expose_provenance());
            let (segments, len) = self.segments(handle, pages)?;
            // SAFETY: as in `read_scatter`.
            let status =
                unsafe { sys::write_gather(handle, self.overlapped(), segments, len, offset) };
            self.started_status(Kind::Transfer, status)
        }

        /// Starts receiving from `socket` into `buf`, as
        /// [`net::recv`](crate::net::recv) does: up to its capacity,
        /// replacing what it holds. The outcome is the count, 0 when the
        /// peer has closed a stream. Of a datagram longer than the
        /// buffer, the start is received and the rest is lost.
        ///
        /// `WSARecv`.
        pub fn recv(
            &mut self,
            socket: impl AsSocket,
            mut buf: Vec<u8>,
            flags: RecvFlags,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            buf.clear();
            let inner = self.prepare(socket as *mut c_void, Memory::One(buf))?;
            inner.fills = true;
            let (ptr, len) = (inner.buf.as_mut_ptr(), len32(inner.buf.capacity()));
            // SAFETY: as in `read`.
            let started = unsafe {
                sys_net::recv_overlapped(socket, ptr, len, flags, self.overlapped().cast())
            };
            self.started(Kind::Transfer, started)
        }

        /// [`recv`](Self::recv) into memory the caller keeps: up to `len`
        /// bytes at `ptr`.
        ///
        /// # Safety
        ///
        /// As [`read_kept`](Self::read_kept).
        pub unsafe fn recv_kept(
            &mut self,
            socket: impl AsSocket,
            ptr: *mut u8,
            len: usize,
            flags: RecvFlags,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            self.prepare(socket as *mut c_void, Memory::None)?;
            // SAFETY: as in `read_kept`.
            let started = unsafe {
                sys_net::recv_overlapped(socket, ptr, len32(len), flags, self.overlapped().cast())
            };
            self.started(Kind::Transfer, started)
        }

        /// The buffers of a vectored operation, as the system takes them:
        /// an array that only the call that starts the operation reads.
        fn slices(bufs: &mut [Vec<u8>], fill: bool) -> Result<Vec<RawIoSlice>> {
            let mut slices = Vec::new();
            slices
                .try_reserve_exact(bufs.len().max(1))
                .map_err(|_| ErrorKind::OutOfMemory)?;
            for buf in bufs {
                let len = if fill { buf.capacity() } else { buf.len() };
                slices.push(RawIoSlice::new(buf.as_mut_ptr(), len));
            }
            if slices.is_empty() {
                // No buffer at all is an empty one, as in `net`.
                slices.push(RawIoSlice::new(ptr::null_mut(), 0));
            }
            Ok(slices)
        }

        /// Starts receiving from `socket` into `bufs`, each filled up to
        /// its capacity before the next is used, as
        /// [`net::recv_vectored`](crate::net::recv_vectored) does. The
        /// outcome is the count of bytes;
        /// [`take_buffers`](Self::take_buffers) hands the buffers back,
        /// with the lengths that count gives them.
        ///
        /// `WSARecv`, with several buffers.
        pub fn recv_vectored(
            &mut self,
            socket: impl AsSocket,
            bufs: Vec<Vec<u8>>,
            flags: RecvFlags,
        ) -> Result<()> {
            self.receive_vectored(socket, bufs, flags, false)
        }

        fn receive_vectored(
            &mut self,
            socket: impl AsSocket,
            mut bufs: Vec<Vec<u8>>,
            flags: RecvFlags,
            source: bool,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            bufs.iter_mut().for_each(Vec::clear);
            let inner = self.prepare(socket as *mut c_void, Memory::Many(bufs))?;
            inner.fills = true;
            inner.has_source = source;
            inner.addr = RawAddr::new();
            let mut slices = Self::slices(&mut inner.bufs, true)?;
            let from = source.then_some(&raw mut inner.addr);
            // SAFETY: the structure, the buffers and the address are owned
            // by the allocation, which lives until the operation is
            // complete; the array of buffers is read by the call.
            let started = unsafe {
                sys_net::recv_vectored_overlapped(
                    socket,
                    slices.as_mut_ptr(),
                    len32(slices.len()),
                    flags,
                    from,
                    self.overlapped().cast(),
                )
            };
            self.started(Kind::Transfer, started)
        }

        /// Starts receiving a datagram from `socket` into `buf`, as
        /// [`net::recv_from`](crate::net::recv_from) does: the outcome is
        /// the count, and [`source`](Self::source) the address it came
        /// from.
        ///
        /// `WSARecvFrom`.
        pub fn recv_from(
            &mut self,
            socket: impl AsSocket,
            mut buf: Vec<u8>,
            flags: RecvFlags,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            buf.clear();
            let inner = self.prepare(socket as *mut c_void, Memory::One(buf))?;
            inner.fills = true;
            inner.has_source = true;
            inner.addr = RawAddr::new();
            let mut slice = RawIoSlice::new(inner.buf.as_mut_ptr(), inner.buf.capacity());
            let from = Some(&raw mut inner.addr);
            // SAFETY: as in `receive_vectored`.
            let started = unsafe {
                sys_net::recv_vectored_overlapped(
                    socket,
                    &raw mut slice,
                    1,
                    flags,
                    from,
                    self.overlapped().cast(),
                )
            };
            self.started(Kind::Transfer, started)
        }

        /// [`recv_vectored`](Self::recv_vectored) for a datagram, with
        /// the address it came from as for
        /// [`recv_from`](Self::recv_from).
        ///
        /// `WSARecvFrom`, with several buffers.
        pub fn recv_from_vectored(
            &mut self,
            socket: impl AsSocket,
            bufs: Vec<Vec<u8>>,
            flags: RecvFlags,
        ) -> Result<()> {
            self.receive_vectored(socket, bufs, flags, true)
        }

        /// The address the datagram of a [`recv_from`](Self::recv_from)
        /// or a [`recv_from_vectored`](Self::recv_from_vectored) came
        /// from: `None` while the operation is in flight, if it failed or
        /// was another kind of operation, and for a socket that is
        /// connected, whose datagrams the system gives no address.
        pub fn source(&self) -> Option<Address> {
            self.result()?.ok()?;
            let inner = self.0.as_ptr();
            // SAFETY: the allocation lives, and the operation is
            // complete: the system has written the address and its
            // length, and writes nothing any more.
            unsafe {
                if !(*inner).has_source {
                    return None;
                }
                let addr: &RawAddr = &(*inner).addr;
                addr.decode()
            }
        }

        /// Starts sending `buf` on `socket`, as
        /// [`net::send`](crate::net::send) does. The outcome is the count
        /// of bytes sent: all of them on a stream, where the operation
        /// completes when the system has taken everything.
        ///
        /// `WSASend`.
        pub fn send(
            &mut self,
            socket: impl AsSocket,
            buf: Vec<u8>,
            flags: SendFlags,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            let inner = self.prepare(socket as *mut c_void, Memory::One(buf))?;
            let (ptr, len) = (inner.buf.as_ptr(), len32(inner.buf.len()));
            // SAFETY: as in `read`.
            let started = unsafe {
                sys_net::send_overlapped(socket, ptr, len, flags, self.overlapped().cast())
            };
            self.started(Kind::Transfer, started)
        }

        /// [`send`](Self::send) from memory the caller keeps: the `len`
        /// bytes at `ptr`.
        ///
        /// # Safety
        ///
        /// As [`write_kept`](Self::write_kept).
        pub unsafe fn send_kept(
            &mut self,
            socket: impl AsSocket,
            ptr: *const u8,
            len: usize,
            flags: SendFlags,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            self.prepare(socket as *mut c_void, Memory::None)?;
            // SAFETY: as in `read_kept`.
            let started = unsafe {
                sys_net::send_overlapped(socket, ptr, len32(len), flags, self.overlapped().cast())
            };
            self.started(Kind::Transfer, started)
        }

        fn transmit_vectored(
            &mut self,
            socket: impl AsSocket,
            bufs: Vec<Vec<u8>>,
            addr: Option<&Address>,
            flags: SendFlags,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            let addr = addr.map(RawAddr::encode).transpose()?;
            let inner = self.prepare(socket as *mut c_void, Memory::Many(bufs))?;
            let slices = Self::slices(&mut inner.bufs, false)?;
            let to = addr.map(|addr| {
                inner.addr = addr;
                &raw const inner.addr
            });
            // SAFETY: as in `receive_vectored`.
            let started = unsafe {
                sys_net::send_vectored_overlapped(
                    socket,
                    slices.as_ptr(),
                    len32(slices.len()),
                    flags,
                    to,
                    self.overlapped().cast(),
                )
            };
            self.started(Kind::Transfer, started)
        }

        /// Starts sending the content of `bufs`, one after the other, on
        /// `socket`, as [`net::send_vectored`](crate::net::send_vectored)
        /// does: as one datagram, on a socket of datagrams.
        /// [`take_buffers`](Self::take_buffers) hands the buffers back.
        ///
        /// `WSASend`, with several buffers.
        pub fn send_vectored(
            &mut self,
            socket: impl AsSocket,
            bufs: Vec<Vec<u8>>,
            flags: SendFlags,
        ) -> Result<()> {
            self.transmit_vectored(socket, bufs, None, flags)
        }

        /// Starts sending `buf` as one datagram to `addr`, as
        /// [`net::send_to`](crate::net::send_to) does.
        ///
        /// `WSASendTo`.
        pub fn send_to(
            &mut self,
            socket: impl AsSocket,
            buf: Vec<u8>,
            addr: &Address,
            flags: SendFlags,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            let addr = RawAddr::encode(addr)?;
            let inner = self.prepare(socket as *mut c_void, Memory::One(buf))?;
            inner.addr = addr;
            let slice = RawIoSlice::new(inner.buf.as_mut_ptr(), inner.buf.len());
            let to = Some(&raw const inner.addr);
            // SAFETY: as in `receive_vectored`.
            let started = unsafe {
                sys_net::send_vectored_overlapped(
                    socket,
                    &raw const slice,
                    1,
                    flags,
                    to,
                    self.overlapped().cast(),
                )
            };
            self.started(Kind::Transfer, started)
        }

        /// Starts sending the content of `bufs` as one datagram to
        /// `addr`, as
        /// [`net::send_to_vectored`](crate::net::send_to_vectored) does.
        ///
        /// `WSASendTo`, with several buffers.
        pub fn send_to_vectored(
            &mut self,
            socket: impl AsSocket,
            bufs: Vec<Vec<u8>>,
            addr: &Address,
            flags: SendFlags,
        ) -> Result<()> {
            self.transmit_vectored(socket, bufs, Some(addr), flags)
        }

        /// Starts sending what the file of `file` holds on `socket`, a
        /// connected stream: `len` bytes from `offset`, or with `None`
        /// everything from `offset` to the end of the file. The outcome
        /// is the count of bytes sent. The system reads the file itself,
        /// through its cache: nothing passes through the program.
        ///
        /// `file` is open for reading, overlapped or not, and **stays
        /// open until the operation is complete**: closed as soon as
        /// this had returned, the operation failed
        /// ([`BadHandle`](ErrorKind::BadHandle)), and on x86_64 the
        /// connection took no other file afterwards (measured). The
        /// position of a handle that has one is not where the file is
        /// read from, and the system moves it all the same, to the end
        /// of what was sent, on most machines and not on all (measured):
        /// it is not to be relied on once the handle was given to this.
        /// From the end of
        /// the file nothing is sent, and the outcome is 0.
        /// By Microsoft's documentation, one call sends at most
        /// 2<sup>31</sup> - 2 bytes, a longer file being sent in parts,
        /// and a system that is not a server runs two of these at a time
        /// and queues the others.
        ///
        /// `TransmitFile`.
        pub fn send_file(
            &mut self,
            socket: impl AsSocket,
            file: impl AsHandle,
            offset: u64,
            len: Option<NonZeroU32>,
        ) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            let file = file.as_handle().as_raw();
            let inner = self.prepare(socket as *mut c_void, Memory::None)?;
            inner.overlapped.offset = offset as u32;
            inner.overlapped.offset_high = (offset >> 32) as u32;
            let len = len.map_or(0, NonZeroU32::get);
            // SAFETY: the structure is owned by the allocation, which
            // lives until the operation is complete.
            let started =
                unsafe { sys_net::transmit_file(socket, file, len, self.overlapped().cast()) };
            self.started(Kind::Transfer, started)
        }

        /// Starts accepting a connection on `listener`. The connection is
        /// accepted *on* `socket`, which the caller makes for the purpose:
        /// a new socket of the listener's family and type, neither bound
        /// nor connected. The operation owns it until
        /// [`take_accepted`](Self::take_accepted) hands it back,
        /// connected.
        ///
        /// On an error nothing was started and `socket` is closed.
        ///
        /// `AcceptEx`.
        pub fn accept(&mut self, listener: impl AsSocket, socket: OwnedSocket) -> Result<()> {
            let listener = listener.as_socket().as_raw();
            let inner = self.prepare(listener as *mut c_void, Memory::None)?;
            let accepting = socket.as_raw();
            inner.socket = Some(socket);
            let output = inner.addresses.as_mut_ptr();
            // SAFETY: the structure and the room for the addresses are
            // owned by the allocation, which lives until the operation is
            // complete, as does the socket.
            let started = unsafe {
                sys_net::accept_overlapped(listener, accepting, output, self.overlapped().cast())
            };
            if started.is_err() {
                // SAFETY: nothing was started: only the system-free
                // members are touched.
                unsafe { (*self.0.as_ptr()).socket = None };
            }
            self.started(Kind::Accept, started)
        }

        /// Starts connecting `socket` to `addr`. The outcome is 0, or the
        /// error.
        ///
        /// **The socket must be bound**, which a connecting socket usually
        /// is not: bind it to the unspecified address of its family and
        /// port 0 first. Otherwise this fails with
        /// [`InvalidInput`](ErrorKind::InvalidInput).
        ///
        /// `ConnectEx`.
        pub fn connect(&mut self, socket: impl AsSocket, addr: &Address) -> Result<()> {
            let socket = socket.as_socket().as_raw();
            let addr = RawAddr::encode(addr)?;
            self.prepare(socket as *mut c_void, Memory::None)?;
            // SAFETY: the structure is owned by the allocation, which
            // lives until the operation is complete; the address is read
            // by the call.
            let started =
                unsafe { sys_net::connect_overlapped(socket, &addr, self.overlapped().cast()) };
            self.started(Kind::Connect, started)
        }

        /// Starts waiting for a client to connect to `server`, an
        /// instance of a named pipe
        /// ([`pipe_server`](super::pipe_server)). The outcome is 0, or
        /// the error.
        ///
        /// `Ok(false)` means that **a client is connected already**:
        /// one that opened the pipe between the creation of the instance
        /// and this call, or the one the instance has had all along.
        /// Nothing was started, no completion will come, and the pipe is
        /// ready to be read and written. `Ok(true)` means the operation
        /// was started, as everywhere else.
        ///
        /// Fails with [`BrokenPipe`](ErrorKind::BrokenPipe)
        /// (`ERROR_NO_DATA`) when a client has connected and gone since:
        /// the instance wants [`disconnect_pipe`](super::disconnect_pipe)
        /// before it waits for another.
        ///
        /// `ConnectNamedPipe`.
        pub fn connect_pipe(&mut self, server: impl AsHandle) -> Result<bool> {
            let server = server.as_handle().as_raw();
            self.prepare(server, Memory::None)?;
            // SAFETY: the structure is owned by the allocation, which
            // lives until the operation is complete.
            let (started, waits) = match unsafe { sys::connect_pipe(server, self.overlapped()) } {
                Ok(sys::PipeConnect::Complete) => (Ok(true), true),
                Ok(sys::PipeConnect::Pending) => (Ok(false), true),
                Ok(sys::PipeConnect::Connected) => (Ok(false), false),
                Err(error) => (Err(error), false),
            };
            let kind = if waits { Kind::Transfer } else { Kind::Idle };
            self.started(kind, started).map(|()| waits)
        }

        /// Starts watching the directory of `directory` for changes: the
        /// operation completes when something that `filter` names has
        /// happened to an entry of the directory, or with `subtree` of
        /// any directory below it. [`changes`](Self::changes) then tells
        /// what, from records the system wrote in a buffer of `capacity`
        /// bytes that the operation makes and keeps.
        ///
        /// `directory` is a directory open for overlapped operation:
        /// [`open`](super::open) with
        /// [`OpenOptions::directory`](crate::fs::OpenOptions::directory).
        /// The system notes what happens to it from the first watch on,
        /// in a buffer of the size of that first watch, for as long as
        /// the handle is open: **what changes between one watch and the
        /// next is told by the next**, which is then complete as soon as
        /// it is started (and was started as pending all the same: its
        /// completion is queued). `filter` and `subtree` are the first
        /// watch's too.
        ///
        /// Changes come in the order they happened, several to a watch
        /// when they came together, and one thing a program does is
        /// often several of them: a file written in a directory below
        /// was told as added, then modified, and on x86_64, not on
        /// aarch64, the directory itself as modified before that.
        ///
        /// **The outcome is the count of bytes of the records, and 0
        /// means that changes were lost**: more happened than the buffer
        /// holds, and the program has to list the directory to know its
        /// state. A record is twelve bytes and the name; a few kilobytes
        /// hold a burst. On a directory of another machine the system
        /// takes at most 64 KiB (by Microsoft's documentation).
        ///
        /// `ReadDirectoryChangesW` (`NtNotifyChangeDirectoryFile`).
        pub fn watch(
            &mut self,
            directory: impl AsHandle,
            capacity: usize,
            filter: Watch,
            subtree: bool,
        ) -> Result<()> {
            let directory = directory.as_handle().as_raw();
            let words = capacity.div_ceil(4);
            let len = words
                .checked_mul(4)
                .and_then(|len| u32::try_from(len).ok())
                .ok_or(ErrorKind::InvalidInput)?;
            let inner = self.prepare(directory, Memory::None)?;
            inner.records.clear();
            inner
                .records
                .try_reserve_exact(words)
                .map_err(|_| ErrorKind::OutOfMemory)?;
            inner.records.resize(words, 0);
            let records = inner.records.as_mut_ptr();
            // SAFETY: the structure and the buffer are owned by the
            // allocation, which lives until the operation is complete.
            let status = unsafe {
                sys::watch(
                    directory,
                    self.overlapped(),
                    records,
                    len,
                    filter.bits(),
                    subtree,
                )
            };
            self.started_status(Kind::Watch, status)
        }

        /// The changes a [`watch`](Self::watch) was told of: `None` while
        /// it is in flight, if it failed, and for another kind of
        /// operation. An iterator of nothing when changes were lost (the
        /// outcome is then 0).
        pub fn changes(&self) -> Option<Changes<'_>> {
            if self.kind() != Kind::Watch {
                return None;
            }
            let bytes = self.result()?.ok()?;
            // SAFETY: the allocation lives, and the operation is
            // complete: the system writes nothing any more, and nothing
            // else does while `self` is borrowed. The system wrote no
            // more than the buffer holds.
            let records = unsafe {
                let records: &Vec<u32> = &(*self.0.as_ptr()).records;
                &records[..bytes.div_ceil(4).min(records.len())]
            };
            Some(Changes { records, next: 0 })
        }

        /// What is left to do once an accept or a connect has completed,
        /// for the socket to be one like any other.
        fn finish(&mut self) {
            let status = self.status();
            let Ok(inner) = self.idle() else { return };
            if inner.finished || inner.kind == Kind::Idle {
                return;
            }
            inner.finished = true;
            if status < 0 {
                return;
            }
            let finished = match inner.kind {
                Kind::Accept => match &inner.socket {
                    Some(socket) => sys_net::accept_finish(inner.target as usize, socket.as_raw()),
                    None => Ok(()),
                },
                Kind::Connect => sys_net::connect_finish(inner.target as usize),
                _ => Ok(()),
            };
            inner.finish_error = finished.err();
        }

        /// The outcome of the operation: `None` while it is in flight, or
        /// if none was started; then the count of bytes transferred, or
        /// the error.
        ///
        /// A connect is only finished by [`finish_connect`]: this tells
        /// whether the connection was made.
        ///
        /// [`finish_connect`]: Self::finish_connect
        pub fn result(&self) -> Option<Result<usize>> {
            if self.kind() == Kind::Idle {
                return None;
            }
            let status = self.status();
            if status == STATUS_PENDING {
                return None;
            }
            // SAFETY: the operation is complete: the system writes
            // nothing any more.
            let bytes =
                unsafe { ptr::read_volatile(&raw const (*self.overlapped()).internal_high) };
            Some(outcome(status, bytes))
        }

        /// Waits until the operation is complete and returns its outcome,
        /// or `None` if `timeout` passes first, or if no operation was
        /// started. `None` for a timeout waits for as long as it takes.
        ///
        /// This is for an operation on a handle that has no port, or for a
        /// thread that needs this one operation over: with a port, the
        /// completion is queued all the same.
        pub fn wait(&self, timeout: Option<Duration>) -> Option<Result<usize>> {
            if self.kind() == Kind::Idle {
                return None;
            }
            // SAFETY: the allocation lives; the status was pending before
            // the operation was started, and the event is the operation's.
            unsafe {
                let inner = self.0.as_ptr();
                sys::wait_status(
                    (*inner).overlapped.event,
                    &raw const (*inner).overlapped.internal,
                    timeout,
                )
            }?;
            self.result()
        }

        /// Asks the system to cancel the operation in flight. `Ok(true)`
        /// if it took the request, `Ok(false)` if there is nothing to
        /// cancel: no operation, or one that is complete or about to be.
        ///
        /// Either way **the operation completes**, and its completion is
        /// queued: with [`Canceled`](ErrorKind::Canceled) if it was
        /// stopped, with its result if it was not. The buffer is the
        /// system's until then.
        ///
        /// `CancelIoEx`.
        pub fn cancel(&self) -> Result<bool> {
            if !self.is_pending() {
                return Ok(false);
            }
            // SAFETY: the target was a handle when the operation was
            // started; if it has been closed since, the call fails or
            // finds nothing of this operation on whatever has the number.
            unsafe { sys::cancel((*self.0.as_ptr()).target, self.overlapped()) }
        }

        /// The buffer of the operation, once it is not in flight: `None`
        /// until then, once taken, and for an operation that was given
        /// none, or several ([`take_buffers`](Self::take_buffers)).
        ///
        /// After a read or a receive its length is the count of bytes
        /// transferred (0 if the operation failed); after a write or a
        /// send it is as it was given.
        pub fn take_buffer(&mut self) -> Option<Vec<u8>> {
            let bytes = self.result().and_then(Result::ok).unwrap_or(0);
            let inner = self.idle().ok()?;
            if !inner.has_buf {
                return None;
            }
            inner.has_buf = false;
            let mut buf = core::mem::take(&mut inner.buf);
            if inner.fills {
                // SAFETY: the system wrote that many bytes at the start of
                // the buffer, and never more than its capacity.
                unsafe { buf.set_len(bytes.min(buf.capacity())) };
            }
            Some(buf)
        }

        /// The buffers of a vectored operation, once it is not in flight:
        /// `None` until then, once taken, and for another kind of
        /// operation.
        ///
        /// After a receive the count of bytes is shared out among them in
        /// order, each full before the next has anything; after a send
        /// they are as they were given.
        pub fn take_buffers(&mut self) -> Option<Vec<Vec<u8>>> {
            let mut bytes = self.result().and_then(Result::ok).unwrap_or(0);
            let inner = self.idle().ok()?;
            if !inner.has_bufs {
                return None;
            }
            inner.has_bufs = false;
            let mut bufs = core::mem::take(&mut inner.bufs);
            if inner.fills {
                for buf in &mut bufs {
                    let len = bytes.min(buf.capacity());
                    // SAFETY: the system filled the buffers in order, and
                    // wrote that many bytes at the start of this one.
                    unsafe { buf.set_len(len) };
                    bytes -= len;
                }
            }
            Some(bufs)
        }

        /// The socket of an [accept](Self::accept) that has completed, and
        /// the address of its peer: `None` while it is in flight, if the
        /// operation was not an accept, and once taken.
        ///
        /// The socket is connected, blocking and private to the process.
        /// If the accept failed, or was cancelled, this is its error and
        /// the socket is closed.
        ///
        /// The listener must still be open: the system is told which one
        /// the socket came from (`SO_UPDATE_ACCEPT_CONTEXT`), without
        /// which it has no addresses.
        pub fn take_accepted(&mut self) -> Option<Result<(OwnedSocket, Address)>> {
            if self.kind() != Kind::Accept {
                return None;
            }
            let outcome = self.result()?;
            self.finish();
            let inner = self.idle().ok()?;
            let socket = inner.socket.take()?;
            if let Err(error) = outcome {
                return Some(Err(error));
            }
            if let Some(error) = inner.finish_error.take() {
                return Some(Err(error));
            }
            let mut peer = RawAddr::new();
            if let Err(error) = sys_net::peer_addr(socket.as_raw(), &mut peer) {
                return Some(Err(error));
            }
            let peer = peer.decode().unwrap_or(Address::Unix(UnixAddr::unnamed()));
            Some(Ok((socket, peer)))
        }

        /// Completes a [connect](Self::connect) that has completed: `None`
        /// while it is in flight, if the operation was not a connect, and
        /// once this has returned its outcome.
        ///
        /// `Ok` means the socket is connected, and from now on one like
        /// any other (`SO_UPDATE_CONNECT_CONTEXT`: until then it cannot be
        /// shut down and has no peer address). The socket must still be
        /// open.
        pub fn finish_connect(&mut self) -> Option<Result<()>> {
            if self.kind() != Kind::Connect {
                return None;
            }
            let outcome = self.result()?;
            self.finish();
            let inner = self.idle().ok()?;
            if core::mem::replace(&mut inner.connect_taken, true) {
                return None;
            }
            if let Err(error) = outcome {
                return Some(Err(error));
            }
            Some(inner.finish_error.take().map_or(Ok(()), Err))
        }
    }

    impl Drop for Operation {
        fn drop(&mut self) {
            if self.is_pending() {
                // Whatever this says, the operation has to be over before
                // the memory goes.
                let _ = self.cancel();
                // SAFETY: the allocation lives; the status was pending
                // before the operation was started.
                let over = unsafe {
                    let inner = self.0.as_ptr();
                    sys::wait_status(
                        (*inner).overlapped.event,
                        &raw const (*inner).overlapped.internal,
                        Some(DROP_PATIENCE),
                    )
                };
                if over.is_none() {
                    // The system still refers to the structure and to the
                    // buffer: they are its own from now on.
                    return;
                }
            }
            // SAFETY: the allocation was made by `Box` in `new`, nothing
            // is in flight, and nothing else refers to it.
            drop(unsafe { Box::from_raw(self.0.as_ptr()) });
        }
    }

    impl fmt::Debug for Operation {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("Operation")
                .field("id", &self.id())
                .field("result", &self.result())
                .finish_non_exhaustive()
        }
    }

    /// An offset as the system takes it. Negative values have meanings of
    /// their own to it.
    fn file_offset(offset: Option<u64>) -> Result<Option<i64>> {
        offset
            .map(|offset| i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput.into()))
            .transpose()
    }

    /// The system counts the bytes of one operation on 32 bits: a longer
    /// buffer is used in part, which is a short read or write.
    fn len32(len: usize) -> u32 {
        len.min(u32::MAX as usize) as u32
    }
}