mmap-io 1.0.0

Zero-copy memory-mapped file I/O for Rust. Safe concurrent reads, writes, and atomic views across Linux, macOS, and Windows. Built for databases, log structures, game runtimes, caches, and IPC.
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
<div id="doc-top" align="center">
    <img width="99" alt="Rust logo" src="https://raw.githubusercontent.com/jamesgober/rust-collection/72baabd71f00e14aa9184efcb16fa3deddda3a0a/assets/rust-logo.svg">
    <h1>
        <strong>mmap-io</strong>
        <sup><br><sub>API REFERENCE</sub><br></sup>
    </h1>
</div>
<br>

Complete reference for public-facing APIs. Each item lists its signature, parameters, description, errors, and examples.

<br>

## Table of Contents
- **[Prerequisites](#prerequisites)**
- **[Features](#features)**
  - [Default Features](#default-features)
- **[Installation](#installation)**
- **[Core Types](#core-types)**
  - [MemoryMappedFile](#memorymappedfile)
  - [AnonymousMmap](#anonymousmmap) (1.0.0)
  - [MmapMode](#mmapmode)
  - [MappedSlice](#mappedslice)
  - [MappedSliceMut](#mappedslicemut)
  - [TouchHint](#touchhint)
  - [MmapReader](#mmapreader) (0.9.11)
  - [MmapIoError](#mmapioerror)
- **[Manager Functions](#manager-functions)**
  - [create_mmap](#create_mmap)
  - [load_mmap](#load_mmap)
  - [update_region](#update_region)
  - [flush](#flush)
  - [copy_mmap](#copy_mmap)
  - [delete_mmap](#delete_mmap)
- **[MemoryMappedFile Methods](#memorymappedfile-methods)**
  - [create_rw](#create_rw)
  - [open_ro](#open_ro)
  - [open_rw](#open_rw)
  - [open_cow](#open_cow) (feature = "cow")
  - [open_or_create](#open_or_create) (0.9.8)
  - [from_file](#from_file) (0.9.8)
  - [unmap](#unmap) (0.9.8)
  - [as_slice](#as_slice)
  - [as_slice_mut](#as_slice_mut)
  - [read_into](#read_into)
  - [update_region](#update_region-1)
  - [flush](#flush-1)
  - [flush_range](#flush_range)
  - [resize](#resize)
  - [len](#len)
  - [is_empty](#is_empty)
  - [path](#path)
  - [mode](#mode)
  - [flush_policy](#flush_policy) (0.9.8)
  - [pending_bytes](#pending_bytes) (0.9.8)
  - [as_ptr](#as_ptr) (0.9.8, unsafe)
  - [as_mut_ptr](#as_mut_ptr) (0.9.8, unsafe)
  - [prefetch_range](#prefetch_range) (0.9.8)
  - [as_slice_bytes](#as_slice_bytes) (0.9.11, 0.9.6-compat)
  - [read_bytes](#read_bytes) (0.9.11, feature = "bytes")
  - [reader](#reader) (0.9.11)
  - [is_hugepage_backed](#is_hugepage_backed) (1.0.0)
- **[Feature-Gated APIs](#feature-gated-apis)**
  - [Memory Advise](#memory-advise-feature--advise)
    - [advise](#advise)
    - [MmapAdvice](#mmapadvice)
  - [Iterator-Based Access](#iterator-based-access-feature--iterator)
    - [chunks](#chunks)
    - [pages](#pages)
    - [chunks_mut](#chunks_mut)
  - [Atomic Operations](#atomic-operations-feature--atomic)
    - [atomic_u64](#atomic_u64)
    - [atomic_u32](#atomic_u32)
    - [atomic_u64_slice](#atomic_u64_slice)
    - [atomic_u32_slice](#atomic_u32_slice)
  - [Memory Locking](#memory-locking-feature--locking)
    - [lock](#lock)
    - [unlock](#unlock)
    - [lock_all](#lock_all)
    - [unlock_all](#unlock_all)
  - [File Watching](#file-watching-feature--watch)
    - [watch](#watch)
    - [ChangeEvent](#changeevent)
    - [ChangeKind](#changekind)
- **[Segment Types](#segment-types)**
  - [Segment](#segment)
  - [SegmentMut](#segmentmut)
- **[Async Operations](#async-operations-feature--async)**
  - [update_region_async](#update_region_async)
  - [flush_async](#flush_async)
  - [flush_range_async](#flush_range_async)
  - [create_mmap_async](#create_mmap_async)
  - [copy_mmap_async](#copy_mmap_async)
  - [delete_mmap_async](#delete_mmap_async)
- **[Utility Functions](#utility-functions)**
  - [page_size](#page_size)
  - [align_up](#align_up)
- **[Safety and Best Practices](#safety-and-best-practices)**
- **[Flush Policy](#flush-policy)**
  - [Mapped Memory Access](#mapped-memory-access)
  - [Copy-On-Write Mode](#copy-on-write-cow-mode)
  - [Flushing Behavior](#flushing-behavior)
  - [Thread Safety](#thread-safety)
  - [Performance Tips](#performance-tips)
  - [Common Pitfalls](#common-pitfalls)
  - [Error Handling](#error-handling)
- **[Examples](#examples)**
  - [Database-like Usage](#database-like-usage)
  - [Game Asset Loading](#game-asset-loading)
  - [Log File Processing](#log-file-processing)
  - [Concurrent Counter](#concurrent-counter)
- **[Version History](#version-history)**

<br><br>

## Prerequisites:
- **MSRV: 1.75**
- **Default (*sync*) APIs**: *always available*.
- **Feature-gated APIs**: *require enabling specific features*.

<br><br>


## Features

The following optional Cargo features enable extended functionality:

| Feature    | Description                                                                                         |
|------------|-----------------------------------------------------------------------------------------------------|
| `async`    | Runtime-agnostic async helpers (drives on tokio, smol, async-std, custom executors).                |
| `bytes`    | `bytes::Bytes` conversions for the hyper/tower/tonic/axum/reqwest ecosystem.                        |
| `advise`   | Memory hinting via **`madvise`/`posix_madvise` (Unix)** or **Prefetch (Windows)**.                  |
| `iterator` | Iterator-based access to memory chunks or pages with zero-copy read access.                         |
| `hugepages` | Best-effort huge-page mappings on Linux (HugeTLB / Transparent Huge Pages with multi-tier fallback). Use `is_hugepage_backed()` to confirm at runtime.|
| `cow`      | Copy-on-Write mapping mode using private memory views (per-process isolation).                       |
| `locking`  | Page-level memory locking via **`mlock`/`munlock` (Unix)** or **`VirtualLock` (Windows)**.           |
| `atomic`   | Atomic views into memory as aligned `u32` / `u64`, with strict alignment checking.                  |
| `watch`    | Native file-change notifications (inotify on Linux, FSEvents on macOS, ReadDirectoryChangesW on Windows). |

<br>

- **Huge Pages** (`feature = "hugepages"`): Best-effort large-page mappings on supported platforms to reduce TLB misses. Falls back safely when unavailable or lacking privileges.

- **Async-Only Flushing** (`feature = "async"`): Async write helpers auto-flush after each write to ensure post-await visibility across platforms.

- **Platform Parity**: After `flush()` or `flush_range()`, newly opened RO mappings observe persisted bytes across supported OSes.

<br> 

### Default Features

By default, the following features are enabled:

- `advise` – Memory access hinting for performance
- `iterator` – Iterator-based chunk/page access


<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>


## Installation

### 1: Basic Installation:
> Add the following to your Cargo.toml file:
```toml
[dependencies]
mmap-io = { version = "1.0.0" }
```

> Or install using Cargo:
```bash
cargo add mmap-io
```

<br>

### 2: Custom Install:
Enable additional features by using the pre-defined [features flags](#features) as shown above.

> ##### Manual Install with Features:
```toml
[dependencies]
mmap-io = { version = "1.0.0", features = ["cow", "locking"] }
```
> ##### Cargo Install with Features:
```bash
cargo add mmap-io --features async,advise,iterator,cow,locking,atomic,watch
```

<br>

### 3: Minimal Install:
If you're building for minimal environments or want total control over feature flags, you can disable the [default features](#default-features).

> ##### Manual Install without Default Features:
```toml
[dependencies]
mmap-io = { version = "1.0.0", default-features = false, features = ["locking"] }
```

> ##### Cargo Install without Default Features:
```bash
cargo add mmap-io --no-default-features --features locking
```

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>


## Core Types

<br>

### MemoryMappedFile

The main type for memory-mapped file operations.

```rust
pub struct MemoryMappedFile { /* private fields */ }
```

**Description**: Provides safe, zero-copy access to memory-mapped files with concurrent access support through interior mutability.

**Example**:
```rust
use mmap_io::MemoryMappedFile;

let mmap = MemoryMappedFile::create_rw("data.bin", 1024)?;
```

<br>

### AnonymousMmap

*(Since 1.0.0)*

Process-local memory mapping with no backing file. Useful for shared scratch memory between threads and as a kernel-side substrate for IPC patterns. Pages are zero-initialized on first touch; memory is released when the value is dropped.

```rust
pub struct AnonymousMmap { /* private fields */ }
```

**Differences from `MemoryMappedFile`**:
- No file descriptor / handle; no `AsFd`/`AsRawFd`/`AsHandle` impls.
- No `resize` (the underlying mapping does not support it).
- No `flush` (volatile memory; nothing to persist).
- No `path` (there is no path).

Everything else (read, write, slice access) works identically.

**Example**:
```rust
use mmap_io::AnonymousMmap;

let mmap = AnonymousMmap::new(4096)?;
mmap.update_region(0, b"hello")?;
let mut buf = [0u8; 5];
mmap.read_into(0, &mut buf)?;
assert_eq!(&buf, b"hello");
# Ok::<(), mmap_io::MmapIoError>(())
```

#### Methods

| Method | Signature | Notes |
|--------|-----------|-------|
| `new` | `fn new(size: u64) -> Result<Self>` | Allocate `size` bytes. Errors on zero/oversized. |
| `len` | `fn len(&self) -> u64` | Length in bytes. |
| `is_empty` | `fn is_empty(&self) -> bool` | Always `false` for a constructed mapping. |
| `read_into` | `fn read_into(&self, offset: u64, buf: &mut [u8]) -> Result<()>` | Copy bytes out of the mapping. |
| `update_region` | `fn update_region(&self, offset: u64, data: &[u8]) -> Result<()>` | Copy bytes into the mapping. |
| `as_slice` | `fn as_slice(&self, offset: u64, len: u64) -> Result<MappedSlice<'_>>` | Borrow a read-only slice (holds a read lock). |
| `as_mut_slice` | `fn as_mut_slice(&self, offset: u64, len: u64) -> Result<MappedSliceMut<'_>>` | Borrow a mutable slice (holds a write lock). |
| `as_ptr` | `unsafe fn as_ptr(&self) -> *const u8` | Raw byte pointer for FFI. |
| `as_mut_ptr` | `unsafe fn as_mut_ptr(&self) -> *mut u8` | Raw mutable byte pointer for FFI. |

<br>

### MappedSlice

Read-only slice into a memory-mapped region. For RW mappings it holds the read lock for its lifetime, so concurrent `resize` blocks until the slice is dropped.

```rust
pub struct MappedSlice<'a> { /* private fields */ }

impl<'a> MappedSlice<'a> {
    pub fn len(&self) -> usize;
    pub fn is_empty(&self) -> bool;
    pub fn as_slice(&self) -> &[u8];
}

impl std::ops::Deref for MappedSlice<'_> { type Target = [u8]; }
impl AsRef<[u8]> for MappedSlice<'_> { /* ... */ }
impl PartialEq for MappedSlice<'_> { /* ... */ }
impl PartialEq<[u8]> for MappedSlice<'_> { /* ... */ }
impl<const N: usize> PartialEq<[u8; N]> for MappedSlice<'_> { /* ... */ }
```

<br>

### MappedSliceMut

Mutable slice into a memory-mapped region. Holds the write lock for its lifetime; any concurrent reader or writer blocks until dropped.

```rust
pub struct MappedSliceMut<'a> { /* private fields */ }

impl<'a> MappedSliceMut<'a> {
    pub fn len(&self) -> usize;
    pub fn is_empty(&self) -> bool;
    pub fn as_mut(&mut self) -> &mut [u8];
}

impl std::ops::Deref for MappedSliceMut<'_> { type Target = [u8]; }
impl std::ops::DerefMut for MappedSliceMut<'_> { /* ... */ }
```

<br>

### MmapReader

*(Since 0.9.11)*

Cursor wrapper that implements `std::io::Read` and `std::io::Seek`. Plugs an `mmap-io` mapping into any parser or decoder that takes a generic `R: Read`: `serde_json::from_reader`, `flate2::read::GzDecoder`, `tar::Archive::new`, `BufReader`, etc.

```rust
pub struct MmapReader<'a> { /* private fields */ }

impl<'a> MmapReader<'a> {
    pub fn position(&self) -> u64;
    pub fn set_position(&mut self, pos: u64);
}

impl std::io::Read for MmapReader<'_> { /* ... */ }
impl std::io::Seek for MmapReader<'_> { /* ... */ }
```

Construct via [`MemoryMappedFile::reader`](#reader).

<br>

### TouchHint

Enum representing when to touch (prewarm) memory pages during mapping creation.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TouchHint {
    Never,   // Don't touch pages during creation (default)
    Eager,   // Eagerly touch all pages during creation
    Lazy,    // Touch pages lazily on first access (same as Never for now)
}
```

**Variants**:
- `Never`: Don't touch pages during creation (default)
- `Eager`: Eagerly touch all pages during creation to prewarm page tables and improve first-access latency. Useful for benchmarking scenarios where you want consistent timing without page fault overhead.
- `Lazy`: Touch pages lazily on first access (same as Never for now)

<br>

### MmapMode

Enum representing the access mode for memory-mapped files.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MmapMode {
    ReadOnly,
    ReadWrite,
    CopyOnWrite, // Available with feature = "cow"
}
```

**Variants**:
- `ReadOnly`: Read-only access to the file
- `ReadWrite`: Read and write access to the file
- `CopyOnWrite`: Private copy-on-write mapping (feature-gated)

<br>

### MmapIoError

Error type for all mmap-io operations.

```rust
#[derive(Debug, Error)]
pub enum MmapIoError {
    Io(#[from] io::Error),
    InvalidMode(&'static str),
    OutOfBounds { offset: u64, len: u64, total: u64 },
    FlushFailed(String),
    ResizeFailed(String),
    AdviceFailed(String),    // feature = "advise"
    LockFailed(String),      // feature = "locking"
    UnlockFailed(String),    // feature = "locking"
    Misaligned { required: u64, offset: u64 }, // feature = "atomic"
    WatchFailed(String),     // feature = "watch"
}
```
<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Manager Functions

High-level convenience functions for common operations.

<br>

### create_mmap

```rust
pub fn create_mmap<P: AsRef<Path>>(path: P, size: u64) -> Result<MemoryMappedFile>
```

**Description**: Creates a new memory-mapped file with the specified size. Truncates if the file already exists.

**Parameters**:
- `path`: Path to the file to create
- `size`: Size of the file in bytes (must be > 0)

**Returns**: `Result<MemoryMappedFile>` - The created memory-mapped file

**Errors**:
- `MmapIoError::ResizeFailed` if size is 0
- `MmapIoError::Io` if file creation fails

**Example**:
```rust
use mmap_io::create_mmap;

let mmap = create_mmap("new_file.bin", 1024 * 1024)?; // 1MB file
```

<br>

### load_mmap

```rust
pub fn load_mmap<P: AsRef<Path>>(path: P, mode: MmapMode) -> Result<MemoryMappedFile>
```

**Description**: Opens an existing file and memory-maps it with the specified mode.

**Parameters**:
- `path`: Path to the file to open
- `mode`: Access mode (`ReadOnly`, `ReadWrite`, or `CopyOnWrite`)

**Returns**: `Result<MemoryMappedFile>` - The opened memory-mapped file

**Errors**:
- `MmapIoError::Io` if file doesn't exist or can't be opened
- `MmapIoError::ResizeFailed` if file is zero-length (for RW mode)

**Example**:
```rust
use mmap_io::{load_mmap, MmapMode};

let ro_mmap = load_mmap("existing.bin", MmapMode::ReadOnly)?;
let rw_mmap = load_mmap("data.bin", MmapMode::ReadWrite)?;
```

<br>

### update_region

```rust
pub fn update_region(mmap: &MemoryMappedFile, offset: u64, data: &[u8]) -> Result<()>
```

**Description**: Writes data to the memory-mapped file at the specified offset.

**Parameters**:
- `mmap`: The memory-mapped file to write to
- `offset`: Byte offset where to start writing
- `data`: Data to write

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::InvalidMode` if not in ReadWrite mode
- `MmapIoError::OutOfBounds` if offset + data.len() exceeds file size

**Example**:
```rust
use mmap_io::{create_mmap, update_region};

let mmap = create_mmap("data.bin", 1024)?;
update_region(&mmap, 100, b"Hello, World!")?;
```

<br>

### flush

```rust
pub fn flush(mmap: &MemoryMappedFile) -> Result<()>
```

**Description**: Flushes all changes to disk. No-op for read-only mappings.

**Parameters**:
- `mmap`: The memory-mapped file to flush

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::FlushFailed` if the flush operation fails

**Example**:
```rust
use mmap_io::{create_mmap, update_region, flush};

let mmap = create_mmap("data.bin", 1024)?;
update_region(&mmap, 0, b"data")?;
flush(&mmap)?; // Ensure data is persisted
```

<br>

### copy_mmap

```rust
pub fn copy_mmap<P: AsRef<Path>>(src: P, dst: P) -> Result<()>
```

**Description**: Copies a file using the filesystem. Does not copy the mapping, only file contents.

**Parameters**:
- `src`: Source file path
- `dst`: Destination file path

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::Io` if the copy operation fails

**Example**:
```rust
use mmap_io::copy_mmap;

copy_mmap("source.bin", "backup.bin")?;
```

<br>

### delete_mmap

```rust
pub fn delete_mmap<P: AsRef<Path>>(path: P) -> Result<()>
```

**Description**: Deletes the file at the specified path. The mapping should be dropped before calling this.

**Parameters**:
- `path`: Path to the file to delete

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::Io` if the delete operation fails

**Example**:
```rust
use mmap_io::{create_mmap, delete_mmap};

{
    let mmap = create_mmap("temp.bin", 1024)?;
    // Use mmap...
} // mmap dropped here

delete_mmap("temp.bin")?;
```
<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## MemoryMappedFile Methods

<br>

### create_rw

```rust
pub fn create_rw<P: AsRef<Path>>(path: P, size: u64) -> Result<Self>
```

**Description**: Creates a new file and memory-maps it in read-write mode.

**Parameters**:
- `path`: Path to the file to create
- `size`: Size in bytes (must be > 0)

**Returns**: `Result<MemoryMappedFile>`

**Example**:
```rust
use mmap_io::MemoryMappedFile;

let mmap = MemoryMappedFile::create_rw("new.bin", 4096)?;
```

<br>

### open_ro

```rust
pub fn open_ro<P: AsRef<Path>>(path: P) -> Result<Self>
```

**Description**: Opens an existing file in read-only mode.

**Parameters**:
- `path`: Path to the file to open

**Returns**: `Result<MemoryMappedFile>`

**Example**:
```rust
use mmap_io::MemoryMappedFile;

let mmap = MemoryMappedFile::open_ro("data.bin")?;
```

<br>

### open_rw

```rust
pub fn open_rw<P: AsRef<Path>>(path: P) -> Result<Self>
```

**Description**: Opens an existing file in read-write mode.

**Parameters**:
- `path`: Path to the file to open

**Returns**: `Result<MemoryMappedFile>`

**Errors**:
- `MmapIoError::ResizeFailed` if file is zero-length

**Example**:
```rust
use mmap_io::MemoryMappedFile;

let mmap = MemoryMappedFile::open_rw("data.bin")?;
```

<br>

### open_cow

```rust
#[cfg(feature = "cow")]
pub fn open_cow<P: AsRef<Path>>(path: P) -> Result<Self>
```

**Description**: Opens an existing file in copy-on-write mode. Changes are private to this process.

**Parameters**:
- `path`: Path to the file to open

**Returns**: `Result<MemoryMappedFile>`

**Example**:
```rust
#[cfg(feature = "cow")]
use mmap_io::MemoryMappedFile;

let mmap = MemoryMappedFile::open_cow("shared.bin")?;
```

<br>

### as_slice

```rust
pub fn as_slice(&self, offset: u64, len: u64) -> Result<MappedSlice<'_>>
```

**Description**: Returns a zero-copy read-only view of `[offset, offset + len)`. Since 0.9.7 this works on **all** mapping modes (ReadOnly, CopyOnWrite, and ReadWrite). `MappedSlice<'_>` implements `Deref<Target = [u8]>` and `AsRef<[u8]>` so it can be used as a `&[u8]` directly (indexing, iteration, passing to functions that take `&[u8]` via `&*slice` or `slice.as_ref()`).

On ReadWrite mappings, the returned slice holds an internal read guard for its lifetime. Concurrent `resize()` (which requires the write lock) blocks until the slice is dropped. Other readers and disjoint writes are not blocked.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Number of bytes to include

**Returns**: `Result<MappedSlice<'_>>` - Wrapper around the immutable byte slice

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds

**Example**:
```rust
let mmap = MemoryMappedFile::open_ro("data.bin")?;
let data = mmap.as_slice(100, 50)?;
let first_byte = data[0];
// pass to a function that wants `&[u8]`:
fn consume(_: &[u8]) {}
consume(&*data);
```

<br>

### as_slice_mut

```rust
pub fn as_slice_mut(&self, offset: u64, len: u64) -> Result<MappedSliceMut<'_>>
```

**Description**: Returns a mutable slice guard for the specified range. Only available in ReadWrite mode.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Number of bytes to include

**Returns**: `Result<MappedSliceMut>` - Guard providing mutable access

**Errors**:
- `MmapIoError::InvalidMode` if not in ReadWrite mode
- `MmapIoError::OutOfBounds` if range exceeds file bounds

**Example**:
```rust
let mmap = MemoryMappedFile::open_rw("data.bin")?;
{
    let mut guard = mmap.as_slice_mut(0, 10)?;
    guard.as_mut().copy_from_slice(b"0123456789");
} // guard dropped, lock released
```

<br>

### read_into

```rust
pub fn read_into(&self, offset: u64, buf: &mut [u8]) -> Result<()>
```

**Description**: Reads bytes from the mapping into the provided buffer.

**Parameters**:
- `offset`: Starting byte offset
- `buf`: Buffer to read into (length determines how many bytes to read)

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds

**Example**:
```rust
let mmap = MemoryMappedFile::open_rw("data.bin")?;
let mut buffer = vec![0u8; 100];
mmap.read_into(50, &mut buffer)?;
```

<br>

### update_region

```rust
pub fn update_region(&self, offset: u64, data: &[u8]) -> Result<()>
```

**Description**: Writes data to the mapped file at the specified offset.

**Parameters**:
- `offset`: Starting byte offset
- `data`: Data to write

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::InvalidMode` if not in ReadWrite mode
- `MmapIoError::OutOfBounds` if range exceeds file bounds

**Example**:
```rust
let mmap = MemoryMappedFile::create_rw("data.bin", 1024)?;
mmap.update_region(100, b"Hello")?;
```

<br>

### flush

Platform Parity: A subsequent fresh read-only mapping observes persisted data after this call on all supported platforms.

```rust
pub fn flush(&self) -> Result<()>
```

**Description**: Flushes all changes to disk.

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::FlushFailed` if flush operation fails

<br>

### flush_range

Platform Parity: A subsequent fresh read-only mapping observes persisted data for the flushed range after this call. Other non-flushed regions may not be visible until a full `flush()` is performed.

```rust
pub fn flush_range(&self, offset: u64, len: u64) -> Result<()>
```

**Description**: Flushes a specific byte range to disk.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Number of bytes to flush

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds
- `MmapIoError::FlushFailed` if flush operation fails

<br>

### resize

```rust
pub fn resize(&self, new_size: u64) -> Result<()>
```

**Description**: Resizes the mapped file. Only available in ReadWrite mode.

**Parameters**:
- `new_size`: New size in bytes (must be > 0)

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::InvalidMode` if not in ReadWrite mode
- `MmapIoError::ResizeFailed` if new size is 0

**Example**:
```rust
let mmap = MemoryMappedFile::create_rw("data.bin", 1024)?;
mmap.resize(2048)?; // Grow to 2KB
```

<br>

### len

```rust
pub fn len(&self) -> u64
```

**Description**: Returns the current length of the mapped file in bytes.

**Returns**: `u64` - File size in bytes

### is_empty

```rust
pub fn is_empty(&self) -> bool
```

**Description**: Returns true if the mapped file is empty (0 bytes).

**Returns**: `bool`

<br>

### path

```rust
pub fn path(&self) -> &Path
```

**Description**: Returns the path to the underlying file.

**Returns**: `&Path`

<br>

### mode

```rust
pub fn mode(&self) -> MmapMode
```

**Description**: Returns the current mapping mode.

**Returns**: `MmapMode`

<br>

### open_or_create

```rust
pub fn open_or_create<P: AsRef<Path>>(path: P, default_size: u64) -> Result<Self>
```

**Description**: Opens `path` for read-write if it exists; creates it at `default_size` bytes otherwise. The classic "open if there, create if not" pattern in one call. Since 0.9.8.

**Parameters**:
- `path`: Path to open or create
- `default_size`: Size used only on the create path; ignored when the file already exists

**Returns**: `Result<MemoryMappedFile>` in ReadWrite mode

**Errors**:
- `MmapIoError::ResizeFailed` if creating and `default_size` is zero
- `MmapIoError::Io` if the filesystem rejects the call

**Example**:
```rust
use mmap_io::MemoryMappedFile;
let mmap = MemoryMappedFile::open_or_create("data.bin", 1024 * 1024)?;
```

<br>

### from_file

```rust
pub fn from_file<P: AsRef<Path>>(file: File, mode: MmapMode, path: P) -> Result<Self>
```

**Description**: Construct a `MemoryMappedFile` from a pre-opened `std::fs::File`. The escape hatch for callers that need custom `OpenOptions` (e.g. `O_DIRECT`, `O_NOATIME`, a specific security context, or a file inherited from a parent process). Since 0.9.8.

**Parameters**:
- `file`: An open File with permissions matching `mode`
- `mode`: Access mode (ReadOnly / ReadWrite / CopyOnWrite)
- `path`: Informational path for `path()` and error messages

**Returns**: `Result<MemoryMappedFile>`

**Errors**:
- `MmapIoError::ResizeFailed` if the file is zero-length on ReadWrite or CopyOnWrite
- `MmapIoError::Io` if metadata or mapping fails

**Example**:
```rust
use std::fs::OpenOptions;
use mmap_io::{MemoryMappedFile, MmapMode};

let file = OpenOptions::new().read(true).write(true).open("data.bin")?;
let mmap = MemoryMappedFile::from_file(file, MmapMode::ReadWrite, "data.bin")?;
# Ok::<(), Box<dyn std::error::Error>>(())
```

<br>

### unmap

```rust
pub fn unmap(self) -> std::result::Result<File, Self>
```

**Description**: Consume the mapping and return the underlying `File`. The mapping is dropped (memory unmapped, background flusher stopped) before the file is returned. Since 0.9.8.

Returns the mapping unchanged (wrapped in `Err`) if other clones of this `MemoryMappedFile` exist; the underlying File cannot be extracted while other handles hold references.

**Returns**: `Ok(File)` on success, `Err(MemoryMappedFile)` if other clones are alive

**Example**:
```rust
use mmap_io::MemoryMappedFile;
use std::io::Write;

let mmap = MemoryMappedFile::create_rw("data.bin", 1024)?;
mmap.update_region(0, b"done")?;
mmap.flush()?;

let mut file = mmap.unmap().expect("no clones alive");
file.write_all(b"more bytes")?;
# Ok::<(), Box<dyn std::error::Error>>(())
```

<br>

### flush_policy

```rust
pub fn flush_policy(&self) -> FlushPolicy
```

**Description**: Returns the `FlushPolicy` this mapping was constructed with. Diagnostic accessor for introspection. Since 0.9.8.

**Returns**: `FlushPolicy`

<br>

### pending_bytes

```rust
pub fn pending_bytes(&self) -> u64
```

**Description**: Bytes written since the last successful flush. Mainly useful for diagnostics under `FlushPolicy::EveryBytes` / `EveryWrites`: poll to see how close you are to the next auto-flush. One atomic read, no I/O. Since 0.9.8.

**Returns**: `u64` accumulator value

<br>

### as_ptr

```rust
pub unsafe fn as_ptr(&self) -> *const u8
```

**Description**: Raw read-only pointer to the start of the mapped region, for FFI use cases that need to hand a `const void *` plus length to a C library. Since 0.9.8.

**Safety**: The caller MUST NOT dereference past `self.len()` bytes, MUST NOT hold the pointer across a `resize()` (which can move the mapping to a new virtual address), and MUST honour Rust aliasing rules at the FFI boundary.

**Returns**: `*const u8` to the base of the mapping

<br>

### as_mut_ptr

```rust
pub unsafe fn as_mut_ptr(&self) -> Result<*mut u8>
```

**Description**: Raw mutable pointer to the start of the mapped region (ReadWrite only). Since 0.9.8.

**Safety**: Same contract as `as_ptr`, plus the caller MUST NOT alias this pointer with any live Rust `&` reference to the same bytes (a `MappedSlice` would alias).

**Returns**: `Result<*mut u8>`

**Errors**:
- `MmapIoError::InvalidMode` if the mapping is not ReadWrite

<br>

### prefetch_range

```rust
pub fn prefetch_range(&self, offset: u64, len: u64) -> Result<()>
```

**Description**: Hint the kernel that the given range of the **backing file** will be read soon. On Linux issues `posix_fadvise(POSIX_FADV_WILLNEED)` against the file descriptor (warms the page cache from the file side). No-op on other platforms. Since 0.9.8.

This is complementary to `advise(offset, len, MmapAdvice::WillNeed)`, which operates on the **mapped virtual memory range** via `madvise`. Both can be issued for cold reads of huge files.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Length of the range to prefetch

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds
- `MmapIoError::AdviceFailed` if the underlying syscall errors (Linux only)

<br>

### touch_pages

```rust
pub fn touch_pages(&self) -> Result<()>
```

**Description**: Prewarns (touches) all pages by reading the first byte of each page, forcing the OS to load all pages into physical memory. This eliminates page faults during subsequent access, which is useful for benchmarking and performance-critical sections.

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::Io` if memory access fails

**Performance**:
- **Time Complexity**: O(n) where n is the number of pages
- **Memory Usage**: Forces all pages into physical memory
- **I/O Operations**: May trigger disk reads for unmapped pages
- **Cache Behavior**: Optimizes subsequent access patterns

**Example**:
```rust
let mmap = MemoryMappedFile::open_ro("data.bin")?;

// Prewarm all pages before performance-critical section
mmap.touch_pages()?;

// Now all subsequent accesses will be fast (no page faults)
let data = mmap.as_slice(0, 1024)?;
```

<br>

### touch_pages_range

```rust
pub fn touch_pages_range(&self, offset: u64, len: u64) -> Result<()>
```

**Description**: Prewarns a specific range of pages. Similar to `touch_pages()` but only affects the specified range.

**Parameters**:
- `offset`: Starting offset in bytes
- `len`: Length of range to touch in bytes

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds
- `MmapIoError::Io` if memory access fails

**Example**:
```rust
let mmap = MemoryMappedFile::create_rw("data.bin", 1024 * 1024)?;

// Prewarm only the first 64KB for immediate use
mmap.touch_pages_range(0, 64 * 1024)?;
```

<br>

### as_slice_bytes

*(Since 0.9.11, compat shim for the 0.9.6 signature)*

```rust
pub fn as_slice_bytes(&self, offset: u64, len: u64) -> Result<&[u8]>
```

**Description**: Returns a direct `&[u8]` borrow into the mapping. Mirrors the 0.9.6 `as_slice` signature for codebases that were broken by the 0.9.7 return-type change. Supported on `ReadOnly` and `CopyOnWrite` mappings; returns `MmapIoError::InvalidMode` on `ReadWrite` (use [`as_slice`](#as_slice) which returns `MappedSlice<'_>` for that path).

**Errors**:
- `MmapIoError::InvalidMode` on `ReadWrite` mappings.
- `MmapIoError::OutOfBounds` if range exceeds file bounds.

<br>

### read_bytes

*(Since 0.9.11; requires `feature = "bytes"`)*

```rust
pub fn read_bytes(&self, offset: u64, len: u64) -> Result<bytes::Bytes>
```

**Description**: Read `len` bytes from `offset` into a newly-allocated `bytes::Bytes`. One allocation + memcpy at the boundary; the resulting `Bytes` is mapping-lifetime-independent and can be sent through `hyper` / `tower` / `tonic` / `axum` / `reqwest`.

For true zero-copy networking, prefer `as_slice` and pass the borrowed `&[u8]` directly; `Bytes` is the right tool when ownership has to cross a thread or process boundary.

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds.

<br>

### reader

*(Since 0.9.11)*

```rust
pub fn reader(&self) -> MmapReader<'_>
```

**Description**: Returns an [`MmapReader`](#mmapreader) cursor over the mapping. Implements `std::io::Read` + `std::io::Seek`, so the mapping plugs directly into any parser or decoder expecting a generic `R: Read`.

**Example**:
```rust
use mmap_io::MemoryMappedFile;
use std::io::Read;

let mmap = MemoryMappedFile::open_ro("data.bin")?;
let mut reader = mmap.reader();
let mut buf = Vec::new();
reader.read_to_end(&mut buf)?;
# Ok::<(), Box<dyn std::error::Error>>(())
```

<br>

### is_hugepage_backed

*(Since 1.0.0)*

```rust
pub fn is_hugepage_backed(&self) -> Option<bool>
```

**Description**: Report whether the kernel currently backs this mapping with huge pages (transparent or explicit HugeTLB).

**Returns**:
- `Some(true)` if any portion of the mapping is backed by huge pages.
- `Some(false)` if the mapping is backed by regular pages only.
- `None` on non-Linux platforms, or when the status cannot be determined (e.g. `/proc/self/smaps` unreadable, no matching entry).

On Linux, parses `/proc/self/smaps` and inspects the `AnonHugePages`, `Private_Hugetlb`, and `Shared_Hugetlb` fields of the entry containing the mapping's base address.

**Notes**: Treat `None` as "unknown", not as "definitely regular pages". The result reflects state at the moment of the call; the kernel may promote or demote pages over time (Transparent Huge Pages).

<br>

## OS Handle Traits

*(Since 0.9.11)*

`MemoryMappedFile` implements the standard-library OS handle traits for file-backed mappings, letting you hand the underlying handle to FFI / `nix` / `rustix` / `polling` etc. without going through `unmap`.

```rust
// Unix (Linux, macOS, BSD):
impl AsFd for MemoryMappedFile { /* ... */ }
impl AsRawFd for MemoryMappedFile { /* ... */ }

// Windows:
impl AsHandle for MemoryMappedFile { /* ... */ }
impl AsRawHandle for MemoryMappedFile { /* ... */ }
```

The trait impls borrow the file handle for as long as the mapping is alive; the handle remains owned by the `MemoryMappedFile`. Use `unmap()` to retake ownership of the `File` explicitly.

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Flush Policy

Configurable write flushing behavior for ReadWrite mappings.

Enum:
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlushPolicy {
    Never,            // Manual control, no automatic flush
    Manual,           // Alias of Never
    Always,           // Flush after every write
    EveryBytes(usize),// Flush when N bytes written since last flush
    EveryWrites(usize), // Flush after W calls to update_region
    EveryMillis(u64), // Automatic time-based flushing every N milliseconds
}
```

Default: FlushPolicy::Never

Builder integration:
```rust
use mmap_io::{MemoryMappedFile, MmapMode};
use mmap_io::flush::FlushPolicy;

let mmap = MemoryMappedFile::builder("file.bin")
    .mode(MmapMode::ReadWrite)
    .size(1_000_000)
    .flush_policy(FlushPolicy::EveryBytes(64 * 1024))
    .create()?;
```

Behavior:
- Never/Manual: internal counters are not used; user must call flush() explicitly.
- Always: flush() is invoked after each update_region() call.
- EveryBytes(n): increments a byte counter by the number of bytes written per update_region; when it reaches n, counter resets and flush() is called.
- EveryWrites(w): increments a write counter per update_region; when it reaches w, counter resets and flush() is called.
- EveryMillis(ms): Enables automatic time-based flushing using a background thread. Writes are tracked and the background thread flushes pending changes every `ms` milliseconds when there are dirty pages. The background thread automatically stops when the MemoryMappedFile is dropped.

Notes:
- Flush is best-effort and may not imply fsync semantics on all platforms.
- COW mappings treat flush() as a no-op.

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Feature-Gated APIs

<br>

### Memory Advise (feature = "advise")

#### advise

```rust
#[cfg(feature = "advise")]
pub fn advise(&self, offset: u64, len: u64, advice: MmapAdvice) -> Result<()>
```

**Description**: Provides hints to the OS about expected access patterns for better performance.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Number of bytes the advice applies to
- `advice`: Type of advice to give

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds
- `MmapIoError::AdviceFailed` if the system call fails

**Example**:
```rust
#[cfg(feature = "advise")]
use mmap_io::MmapAdvice;

mmap.advise(0, 1024 * 1024, MmapAdvice::Sequential)?;
```

<br>

#### MmapAdvice

```rust
#[cfg(feature = "advise")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MmapAdvice {
    Normal,      // Default access pattern
    Random,      // Random access expected
    Sequential,  // Sequential access expected
    WillNeed,    // Will need this range soon
    DontNeed,    // Won't need this range soon
}
```

<br>

### Iterator-Based Access (feature = "iterator")

> Since 0.9.7 the chunk and page iterators are zero-copy: they yield
> `MappedSlice<'a>` items directly from the mapped region with no
> allocation and no memcpy. Callers who genuinely need owned `Vec<u8>`
> buffers can use `chunks_owned()` / `pages_owned()` as a migration
> aid.

#### chunks

```rust
#[cfg(feature = "iterator")]
pub fn chunks(&self, chunk_size: usize) -> ChunkIterator<'_>
```

**Description**: Zero-copy iterator over fixed-size chunks. The iterator holds a read guard (on RW mappings) for its lifetime; concurrent `resize()` blocks until the iterator is dropped.

**Parameters**:
- `chunk_size`: Size of each chunk in bytes (final chunk may be shorter)

**Returns**: `ChunkIterator` yielding `MappedSlice<'a>` (derefs to `&[u8]`)

**Example**:
```rust
#[cfg(feature = "iterator")]
for chunk in mmap.chunks(4096) {
    let _len = chunk.len();
    let _first = chunk[0];
}
```

<br>

#### pages

```rust
#[cfg(feature = "iterator")]
pub fn pages(&self) -> PageIterator<'_>
```

**Description**: Zero-copy iterator over page-aligned chunks. Same lifetime guarantees as `chunks()`.

**Returns**: `PageIterator` yielding `MappedSlice<'a>`

**Example**:
```rust
#[cfg(feature = "iterator")]
for page in mmap.pages() {
    let _ = page.len();
}
```

<br>

#### chunks_owned / pages_owned

```rust
#[cfg(feature = "iterator")]
pub fn chunks_owned(&self, chunk_size: usize) -> ChunkIteratorOwned<'_>
#[cfg(feature = "iterator")]
pub fn pages_owned(&self) -> PageIteratorOwned<'_>
```

**Description**: Migration-aid iterators that yield `Result<Vec<u8>>`. Each item is allocated and the chunk's bytes are copied into it. Prefer the zero-copy `chunks()` / `pages()` for performance; reach for the owned variants only when you must hand off ownership.

**Example**:
```rust
#[cfg(feature = "iterator")]
for chunk in mmap.chunks_owned(4096) {
    let bytes: Vec<u8> = chunk?;
    let _ = bytes;
}
```

<br>

#### chunks_mut

```rust
#[cfg(feature = "iterator")]
pub fn chunks_mut(&self, chunk_size: usize) -> ChunkIteratorMut<'_>
```

**Description**: Creates a mutable iterator that processes chunks via callback. Since 0.9.7 the write guard is acquired ONCE for the entire iteration (instead of per-chunk).

**Parameters**:
- `chunk_size`: Size of each chunk in bytes

**Returns**: `ChunkIteratorMut` with `for_each_mut` method

**Example**:
```rust
#[cfg(feature = "iterator")]
mmap.chunks_mut(1024).for_each_mut(|_offset, chunk| {
    chunk.fill(0);
    Ok(())
})?;
```

Note: since 0.9.7 the closure returns the crate's `Result<()>`
(was `std::result::Result<(), E>`); the outer `Result` is no longer
nested. If your closure needs to surface a foreign error type, map
it into `MmapIoError::Io(...)` before returning.

<br>

### Atomic Operations (feature = "atomic")

> Since 0.9.5, atomic methods return wrapper types
> (`AtomicView<'_, T>` for single atoms, `AtomicSliceView<'_, T>` for
> slices) instead of bare `&T` / `&[T]`. The wrappers `Deref` to the
> underlying atomic, so call sites that do
> `view.fetch_add(...)` / `slice.iter()` keep working unchanged. The
> wrapper holds the read lock for its lifetime, so a concurrent
> `resize()` blocks while the view is alive (C3 fix).

#### atomic_u64

```rust
#[cfg(feature = "atomic")]
pub fn atomic_u64(&self, offset: u64) -> Result<AtomicView<'_, AtomicU64>>
```

**Description**: Returns an atomic view of a u64 value at the specified offset.

**Parameters**:
- `offset`: Byte offset (must be 8-byte aligned)

**Returns**: `Result<AtomicView<'_, AtomicU64>>` - wrapper that derefs to `&AtomicU64`

**Errors**:
- `MmapIoError::Misaligned` if offset is not 8-byte aligned
- `MmapIoError::OutOfBounds` if offset + 8 exceeds file bounds

**Example**:
```rust
#[cfg(feature = "atomic")]
use std::sync::atomic::Ordering;

let counter = mmap.atomic_u64(0)?;
counter.fetch_add(1, Ordering::SeqCst);
```

<br>

#### atomic_u32

```rust
#[cfg(feature = "atomic")]
pub fn atomic_u32(&self, offset: u64) -> Result<AtomicView<'_, AtomicU32>>
```

**Description**: Returns an atomic view of a u32 value at the specified offset.

**Parameters**:
- `offset`: Byte offset (must be 4-byte aligned)

**Returns**: `Result<AtomicView<'_, AtomicU32>>` - wrapper that derefs to `&AtomicU32`

**Errors**:
- `MmapIoError::Misaligned` if offset is not 4-byte aligned
- `MmapIoError::OutOfBounds` if offset + 4 exceeds file bounds

<br>

#### atomic_u64_slice

```rust
#[cfg(feature = "atomic")]
pub fn atomic_u64_slice(&self, offset: u64, count: usize) -> Result<AtomicSliceView<'_, AtomicU64>>
```

**Description**: Returns a slice of atomic u64 values.

**Parameters**:
- `offset`: Starting byte offset (must be 8-byte aligned)
- `count`: Number of u64 values

**Returns**: `Result<AtomicSliceView<'_, AtomicU64>>` - wrapper that derefs to `&[AtomicU64]`

<br>

#### atomic_u32_slice

```rust
#[cfg(feature = "atomic")]
pub fn atomic_u32_slice(&self, offset: u64, count: usize) -> Result<AtomicSliceView<'_, AtomicU32>>
```

**Description**: Returns a slice of atomic u32 values.

**Parameters**:
- `offset`: Starting byte offset (must be 4-byte aligned)
- `count`: Number of u32 values

**Returns**: `Result<AtomicSliceView<'_, AtomicU32>>` - wrapper that derefs to `&[AtomicU32]`

<br>

### Memory Locking (feature = "locking")

#### lock

```rust
#[cfg(feature = "locking")]
pub fn lock(&self, offset: u64, len: u64) -> Result<()>
```

**Description**: Locks memory pages to prevent them from being swapped out. Requires appropriate privileges.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Number of bytes to lock

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds
- `MmapIoError::LockFailed` if lock operation fails (often due to privileges)

**Example**:
```rust
#[cfg(feature = "locking")]
mmap.lock(0, 4096)?; // Lock first page
```

<br>

#### unlock

```rust
#[cfg(feature = "locking")]
pub fn unlock(&self, offset: u64, len: u64) -> Result<()>
```

**Description**: Unlocks previously locked memory pages.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Number of bytes to unlock

**Returns**: `Result<()>`

<br>

#### lock_all

```rust
#[cfg(feature = "locking")]
pub fn lock_all(&self) -> Result<()>
```

**Description**: Locks all pages of the memory-mapped file.

**Returns**: `Result<()>`

<br>

#### unlock_all

```rust
#[cfg(feature = "locking")]
pub fn unlock_all(&self) -> Result<()>
```

**Description**: Unlocks all pages of the memory-mapped file.

**Returns**: `Result<()>`

<br>

### File Watching (feature = "watch")

> Since 0.9.9 the watcher uses the OS-native event source on every
> supported platform: `inotify` on Linux, FSEvents on macOS, and
> `ReadDirectoryChangesW` on Windows. The polling fallback used
> through 0.9.8 is gone, along with the Windows mtime granularity
> issue that previously forced three watch tests to be ignored.
>
> Note: mmap-side writes (`mmap.update_region(...)` + `mmap.flush()`)
> only reach the FS watcher at OS-decided writeback time and are
> not a reliable trigger for any platform's native event source.
> Reliable detection comes from `std::fs` API writes by another
> process / handle. This matches the actual real-world use case
> for `watch`: detect changes made by something other than the
> current mapping holder.

#### watch

```rust
#[cfg(feature = "watch")]
pub fn watch<F>(&self, callback: F) -> Result<WatchHandle>
where
    F: Fn(ChangeEvent) + Send + 'static
```

**Description**: Watch the backing file for changes using the OS-native event source. The callback runs on a dedicated dispatcher thread for each detected change. Drop the returned `WatchHandle` to stop watching and release the OS subscription.

**Parameters**:
- `callback`: `Fn(ChangeEvent) + Send + 'static` invoked once per detected change

**Returns**: `Result<WatchHandle>` - drop to stop watching

**Platform behavior**:

| Platform | Backend                       | Typical latency      |
|----------|-------------------------------|----------------------|
| Linux    | `inotify`                     | <1 ms                |
| macOS    | FSEvents                      | <50 ms (coalesced)   |
| Windows  | `ReadDirectoryChangesW`       | <10 ms               |

Event coalescing differs by platform: FSEvents on macOS batches at ~50 ms by design; `inotify` and RDCW deliver events as the kernel sees them. Callers that need to debounce should do so on top of the callback (e.g. wait 100 ms after the last event before reacting).

**Errors**:
- `MmapIoError::WatchFailed` if the OS subscription cannot be established (missing inotify support, exhausted per-process watch limit, path disappeared between the call and the kernel registration, etc.)

**Example**:
```rust
#[cfg(feature = "watch")]
use mmap_io::{MemoryMappedFile, watch::ChangeEvent};

let mmap = MemoryMappedFile::open_ro("data.bin")?;
let handle = mmap.watch(|event: ChangeEvent| {
    println!("File changed: {:?}", event.kind);
})?;
// ...handle dropped at end of scope stops the watch.
# Ok::<(), mmap_io::MmapIoError>(())
```

<br>

#### ChangeEvent

```rust
#[cfg(feature = "watch")]
#[derive(Debug, Clone)]
pub struct ChangeEvent {
    pub offset: Option<u64>,  // Offset where change occurred (if known)
    pub len: Option<u64>,     // Length of changed region (if known)
    pub kind: ChangeKind,     // Type of change
}
```

<br>

#### ChangeKind

```rust
#[cfg(feature = "watch")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeKind {
    Modified,  // File content was modified
    Metadata,  // File metadata changed
    Removed,   // File was removed
}
```
<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Segment Types

### Segment

```rust
pub struct Segment { /* private fields */ }
```

**Description**: Immutable view into a region of a memory-mapped file.

**Methods**:
- `new(parent: Arc<MemoryMappedFile>, offset: u64, len: u64) -> Result<Self>`
- `as_slice(&self) -> Result<&[u8]>`
- `len(&self) -> u64`
- `is_empty(&self) -> bool`
- `offset(&self) -> u64`
- `parent(&self) -> &MemoryMappedFile`

**Example**:
```rust
use std::sync::Arc;
use mmap_io::segment::Segment;

let mmap = Arc::new(MemoryMappedFile::open_ro("data.bin")?);
let segment = Segment::new(mmap.clone(), 100, 50)?;
let data = segment.as_slice()?;
```

<br>

### SegmentMut

```rust
pub struct SegmentMut { /* private fields */ }
```

**Description**: Mutable view into a region of a memory-mapped file.

**Methods**:
- `new(parent: Arc<MemoryMappedFile>, offset: u64, len: u64) -> Result<Self>`
- `as_slice_mut(&self) -> Result<MappedSliceMut<'_>>`
- `write(&self, data: &[u8]) -> Result<()>`
- `len(&self) -> u64`
- `is_empty(&self) -> bool`
- `offset(&self) -> u64`
- `parent(&self) -> &MemoryMappedFile`

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Async Operations (feature = "async")

The crate exposes two layers of async helpers: manager-level
free functions for file lifecycle (`create_mmap_async`,
`copy_mmap_async`, `delete_mmap_async`) and instance methods on
`MemoryMappedFile` for write / flush operations. The instance
methods auto-flush after each call to guarantee post-await
durability across platforms (Async-Only Flushing).

### update_region_async

```rust
#[cfg(feature = "async")]
pub async fn update_region_async(&self, offset: u64, data: &[u8]) -> Result<()>
```

**Description**: Async write that also flushes after the write completes. The write itself runs on a `tokio::spawn_blocking` task; the flush is unconditional regardless of the configured `FlushPolicy`. This is the cross-platform-safe write path for async code.

**Parameters**:
- `offset`: Starting byte offset
- `data`: Bytes to write

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::InvalidMode` if not in `ReadWrite` mode
- `MmapIoError::OutOfBounds` if `offset + data.len()` exceeds file bounds
- `MmapIoError::FlushFailed` if the post-write flush fails

**Example**:
```rust
#[cfg(feature = "async")]
mmap.update_region_async(128, b"ASYNC-FLUSH").await?;
```

<br>

### flush_async

```rust
#[cfg(feature = "async")]
pub async fn flush_async(&self) -> Result<()>
```

**Description**: Async equivalent of `flush()`. Runs the underlying flush in a `spawn_blocking` task so the async scheduler is not blocked on disk I/O.

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::FlushFailed` if the flush operation fails

<br>

### flush_range_async

```rust
#[cfg(feature = "async")]
pub async fn flush_range_async(&self, offset: u64, len: u64) -> Result<()>
```

**Description**: Async equivalent of `flush_range()`. Same cancellation semantics as `flush_async`.

**Parameters**:
- `offset`: Starting byte offset
- `len`: Length of the range to flush

**Returns**: `Result<()>`

**Errors**:
- `MmapIoError::OutOfBounds` if range exceeds file bounds
- `MmapIoError::FlushFailed` if the flush operation fails

<br>

### create_mmap_async

```rust
#[cfg(feature = "async")]
pub async fn create_mmap_async<P: AsRef<Path>>(
    path: P, 
    size: u64
) -> Result<MemoryMappedFile>
```

**Description**: Asynchronously creates a new memory-mapped file.

**Parameters**:
- `path`: Path to the file to create
- `size`: Size in bytes

**Returns**: `Result<MemoryMappedFile>`

**Example**:
```rust
#[cfg(feature = "async")]
let mmap = mmap_io::manager::r#async::create_mmap_async("async.bin", 4096).await?;
```

<br>

### copy_mmap_async

```rust
#[cfg(feature = "async")]
pub async fn copy_mmap_async<P: AsRef<Path>>(src: P, dst: P) -> Result<()>
```

**Description**: Asynchronously copies a file.

**Parameters**:
- `src`: Source file path
- `dst`: Destination file path

**Returns**: `Result<()>`

<br>

### delete_mmap_async

```rust
#[cfg(feature = "async")]
pub async fn delete_mmap_async<P: AsRef<Path>>(path: P) -> Result<()>
```

**Description**: Asynchronously deletes a file.

**Parameters**:
- `path`: Path to the file to delete

**Returns**: `Result<()>`

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Utility Functions

### page_size

```rust
pub fn page_size() -> usize
```

**Description**: Returns the system's memory page size in bytes.

**Returns**: `usize` - Page size (typically 4096 on most systems)

**Example**:
```rust
use mmap_io::utils::page_size;

let ps = page_size();
println!("System page size: {} bytes", ps);
```

<br>

### align_up

```rust
pub fn align_up(value: u64, alignment: u64) -> u64
```

**Description**: Aligns a value up to the nearest multiple of alignment.

**Parameters**:
- `value`: Value to align
- `alignment`: Alignment boundary

**Returns**: `u64` - Aligned value

**Example**:
```rust
use mmap_io::utils::align_up;

let aligned = align_up(1001, 1024); // Returns 1024
let aligned2 = align_up(2048, 1024); // Returns 2048
```

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Safety and Best Practices

This crate uses `unsafe` code internally to interact with system memory mapping APIs:
- **Unix:** Uses `mmap`, `munmap`, `msync`, `madvise`, etc.
- **Windows:** Uses `CreateFileMappingW`, `MapViewOfFile`, `VirtualLock`, etc.

We expose only safe public APIs, but the following safety considerations apply:

<br>

### Mapped Memory Access
- You must not access memory after the file is closed, truncated, or deleted.
- Writing to `as_slice_mut()` is only allowed in `ReadWrite` or `CopyOnWrite` modes.
- Do not share mutable slices across threads without synchronization.

<br>

### Copy-On-Write (COW) Mode
- Writes are isolated per-process and never flushed to disk.
- `as_slice_mut()` is restricted in COW mode (future support planned).
- Flush in COW is a no-op for disk persistence.


<br>

### Flushing Behavior
- `flush()` ensures memory is flushed to the underlying file, but is a **best-effort** operation and may not guarantee disk sync unless `sync_all` or `fsync` is also called.
- Platform Parity: After `flush()`/`flush_range()`, opening a new RO mapping will observe the persisted bytes (entire file for `flush()`, specific region for `flush_range()`).
- Async-Only Flushing: When using async helpers, writes are auto-flushed after each async write to maintain cross-platform visibility guarantees.

<br>

### Thread Safety
`MemoryMappedFile` can be used across threads with `Arc`, but internal mutability requires synchronization if using `as_slice_mut()`.
- All operations are thread-safe through interior mutability
- Read operations can proceed concurrently
- Write operations are serialized through `RwLock`

<br>

### Performance Tips
1. Use `advise()` to hint access patterns for better OS optimization
2. Prefer page-aligned operations when possible
3. Use iterators for sequential processing of large files
4. Lock critical memory regions to prevent swapping
5. Batch writes and flush once rather than flushing frequently

<br>

### Common Pitfalls
1. Don't hold mutable guards across `flush()` calls (causes deadlock)
2. Ensure proper alignment when using atomic operations
3. Drop mappings before deleting files
4. Check privileges before using memory locking
5. Handle watch events promptly to avoid missing changes

<br>

### Error Handling
All operations return `Result<T, MmapIoError>`. Common error scenarios:
- `OutOfBounds`: Accessing beyond file boundaries
- `InvalidMode`: Operation not supported in current mode
- `Misaligned`: Atomic operations require proper alignment
- `LockFailed`: Usually due to insufficient privileges
- `Io`: Underlying filesystem errors

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br>

## Examples

### Database-like Usage
```rust
use mmap_io::{MemoryMappedFile, MmapAdvice};
use std::sync::atomic::Ordering;

// Create a file for storing records
let db = MemoryMappedFile::create_rw("database.bin", 1024 * 1024)?;

// Advise random access pattern
db.advise(0, 1024 * 1024, MmapAdvice::Random)?;

// Use atomic counter for record count
let record_count = db.atomic_u64(0)?;
record_count.store(0, Ordering::SeqCst);

// Write records starting at offset 64
let record_data = b"First record";
db.update_region(64, record_data)?;
record_count.fetch_add(1, Ordering::SeqCst);

db.flush()?;
```

<br>

### Game Asset Loading
```rust
use mmap_io::{MemoryMappedFile, MmapAdvice};

// Load game assets read-only
let assets = MemoryMappedFile::open_ro("game_assets.dat")?;

// Hint that we'll need textures soon
assets.advise(0, 50 * 1024 * 1024, MmapAdvice::WillNeed)?;

// Load texture data
let texture_data = assets.as_slice(1024 * 1024, 2048 * 2048 * 4)?;
```

<br>

### Log File Processing
```rust
#[cfg(feature = "iterator")]
use mmap_io::MemoryMappedFile;

let log = MemoryMappedFile::open_ro("app.log")?;

// Process log file line by line using chunks
for chunk in log.chunks(4096) {
    let data = chunk?;
    // Process lines in chunk...
}
```

<br>

### Concurrent Counter
```rust
#[cfg(feature = "atomic")]
use mmap_io::MemoryMappedFile;
use std::sync::Arc;
use std::thread;
use std::sync::atomic::Ordering;

let mmap = Arc::new(MemoryMappedFile::create_rw("counters.bin", 64)?);

// Initialize counters
for i in 0..8 {
    let counter = mmap.atomic_u64(i * 8)?;
    counter.store(0, Ordering::SeqCst);
}

// Spawn threads to increment counters
let handles: Vec<_> = (0..4).map(|i| {
    let mmap = Arc::clone(&mmap);
    thread::spawn(move || {
        let counter = mmap.atomic_u64(i * 8).unwrap();
        for _ in 0..1000 {
            counter.fetch_add(1, Ordering::SeqCst);
        }
    })
}).collect();

for handle in handles {
    handle.join().unwrap();
}
```

<hr>
<div align="right"><a href="#doc-top">&uarr; TOP</a></div>
<br><br>

## Version History
- **1.0.0**: Stable release. New surface: `AnonymousMmap` (process-local file-less mappings), `is_hugepage_backed()` runtime introspection, multi-process IPC integration test, sparse-file documentation. Doc-completeness pass: every `Result`-returning public method documents `# Errors`; every panicking method documents `# Panics`. `cargo public-api` snapshot committed and enforced via CI; `cargo-semver-checks` becomes a hard gate against unintended breaks. No API breaks vs 0.9.11.
- **0.9.11**: Patch release. Compat shims for the 0.9.7 semver violation (`as_slice_bytes`, `for_each_mut_legacy`). Runtime-agnostic async via `blocking` crate (smol/tokio/async-std all work). New `bytes::Bytes` integration (`feature = "bytes"`), `io::Read`+`io::Seek` cursor (`mmap.reader()`), and `AsFd`/`AsRawFd` (Unix) + `AsHandle`/`AsRawHandle` (Windows) trait impls.
- **0.9.10**: Pre-1.0 stabilization (Lockdown). Audit D1, D7, D8, R1-R7, D5 closed. Ten focused examples, `cargo-fuzz` scaffold, `docs/PERFORMANCE.md` with measured numbers, `cargo-audit` + `cargo-semver-checks` CI workflows, bench-regression hard gate. MSRV held at Rust 1.75.
- **0.9.9**: Native watch backends. `inotify` (Linux), FSEvents (macOS), `ReadDirectoryChangesW` (Windows) replace the polling implementation, backed by the `notify 6` crate gated on the `watch` feature. Three previously-ignored Windows watch tests now pass live; five new integration tests cover modify / truncate / extend / rapid-sequence / removed.
- **0.9.8**: Ergonomic API expansion (closes audit E1, E2, E6, E7, F2, F5, F9). Adds `open_or_create`, builder `open_or_create`, `from_file`, `unmap`, `flush_policy`, `pending_bytes`, `unsafe as_ptr` / `as_mut_ptr`, and `prefetch_range`. Hot-path bounds-check helpers (`ensure_in_bounds`, `slice_range`) and length/mode accessors marked `#[inline]`. Fixed a Duration underflow in the time-based flusher's slice arithmetic.
- **0.9.7**: Performance milestone (closes audit H1, H2, H4, E4). `as_slice` returns `MappedSlice<'_>` and works uniformly on RO / COW / RW (breaking). Iterators are zero-copy and yield `MappedSlice<'a>` directly (breaking); `chunks_owned` / `pages_owned` provided as migration aids. `touch_pages` rewritten as a tight `ptr::read_volatile` loop holding the lock once (~50-100x speedup on multi-GiB files). `chunks_mut().for_each_mut` flattened to `Result<()>` and holds the write guard once for the whole iteration. New workload-pattern benches and `bench-regression.yml` CI workflow.
- **0.9.6**: Unsafe audit (closes audit S2, S3); SAFETY comments rewritten with platform-spec citations; `docs/SAFETY.md` added; property-test suite (`tests/proptest_bounds.rs`, `tests/proptest_atomic.rs`, `tests/proptest_flush.rs`) added via `proptest 1.5`; CI matrix-feature gate fix.
- **0.9.5**: Correctness bugfix release. Closes audit C1 (`flush_range` accumulator), C2 (`FlushPolicy::EveryMillis` now actually flushes), C3 (atomic-view UAF; methods now return `AtomicView<'_, T>` / `AtomicSliceView<'_, T>` wrappers), H5 (`WatchHandle::drop` signals thread), H6 (`Segment::as_slice` re-validates bounds), H7 (`page_size()` cached via `OnceLock`).
- **0.9.4**: Production-Ready Performance 
- **0.9.3**: Final optimizations, cleaned codebase.
- **0.9.0**: Fixed Remaining Issues, Finalized Codebase for Stable Beta Release.
- **0.8.0**: Added Async-Only Flushing APIs; Platform Parity docs and tests; Huge Pages docs.
- **0.7.5**: Added Flush Policy.
- **0.7.3**: Fixed Build Errors.
- **0.7.2**: Added CHANGELOG and updated Documentation.
- **0.7.1**: Added atomic, locking, and watch features.
- **0.7.0**: Added advise and iterator features.
- **0.5.0**: Added copy-on-write mode support.
- **0.3.0**: Added async support with Tokio.
- **0.2.0**: basic mmap functionality with segment types.
- **0.1.0**: Initial release.

<br>

View the [CHANGELOG](../CHANGELOG.md).

<br>


<!--// LICENSE // -->
<div align="center">
    <br>
    <h2>LICENSE</h2>
    <p>
        Licensed under the <b>Apache License</b>, <b>Version 2.0</b>. 
        <br>
        See <b><a href="../LICENSE">LICENSE</a></b> file for details.
    </p>
</div>


<!--// COPYRIGHT // -->
<div align="center">
    <br>
    <h2></h2>
    <sub>Copyright &copy; 2026 James Gober.</sub>
</div>