rsmount 0.2.2

Safe Rust wrapper around the `util-linux/libmount` C library
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
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
// Copyright (c) 2023 Nick Piaddo
// SPDX-License-Identifier: Apache-2.0 OR MIT

// From dependency library
use enum_iterator::all;

// From standard library
use std::collections::HashSet;
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::path::{Path, PathBuf};
use std::ptr::NonNull;
use std::str::FromStr;

// From this library
use crate::core::cache::Cache;
use crate::core::device::Tag;
use crate::core::entries::{FsTabEntry, MountInfoEntry};
use crate::core::flags::MountFlag;
use crate::core::flags::UserspaceMountFlag;
use crate::core::fs::{FileLock, FileSystem};
use crate::tables::{FsTab, GcItem, MountInfo};
use crate::{owning_mut_from_ptr, owning_ref_from_ptr};

use crate::ffi_utils;
use crate::mount::ExitCode;
use crate::mount::ExitStatus;
use crate::mount::MntBuilder;
use crate::mount::MountBuilder;
use crate::mount::MountError;
use crate::mount::MountIter;
use crate::mount::MountNamespace;
use crate::mount::MountOptionsMode;
use crate::mount::MountSource;
use crate::mount::ProcessExitStatus;
use crate::mount::ReMountIter;

/// Object to mount/unmount a device.
#[derive(Debug)]
pub struct Mount {
    pub(crate) inner: *mut libmount::libmnt_context,
    pub(crate) gc: Vec<GcItem>,
}

impl Mount {
    #[doc(hidden)]
    /// Wraps a raw `libmount::mnt_context` pointer with a safe `Mount`.
    #[allow(dead_code)]
    pub(crate) fn from_ptr(ptr: *mut libmount::libmnt_context) -> Mount {
        Self {
            inner: ptr,
            gc: vec![],
        }
    }

    #[doc(hidden)]
    /// Creates a new `Mount`.
    pub(crate) fn new() -> Result<Mount, MountError> {
        log::debug!("Mount::new creating a new `Mount` instance");

        let mut inner = MaybeUninit::<*mut libmount::libmnt_context>::zeroed();

        unsafe {
            inner.write(libmount::mnt_new_context());
        }

        match unsafe { inner.assume_init() } {
            inner if inner.is_null() => {
                let err_msg = "failed to create a new `Mount` instance".to_owned();
                log::debug!(
                    "Mount::new {}. libmount::mnt_new_contex returned a NULL pointer",
                    err_msg
                );

                Err(MountError::Creation(err_msg))
            }
            inner => {
                log::debug!("Mount::new created a new `Mount` instance");
                let mount = Self::from_ptr(inner);

                Ok(mount)
            }
        }
    }

    #[doc(hidden)]
    /// Converts a function's return code to unified `libmount` exit code.
    fn return_code_to_exit_status(&self, return_code: i32) -> Result<ExitStatus, MountError> {
        log::debug!(
            "Mount::return_code_to_exit_status converting to exit status the return code: {:?}",
            return_code
        );

        const BUFFER_LENGTH: usize = 4097; // 4096 characters + `\0`
        let mut buffer: Vec<libc::c_char> = vec![0; BUFFER_LENGTH];

        let rc = unsafe {
            libmount::mnt_context_get_excode(
                self.inner,
                return_code,
                buffer.as_mut_ptr(),
                BUFFER_LENGTH,
            )
        };

        let exit_code = ExitCode::try_from(rc)?;
        let error_message = ffi_utils::c_char_array_to_string(buffer.as_ptr());
        let exit_status = ExitStatus::new(exit_code, error_message);

        log::debug!(
            "Mount::return_code_to_exit_status converted return code: {:?} to exit status {:?}",
            return_code,
            exit_status
        );

        Ok(exit_status)
    }

    //---- BEGIN setters

    #[doc(hidden)]
    /// Enables/disables path canonicalization.
    fn disable_canonicalize(
        mount: *mut libmount::libmnt_context,
        disable: bool,
    ) -> Result<(), MountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_canonicalize(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Mount::disable_canonicalize {}d path canonicalization",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} path canonicalization", op_str);
                log::debug!("Mount::disable_canonicalize {}. libmount::mnt_context_disable_canonicalize returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Disables path canonicalization.
    pub(crate) fn disable_path_canonicalization(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::disable_path_canonicalization disabling path canonicalization");

        Self::disable_canonicalize(self.inner, true)
    }

    #[doc(hidden)]
    /// Enables path canonicalization.
    pub(crate) fn enable_path_canonicalization(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::enable_path_canonicalization enabling path canonicalization");

        Self::disable_canonicalize(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables mount helpers.
    fn disable_mnt_helpers(
        mount: *mut libmount::libmnt_context,
        disable: bool,
    ) -> Result<(), MountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_helpers(mount, op) };

        match result {
            0 => {
                log::debug!("Mount::disable_mnt_helpers {}d mount helpers", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} mount helpers", op_str);
                log::debug!("Mount::disable_mnt_helpers {}. libmount::mnt_context_disable_helpers returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Prevents `Mount` from calling `/sbin/mount.suffix` helper functions, where *suffix* is a file system type.
    pub(crate) fn disable_helpers(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::disable_helpers disabling mount helpers");

        Self::disable_mnt_helpers(self.inner, true)
    }

    #[doc(hidden)]
    /// Allows `Mount` to call `/sbin/mount.suffix` helper functions, where *suffix* is a file system type.
    pub(crate) fn enable_helpers(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::enable_helpers enabling mount helpers");

        Self::disable_mnt_helpers(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables mount point lookup.
    fn disable_swap_match(
        mount: *mut libmount::libmnt_context,
        disable: bool,
    ) -> Result<(), MountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_swapmatch(mount, op) };

        match result {
            0 => {
                log::debug!("Mount::disable_swap_match {}d mount point lookup", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} mount point lookup", op_str);
                log::debug!("Mount::disable_swap_match {}. libmount::mnt_context_disable_swapmatch returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Disables mount point lookup in `/etc/fstab` when either the mount `source` or `target` is
    /// not set.
    pub(crate) fn disable_mount_point_lookup(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::disable_mount_point_lookup disabling mount point lookup");

        Self::disable_swap_match(self.inner, true)
    }

    #[doc(hidden)]
    /// Enables mount point lookup in `/etc/fstab` when either the mount `source` or `target` is
    /// not set.
    pub(crate) fn enable_mount_point_lookup(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::enable_mount_point_lookup enabling mount point lookup");

        Self::disable_swap_match(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables userspace mount table updates.
    fn disable_mtab(mount: *mut libmount::libmnt_context, disable: bool) -> Result<(), MountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_mtab(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Mount::disable_mtab {}d userspace mount table updates",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} userspace mount table updates", op_str);
                log::debug!("Mount::disable_mtab {}. libmount::mnt_context_disable_mtab returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Disables userspace mount table updates.
    pub(crate) fn do_not_update_utab(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::do_not_update_utab disabling userspace mount table updates");

        Self::disable_mtab(self.inner, true)
    }

    #[doc(hidden)]
    /// Enables userspace mount table updates.
    pub(crate) fn update_utab(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::update_utab enabling userspace mount table updates");

        Self::disable_mtab(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables skipping all mount source preparation, mount option analysis, and the actual mounting process.
    /// (see the [`mount` command](https://www.man7.org/linux/man-pages/man8/mount.8.html) man page, option `-f, --fake`)
    fn enable_fake(mount: *mut libmount::libmnt_context, enable: bool) -> Result<(), MountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_fake(mount, op) };

        match result {
            0 => {
                log::debug!("Mount::enable_fake {}d dry run", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} dry run", op_str);
                log::debug!("Mount::enable_fake {}. libmount::mnt_context_enable_fake returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Skips all mount source preparation, mount option analysis, and the actual mounting process.
    pub(crate) fn enable_dry_run(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::enable_dry_run enabling dry run");

        Self::enable_fake(self.inner, true)
    }

    #[doc(hidden)]
    pub(crate) fn disable_dry_run(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::disable_dry_run disabling dry run");

        Self::enable_fake(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables `Mount` functionality to force a device to be mounted in read-write mode.
    fn enable_force_mount_device_read_write(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), MountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_rwonly_mount(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Mount::enable_force_mount_device_read_write {}d force mount device read-write",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} force mount device read-write", op_str);
                log::debug!("Mount::enable_force_mount_device_read_write {}. libmount::mnt_context_enable_rwonly_mount returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Forces a device to be mounted in read-write mode.
    pub(crate) fn enable_force_mount_read_write(&mut self) -> Result<(), MountError> {
        log::debug!(
            "Mount::enable_force_mount_read_write enabling force mount device in read-write mode"
        );

        Self::enable_force_mount_device_read_write(self.inner, true)
    }

    #[doc(hidden)]
    /// Sets a device to be mounted in read-only mode.
    pub(crate) fn disable_force_mount_read_write(&mut self) -> Result<(), MountError> {
        log::debug!(
            "Mount::disable_force_mount_read_write disabling force mount device in read-write mode"
        );

        Self::enable_force_mount_device_read_write(self.inner, false)
    }

    #[cfg(mount = "v2_39")]
    #[doc(hidden)]
    /// Enables/disables ignore `autofs` mount table entries.
    fn ignore_autofs(mount: *mut libmount::libmnt_context, ignore: bool) -> Result<(), MountError> {
        let op = if ignore { 1 } else { 0 };
        let op_str = if ignore {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_noautofs(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Mount::ignore_autofs {}d ignore `autofs` mount table entries",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} ignore `autofs` mount table entries", op_str);
                log::debug!("Mount::ignore_autofs {}. libmount::mnt_context_enable_noautofs returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[cfg(mount = "v2_39")]
    #[doc(hidden)]
    /// Enables `Mount` to ignore `autofs` mount table entries.
    pub(crate) fn enable_ignore_autofs(&mut self) -> Result<(), MountError> {
        log::debug!(
            "Mount::enable_ignore_autofs enabling `Mount` functionality to ignore `autofs` mount table entries"
        );

        Self::ignore_autofs(self.inner, true)
    }

    #[cfg(mount = "v2_39")]
    #[doc(hidden)]
    /// Disables `Mount` to ignore `autofs` mount table entries.
    pub(crate) fn disable_ignore_autofs(&mut self) -> Result<(), MountError> {
        log::debug!(
            "Mount::enable_ignore_autofs disabling `Mount` functionality to ignore `autofs` mount table entries"
        );

        Self::ignore_autofs(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables `Mount` functionality to ignore mount options not supported by a file
    /// system.
    fn ignore_unsupported_mount_options(
        mount: *mut libmount::libmnt_context,
        ignore: bool,
    ) -> Result<(), MountError> {
        let op = if ignore { 1 } else { 0 };
        let op_str = if ignore {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_sloppy(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Mount::ignore_unsupported_mount_options {}d ignore unsupported mount options",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} ignore unsupported mount options", op_str);
                log::debug!("Mount::ignore_unsupported_mount_options {}. libmount::mnt_context_enable_sloppy returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables `Mount` to ignore `autofs` mount table entries.
    pub(crate) fn enable_ignore_unsupported_mount_options(&mut self) -> Result<(), MountError> {
        log::debug!(
            "Mount::enable_ignore_unsupported_mount_options enabling `Mount` functionality to ignore mount options not supported by a file system"
        );

        Self::ignore_unsupported_mount_options(self.inner, true)
    }

    #[doc(hidden)]
    /// Disables `Mount` to ignore `autofs` mount table entries.
    pub(crate) fn disable_ignore_unsupported_mount_options(&mut self) -> Result<(), MountError> {
        log::debug!(
            "Mount::disable_ignore_unsupported_mount_options disabling `Mount` functionality to ignore mount options not supported by a file system"
        );

        Self::ignore_unsupported_mount_options(self.inner, false)
    }

    #[doc(hidden)]
    /// Disables all of `libmount`'s security protocols using this `Mount` as if its user has root
    /// permissions.
    pub(crate) fn force_user_mount(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::force_user_mount removing all safety checks");

        let result = unsafe { libmount::mnt_context_force_unrestricted(self.inner) };

        match result {
            0 => {
                log::debug!("Mount::force_user_mount removed all safety checks");

                Ok(())
            }
            code => {
                let err_msg = "failed to remove all safety checks".to_owned();
                log::debug!("Mount::force_user_mount {}. libmount::mnt_context_force_unrestricted returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables/disables verbose output.
    fn enable_verbose(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), MountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_verbose(mount, op) };

        match result {
            0 => {
                log::debug!("Mount::enable_verbose {}d verbose output", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} verbose output", op_str);
                log::debug!("Mount::enable_verbose {}. libmount::mnt_context_enable_verbose returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables `Mount` to check that a device is not already mounted before mounting it.
    pub(crate) fn enable_verbose_output(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::enable_verbose_output enabling verbose output");

        Self::enable_verbose(self.inner, true)
    }

    #[doc(hidden)]
    /// Disables `Mount` to check that a device is not already mounted before mounting it.
    pub(crate) fn disable_verbose_output(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::disable_verbose_output disabling verbose output");

        Self::enable_verbose(self.inner, false)
    }

    #[cfg(mount = "v2_39")]
    #[doc(hidden)]
    /// Enables/disables `Mount` functionality to check that a device is not already mounted before mounting it.
    fn enable_only_once(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), MountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_onlyonce(mount, op) };

        match result {
            0 => {
                log::debug!("Mount::enable_only_once {}d mount only once", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} mount only once", op_str);
                log::debug!("Mount::enable_only_once {}. libmount::mnt_context_enable_onlyonce returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[cfg(mount = "v2_39")]
    #[doc(hidden)]
    /// Enables `Mount` to check that a device is not already mounted before mounting it.
    pub(crate) fn enable_mount_only_once(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::enable_mount_only_once enabling check if device not already mounted");

        Self::enable_only_once(self.inner, true)
    }

    #[cfg(mount = "v2_39")]
    #[doc(hidden)]
    /// Disables `Mount` to check that a device is not already mounted before mounting it.
    pub(crate) fn disable_mount_only_once(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::disable_mount_only_once disabling check if device not already mounted");

        Self::enable_only_once(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables parallel mounts.
    fn enable_fork(mount: *mut libmount::libmnt_context, enable: bool) -> Result<(), MountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_fork(mount, op) };

        match result {
            0 => {
                log::debug!("Mount::enable_fork {}d parallel mounts", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} parallel mounts", op_str);
                log::debug!("Mount::enable_fork {}. libmount::mnt_context_enable_fork returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables parallel mounts.
    pub(crate) fn enable_parallel_mount(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::enable_parallel_mount enabling parallel mounts");

        Self::enable_fork(self.inner, true)
    }

    #[doc(hidden)]
    /// Disables parallel mounts.
    pub(crate) fn disable_parallel_mount(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::disable_parallel_mount disabling parallel mounts");

        Self::enable_fork(self.inner, false)
    }

    #[doc(hidden)]
    pub(crate) fn set_cache(&mut self, cache: Cache) -> Result<(), MountError> {
        log::debug!("Mount::set_cache overriding internal cache with custom instance");

        let result = unsafe { libmount::mnt_context_set_cache(self.inner, cache.inner) };

        match result {
            0 => {
                log::debug!("Mount::set_cache overrode internal cache with custom table");

                Ok(())
            }
            code => {
                let err_msg = "failed to override internal cache with custom instance".to_owned();
                log::debug!("Mount::set_cache {}. libmount::mnt_context_set_cache returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Overrides this `Mount`'s internal `fstab` with a custom table.
    pub(crate) fn set_fstab(&mut self, table: FsTab) -> Result<(), MountError> {
        log::debug!("Mount::set_fstab overriding internal fstab with custom table");

        let result = unsafe { libmount::mnt_context_set_fstab(self.inner, table.inner) };

        match result {
            0 => {
                log::debug!("Mount::set_fstab overrode internal fstab with custom table");

                Ok(())
            }
            code => {
                let err_msg = "failed to override internal fstab with custom table".to_owned();
                log::debug!("Mount::set_fstab {}. libmount::mnt_context_set_fstab returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets a list of file systems.
    pub(crate) fn set_file_systems_filter<T>(&mut self, fs_list: T) -> Result<(), MountError>
    where
        T: AsRef<str>,
    {
        let fs_list = fs_list.as_ref();
        let fs_list_cstr = ffi_utils::as_ref_str_to_c_string(fs_list)?;
        log::debug!(
            "Mount::set_file_systems_filter setting the list of file systems: {:?}",
            fs_list
        );

        let result =
            unsafe { libmount::mnt_context_set_fstype_pattern(self.inner, fs_list_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_file_systems_filter set the list of file systems: {:?}",
                    fs_list
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set file systems list: {:?}", fs_list);
                log::debug!("Mount::set_file_systems_filter {}. libmount::mnt_context_set_fstype_pattern returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    // #[doc(hidden)]
    // /// Overrides this `Mount`'s internal mount table entry with a custom one.
    // pub(crate) fn set_table_entry(&mut self, entry: MountTableEntry) -> Result<(), MountError> {
    //     log::debug!("Mount::set_table_entry overriding internal table entry");

    //     let result = unsafe { libmount::mnt_context_set_fs(self.inner, entry.ptr) };

    //     match result {
    //         0 => {
    //             log::debug!("Mount::set_table_entry overrode internal table entry");

    //             Ok(())
    //         }
    //         code => {
    //             let err_msg = "failed to overrride internal table entry".to_owned();
    //             log::debug!("Mount::set_table_entry {}. libmount::mnt_context_set_fs returned error code: {:?}", err_msg, code);

    //             Err(MountError::Config(err_msg))
    //         }
    //     }
    // }

    #[doc(hidden)]
    /// Overrides the data argument of the [`mount` syscall](https://www.man7.org/linux/man-pages/man2/mount.2.html).
    pub(crate) fn set_mount_data(&mut self, data: NonNull<libc::c_void>) -> Result<(), MountError> {
        log::debug!("Mount::set_mount_data overriding data argument of mount syscall");

        let result = unsafe { libmount::mnt_context_set_mountdata(self.inner, data.as_ptr()) };

        match result {
            0 => {
                log::debug!("Mount::set_mount_data overrode data argument of mount syscall");

                Ok(())
            }
            code => {
                let err_msg = "failed to override data argument of mount syscall".to_owned();
                log::debug!("Mount::set_mount_data {}. libmount::mnt_context_set_mountdata returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets mount options.
    pub(crate) fn set_mount_options<T>(&mut self, options_list: T) -> Result<(), MountError>
    where
        T: AsRef<str>,
    {
        let options_list = options_list.as_ref();
        let options_list_cstr = ffi_utils::as_ref_str_to_c_string(options_list)?;
        log::debug!(
            "Mount::set_mount_options setting mount options: {:?}",
            options_list
        );

        let result =
            unsafe { libmount::mnt_context_set_options(self.inner, options_list_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_mount_options set mount options: {:?}",
                    options_list
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount options: {:?}", options_list);
                log::debug!("Mount::set_mount_options {}. libmount::mnt_context_set_options returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets mount options mode.
    pub(crate) fn set_mount_options_mode(
        &mut self,
        mode: Vec<MountOptionsMode>,
    ) -> Result<(), MountError> {
        log::debug!(
            "Mount::set_mount_options_mode setting mount options mode: {:?}",
            mode
        );

        let options_mode = mode.iter().fold(0, |acc, &m| acc | (m as i32));

        let result = unsafe { libmount::mnt_context_set_optsmode(self.inner, options_mode) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_mount_options_mode set mount options mode: {:?}",
                    mode
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount options mode: {:?}", mode);
                log::debug!("Mount::set_mount_options_mode {}. libmount::mnt_context_set_optsmode returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets the pattern of mount options to use as filter when mounting devices.
    pub(crate) fn set_mount_options_filter<T>(&mut self, options_list: T) -> Result<(), MountError>
    where
        T: AsRef<str>,
    {
        let options_list = options_list.as_ref();
        let options_list_cstr = ffi_utils::as_ref_str_to_c_string(options_list)?;
        log::debug!(
            "Mount::set_mount_options_filter setting mount options filter: {:?}",
            options_list
        );

        let result = unsafe {
            libmount::mnt_context_set_options_pattern(self.inner, options_list_cstr.as_ptr())
        };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_mount_options_filter set mount options filter: {:?}",
                    options_list
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount options filter: {:?}", options_list);
                log::debug!("Mount::set_mount_options_filter {}. libmount::mnt_context_set_options_pattern returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Set the `Mount`'s source.
    fn set_source(mount: *mut libmount::libmnt_context, source: CString) -> Result<(), MountError> {
        let result = unsafe { libmount::mnt_context_set_source(mount, source.as_ptr()) };

        match result {
            0 => {
                log::debug!("Mount::set_source mount source set");

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount source: {:?}", source);
                log::debug!("Mount::set_source {}. libmount::mnt_context_set_source returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets the location/ID of the device to mount.
    ///
    /// A source can take any of the following forms:
    /// - block device path (e.g. `/dev/sda1`),
    /// - network ID:
    ///     - Samba: `smb://ip-address-or-hostname/shared-dir`,
    ///     - NFS: `hostname:/shared-dir`  (e.g. knuth.cwi.nl:/dir)
    ///     - SSHFS: `[user@]ip-address-or-hostname:[/shared-dir]` elements in brackets are optional (e.g.
    ///     tux@192.168.0.1:/share)
    ///
    /// - label:
    ///     - `UUID=uuid`,
    ///     - `LABEL=label`,
    ///     - `PARTLABEL=label`,
    ///     - `PARTUUID=uuid`,
    ///     - `ID=id`.
    pub(crate) fn set_mount_source(&mut self, source: MountSource) -> Result<(), MountError> {
        let source = source.to_string();
        let source_cstr = ffi_utils::as_ref_path_to_c_string(&source)?;
        log::debug!("Mount::set_mount_source setting mount source: {:?}", source);

        Self::set_source(self.inner, source_cstr)
    }

    #[doc(hidden)]
    /// Sets this `Mount`'s mount point.
    pub(crate) fn set_mount_target<T>(&mut self, target: T) -> Result<(), MountError>
    where
        T: AsRef<Path>,
    {
        let target = target.as_ref();
        let target_cstr = ffi_utils::as_ref_path_to_c_string(target)?;
        log::debug!(
            "Mount::set_mount_target setting mount target to: {:?}",
            target
        );

        let result = unsafe { libmount::mnt_context_set_target(self.inner, target_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!("Mount::set_mount_target set mount target to: {:?}", target);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount target to: {:?}", target);
                log::debug!("Mount::set_mount_target {}. libmount::mnt_context_set_target returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets the namespace of this `Mount`'s mount point.
    pub(crate) fn set_mount_target_namespace<T>(&mut self, path: T) -> Result<(), MountError>
    where
        T: AsRef<Path>,
    {
        let path = path.as_ref();
        let path_cstr = ffi_utils::as_ref_path_to_c_string(path)?;
        log::debug!(
            "Mount::set_mount_target_namespace setting mount target namespace: {:?}",
            path
        );

        let result = unsafe { libmount::mnt_context_set_target_ns(self.inner, path_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_mount_target_namespace set mount target namespace: {:?}",
                    path
                );

                Ok(())
            }
            code if code == -libc::ENOSYS => {
                let err_msg = "`libmount` was compiled without namespace support".to_owned();
                log::debug!("Mount::set_mount_target_namespace {}. libmount::mnt_context_set_target returned error code: {:?}", err_msg, code);

                Err(MountError::NoNamespaceSupport(err_msg))
            }
            code => {
                let err_msg = format!("failed to set mount target namespace: {:?}", path);
                log::debug!("Mount::set_mount_target_namespace {}. libmount::mnt_context_set_target_ns returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets the prefix of this `Mount`'s mount point.
    pub(crate) fn set_mount_target_prefix<T>(&mut self, path: T) -> Result<(), MountError>
    where
        T: AsRef<Path>,
    {
        let path = path.as_ref();
        let path_cstr = ffi_utils::as_ref_path_to_c_string(path)?;
        log::debug!(
            "Mount::set_mount_target_prefix setting mount target prefix: {:?}",
            path
        );

        let result =
            unsafe { libmount::mnt_context_set_target_prefix(self.inner, path_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_mount_target_prefix set mount target prefix: {:?}",
                    path
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount target prefix: {:?}", path);
                log::debug!("Mount::set_mount_target_prefix {}. libmount::mnt_context_set_target_prefix returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets userspace mount flags.
    pub(crate) fn set_userspace_mount_flags(
        &mut self,
        flags: Vec<UserspaceMountFlag>,
    ) -> Result<(), MountError> {
        log::debug!(
            "Mount::set_userspace_mount_flags setting userspace mount flags: {:?}",
            flags
        );

        let bits = flags.iter().fold(0, |acc, &flag| acc | (flag as u64));

        let result = unsafe { libmount::mnt_context_set_user_mflags(self.inner, bits) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_userspace_mount_flags set userspace mount flags: {:?}",
                    flags
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set userspace mount flags: {:?}", flags);
                log::debug!("Mount::set_userspace_mount_flags {}. libmount::mnt_context_set_user_mflags returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }
    //---- END setters

    //---- BEGIN mutators
    /// Creates a [`MountBuilder`] to configure and construct a new `Mount`
    /// instance.
    ///
    /// Call the `MountBuilder`'s [`build()`](MountBuilder::build) method to
    /// construct a new `Mount` instance.
    pub fn builder() -> MountBuilder {
        log::debug!("Mount::builder creating new `MountBuilder` instance");
        MntBuilder::builder()
    }

    /// Sets this `Mount`'s mount flags.
    pub fn set_mount_flags<T>(&mut self, flags: T) -> Result<(), MountError>
    where
        T: AsRef<[MountFlag]>,
    {
        let flags = flags.as_ref();
        log::debug!("Mount::set_mount_flags setting mount flags: {:?}", flags);

        let bits = flags.iter().fold(0, |acc, &flag| acc | (flag as u64));

        let result = unsafe { libmount::mnt_context_set_mflags(self.inner, bits) };

        match result {
            0 => {
                log::debug!("Mount::set_mount_flags set mount flags: {:?}", flags);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount flags: {:?}", flags);
                log::debug!("Mount::set_mount_flags {}. libmount::mnt_context_set_mflags returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    /// Sets this `Mount`'s file system type.
    pub fn set_file_system_type(&mut self, fs_type: FileSystem) -> Result<(), MountError> {
        log::debug!(
            "Mount::set_file_system_type setting file system type: {:?}",
            fs_type
        );

        let fs_type_cstr = ffi_utils::as_ref_str_to_c_string(&fs_type)?;

        let result = unsafe { libmount::mnt_context_set_fstype(self.inner, fs_type_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_file_system_type set file system type: {:?}",
                    fs_type
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set file system type: {:?}", fs_type);
                log::debug!("Mount::set_file_system_type {}. libmount::mnt_context_set_fstype returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    /// Appends a comma-delimited list of mount options.
    pub fn append_mount_options<T>(&mut self, option_list: T) -> Result<(), MountError>
    where
        T: AsRef<str>,
    {
        let option_list = option_list.as_ref();
        let opts_cstr = ffi_utils::as_ref_str_to_c_string(option_list)?;
        log::debug!(
            "Mount::append_mount_options appending mount options: {:?}",
            option_list
        );

        let result =
            unsafe { libmount::mnt_context_append_options(self.inner, opts_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Mount::append_mount_options appended mount options: {:?}",
                    option_list
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to append mount options: {:?}", option_list);
                log::debug!("Mount::append_mount_options {}. libmount::mnt_context_append_options returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    /// Mounts a device using the [`mount` syscall](https://www.man7.org/linux/man-pages/man2/mount.2.html) and/or
    /// [`mount` helpers](https://www.man7.org/linux/man-pages/man8/mount.8.html#EXTERNAL_HELPERS).
    ///
    /// Equivalent to running the following functions in succession:
    /// - [`Mount::prepare_mount`]
    /// - [`Mount::call_mount_syscall`]
    /// - [`Mount::finalize_mount`]
    pub fn mount_device(&mut self) -> Result<ExitStatus, MountError> {
        log::debug!("Mount::mount_device mounting device");

        let return_code = unsafe { libmount::mnt_context_mount(self.inner) };
        self.return_code_to_exit_status(return_code)
    }

    /// Validates this `Mount`'s parameters before it tries to mount a device.
    ///
    /// **Note:** you do not need to call this method if you are using [`Mount::mount_device`], it
    /// will take care of parameter validation.
    pub fn prepare_mount(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::prepare_mount preparing for mount");

        let result = unsafe { libmount::mnt_context_prepare_mount(self.inner) };

        match result {
            0 => {
                log::debug!("Mount::prepare_mount preparation successful");

                Ok(())
            }
            code => {
                let err_msg = "failed to prepare for device mount".to_owned();
                log::debug!("Mount::prepare_mount {}. libmount::mnt_context_prepare_mount returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    /// Runs the [`mount` syscall](https://www.man7.org/linux/man-pages/man2/mount.2.html) and/or
    /// [mount helpers](https://www.man7.org/linux/man-pages/man8/mount.8.html#EXTERNAL_HELPERS).
    ///
    /// If you want to call this function again with different mount flags and/or file system type:
    /// - modify the corresponding parameters,
    /// - call [`Mount::reset_syscall_exit_status`],
    /// - then try again.
    ///
    /// **Note:** you do not need to call this method if you are using [`Mount::mount_device`], it
    /// will take care of everything for you.
    pub fn call_mount_syscall(&mut self) -> Result<ExitStatus, MountError> {
        log::debug!("Mount::call_mount_syscall mounting device");

        let return_code = unsafe { libmount::mnt_context_do_mount(self.inner) };
        self.return_code_to_exit_status(return_code)
    }

    /// Updates the system's mount tables to take the last modifications into account. You should
    /// call this function after invoking [`Mount::call_mount_syscall`].
    ///
    /// **Note:** you do not need to call this method if you are using [`Mount::mount_device`], it
    /// will take care of finalizing the mount.
    pub fn finalize_mount(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::finalize_mount finalizing mount");

        let result = unsafe { libmount::mnt_context_finalize_mount(self.inner) };

        match result {
            0 => {
                log::debug!("Mount::finalize_mount finalized mount");

                Ok(())
            }
            code => {
                let err_msg = "failed to finalize device mount".to_owned();
                log::debug!("Mount::finalize_mount {}. libmount::mnt_context_finalize_mount returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Searches `/proc/self/mountinfo` for an entry with a field matching the given `target`.
    fn find_mounted_entry<'a>(
        mount: &mut Self,
        target: CString,
    ) -> Result<&'a MountInfoEntry, MountError> {
        let mut ptr = MaybeUninit::<*mut libmount::libmnt_fs>::zeroed();

        let result = unsafe {
            libmount::mnt_context_find_umount_fs(mount.inner, target.as_ptr(), ptr.as_mut_ptr())
        };

        match result {
            0 => {
                log::debug!(
                    "Mount::find_mounted_entry found mount table entry matching {:?}",
                    target
                );
                let ptr = unsafe { ptr.assume_init() };
                let entry = owning_ref_from_ptr!(mount, MountInfoEntry, ptr);

                Ok(entry)
            }
            code => {
                let err_msg = format!("failed to find mount table entry matching {:?}", target);
                log::debug!("Mount::find_mounted_entry {}. libmount::mnt_context_find_umount_fs returned error code: {:?}", err_msg, code);

                Err(MountError::Action(err_msg))
            }
        }
    }

    /// Searches `/proc/self/mountinfo` for an entry with a source field matching the given `source`.
    pub fn find_entry_matching_source<T>(
        &mut self,
        source: T,
    ) -> Result<&MountInfoEntry, MountError>
    where
        T: AsRef<Path>,
    {
        let source = source.as_ref();
        let source_cstr = ffi_utils::as_ref_path_to_c_string(source)?;
        log::debug!(
            "Mount::find_entry_matching_source finding mounted table entry matching source: {:?}",
            source
        );

        Self::find_mounted_entry(self, source_cstr)
    }

    /// Searches `/proc/self/mountinfo` for an entry with a target field matching the given `target`.
    pub fn find_entry_matching_target<T>(
        &mut self,
        target: T,
    ) -> Result<&MountInfoEntry, MountError>
    where
        T: AsRef<Path>,
    {
        let target = target.as_ref();
        let target_cstr = ffi_utils::as_ref_path_to_c_string(target)?;
        log::debug!(
            "Mount::find_entry_matching_target finding mounted table entry matching target: {:?}",
            target
        );

        Self::find_mounted_entry(self, target_cstr)
    }

    /// Searches `/proc/self/mountinfo` for an entry with a tag field matching the given `tag`.
    pub fn find_entry_matching_tag(&mut self, tag: &Tag) -> Result<&MountInfoEntry, MountError> {
        let tag_cstr = ffi_utils::as_ref_path_to_c_string(tag.to_string())?;
        log::debug!(
            "Mount::find_entry_matching_tag finding mounted table entry matching tag: {:?}",
            tag
        );

        Self::find_mounted_entry(self, tag_cstr)
    }

    // /// Parses a file into a [`MountTable`]. This `Mount` will use its own cache, and parser error callback function during the conversion.
    // pub fn parse_mount_table<T>(&self, file: T) -> Result<MountTable, MountError>
    // where
    //     T: AsRef<Path>,
    // {
    //     let file = file.as_ref();
    //     let file_cstr = ffi_utils::as_ref_path_to_c_string(file)?;
    //     log::debug!(
    //         "Mount::parse_mount_table parsing mount table from {:?}",
    //         file
    //     );

    //     let mut table = MaybeUninit::<*mut libmount::libmnt_table>::zeroed();

    //     let result = unsafe {
    //         libmount::mnt_context_get_table(self.inner, file_cstr.as_ptr(), table.as_mut_ptr())
    //     };

    //     match result {
    //         0 => {
    //             log::debug!(
    //                 "Mount::parse_mount_table parsed mount table from {:?}",
    //                 file
    //             );
    //             let ptr = unsafe { table.assume_init() };
    //             let table = MountTable::from(ptr);

    //             Ok(table)
    //         }
    //         code => {
    //             let err_msg = format!("failed to parse mount table from {:?}", file);
    //             log::debug!("Mount::parse_mount_table {}. libmount::mnt_context_get_table returned error code: {:?}", err_msg, code);

    //             Err(MountError::Parse(err_msg))
    //         }
    //     }
    // }

    /// Sets `mount`'s syscall exit status if the function was called outside of `libmount`.
    ///
    /// The `exit_status` should be `0` on success, and a negative number on error (e.g. `-errno`).
    pub fn set_syscall_exit_status(&mut self, exit_status: i32) -> Result<(), MountError> {
        log::debug!(
            "Mount::set_syscall_exit_status setting mount syscall exit status to {:?}",
            exit_status
        );

        let result = unsafe { libmount::mnt_context_set_syscall_status(self.inner, exit_status) };

        match result {
            0 => {
                log::debug!(
                    "Mount::set_syscall_exit_status set mount syscall exit status to {:?}",
                    exit_status
                );

                Ok(())
            }
            code => {
                let err_msg = format!(
                    "ailed to set mount syscall exit status to {:?}",
                    exit_status
                );
                log::debug!("Mount::set_syscall_exit_status {}. libmount::mnt_context_set_syscall_status returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    /// Resets `mount` exit status so that `mount` methods can be called again.
    pub fn reset_syscall_exit_status(&mut self) -> Result<(), MountError> {
        log::debug!("Mount::reset_syscall_exit_status resetting syscall exit status");

        let result = unsafe { libmount::mnt_context_reset_status(self.inner) };

        match result {
            0 => {
                log::debug!("Mount::reset_syscall_exit_status reset syscall exit status");

                Ok(())
            }
            code => {
                let err_msg = "failed to reset syscall exit status".to_owned();
                log::debug!("Mount::reset_syscall_exit_status {}. libmount::mnt_context_reset_status returned error code: {:?}", err_msg, code);

                Err(MountError::Config(err_msg))
            }
        }
    }

    /// Switches to the provided `namespace`, and returns the namespace used previously.
    pub fn switch_to_namespace(&mut self, namespace: MountNamespace) -> Option<MountNamespace<'_>> {
        log::debug!("Mount::switch_to_namespace switching namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();
        unsafe {
            ptr.write(libmount::mnt_context_switch_ns(self.inner, namespace.ptr));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no prior namespace";
                log::debug!("Mount::switch_to_namespace {}. libmount::mnt_context_switch_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::switch_to_namespace switched namespace");
                let namespace = MountNamespace::from_raw_parts(ptr, self);

                Some(namespace)
            }
        }
    }

    /// Switches to the namespace at creation, and returns the replacement namespace used up to this point.
    pub fn switch_to_original_namespace(&mut self) -> Option<MountNamespace<'_>> {
        log::debug!("Mount::switch_to_original_namespace switching to original namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_switch_origin_ns(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no prior namespace";
                log::debug!("Mount::switch_to_original_namespace {}. libmount::mnt_context_switch_origin_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::switch_to_original_namespace switched to original namespace");
                let namespace = MountNamespace::from_raw_parts(ptr, self);

                Some(namespace)
            }
        }
    }

    /// Switches to the target's namespace, and returns the namespace used previously.
    pub fn switch_to_target_namespace(&mut self) -> Option<MountNamespace<'_>> {
        log::debug!("Mount::switch_to_target_namespace switching to target namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_switch_target_ns(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no prior namespace";
                log::debug!("Mount::switch_to_target_namespace {}. libmount::mnt_context_switch_target_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::switch_to_target_namespace switched to target namespace");
                let namespace = MountNamespace::from_raw_parts(ptr, self);

                Some(namespace)
            }
        }
    }

    /// Waits on parallel mount child processes.
    pub fn wait_on_children(&mut self) -> ProcessExitStatus {
        log::debug!("Mount::wait_on_children waiting on child processes");

        let mut children = 0i32;
        let mut errors = 0i32;

        unsafe {
            libmount::mnt_context_wait_for_children(
                self.inner,
                &mut children as *mut _,
                &mut errors as *mut _,
            );
        }

        ProcessExitStatus::new(children as usize, errors as usize)
    }
    //---- END mutators

    //---- BEGIN getters
    /// Returns the identifier of the device to mount, or `None` if it was not provided.
    pub fn source(&self) -> Option<String> {
        log::debug!("Mount::source getting identifier of device to mount");

        let mut identifier = MaybeUninit::<*const libc::c_char>::zeroed();

        unsafe {
            identifier.write(libmount::mnt_context_get_source(self.inner));
        }

        match unsafe { identifier.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get identifier of device to mount";
                log::debug!(
                    "Mount::source {}. libmount::mnt_context_get_source returned a NULL pointer",
                    err_msg
                );

                None
            }
            ptr => {
                log::debug!("Mount::source got identifier of device to mount");
                let source = ffi_utils::c_char_array_to_string(ptr);

                Some(source)
            }
        }
    }

    /// Returns the configured device mount point, or `None` if it was not provided.
    pub fn target(&self) -> Option<PathBuf> {
        log::debug!("Mount::target getting mount point");

        let mut mount_point = MaybeUninit::<*const libc::c_char>::zeroed();

        unsafe {
            mount_point.write(libmount::mnt_context_get_target(self.inner));
        }

        match unsafe { mount_point.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get mount point";
                log::debug!(
                    "Mount::target {}. libmount::mnt_context_get_target returned a NULL pointer",
                    err_msg
                );

                None
            }
            ptr => {
                log::debug!("Mount::target got mount point");
                let target = ffi_utils::const_c_char_array_to_path_buf(ptr);

                Some(target)
            }
        }
    }

    /// Returns the mount point's [`MountNamespace`], or `None` if it is
    /// not set.
    pub fn target_namespace(&self) -> Option<MountNamespace<'_>> {
        log::debug!("Mount::target_namespace getting mount point's namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_target_ns(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no mount point namespace";
                log::debug!("Mount::target_namespace {}. libmount::mnt_context_get_target_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::target_namespace got mount point's namespace");
                let ns = MountNamespace::from_raw_parts(ptr, self);

                Some(ns)
            }
        }
    }

    /// Returns the prefix of the configured device's mount point.
    pub fn target_prefix(&self) -> Option<PathBuf> {
        log::debug!("Mount::target_prefix getting mount point prefix");

        let mut mount_point = MaybeUninit::<*const libc::c_char>::zeroed();

        unsafe {
            mount_point.write(libmount::mnt_context_get_target_prefix(self.inner));
        }

        match unsafe { mount_point.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get mount point prefix ";
                log::debug!("Mount::target_prefix {}. libmount::mnt_context_get_target_prefix returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::target_prefix got mount point prefix ");
                let target_prefix = ffi_utils::const_c_char_array_to_path_buf(ptr);

                Some(target_prefix)
            }
        }
    }

    /// Returns a reference to the internal table entry describing this `Mount`, or `None` if it is
    /// not set.
    pub fn internal_table_entry(&self) -> Option<&FsTabEntry> {
        log::debug!("Mount::internal_table_entry getting reference to internal mount table entry");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_fs>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_fs(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get reference to internal mount table entry";
                log::debug!(
                    "Mount::internal_table_entry {}. libmount::mnt_context_get_fs returned a NULL pointer",
                    err_msg
                );

                None
            }
            ptr => {
                log::debug!(
                    "Mount::internal_table_entry got reference to internal mount table entry"
                );
                let entry = owning_ref_from_ptr!(self, FsTabEntry, ptr);

                Some(entry)
            }
        }
    }

    /// Returns the private user data associated with this `Mount`'s internal mount table entry.
    pub fn internal_table_entry_user_data(&self) -> Option<NonNull<libc::c_void>> {
        log::debug!("Mount::internal_table_entry_user_data getting private user data associated with internal table entry");

        let mut ptr = MaybeUninit::<*mut libc::c_void>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_fs_userdata(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg =
                    "failed to get private user data associated with internal table entry";
                log::debug!("Mount::internal_table_entry_user_data {}. libmount::mnt_context_get_fs_userdata returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::internal_table_entry_user_data got private user data associated with internal table entry");

                NonNull::new(ptr)
            }
        }
    }

    /// Returns a reference to a [`FileLock`] on the userspace mount table. In most cases,
    /// applications using `libmount`  do not need to worry about managing the lock on `utab`.
    /// However, in rare instances, they have to be able unlock `utab` when interrupted by a Linux
    /// signal or ignore them when the lock is active.
    ///
    /// **Note:** a locked [`FileLock`] ignores by default all signals, except `SIGALARM` and `SIGTRAP` for
    /// `utab` updates.
    pub fn utab_file_lock(&mut self) -> Option<&mut FileLock> {
        log::debug!("Mount::utab_file_lock getting `utab` file lock");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_lock>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_lock(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no `utab` file lock";
                log::debug!("Mount::utab_file_lock {}. libmount::mnt_context_get_lock returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::utab_file_lock got `utab` file lock");
                let lock = owning_mut_from_ptr!(self, FileLock, ptr);

                Some(lock)
            }
        }
    }

    /// Returns the mount options set by [`MountBuilder::mount_options`],
    /// [`MountBuilder::mount_flags`], and [`Mount::append_mount_options`].
    ///
    /// **Note:** before `v2.39` this function ignored options specified by
    /// [`MountBuilder::mount_flags`] before calling [`Mount::prepare_mount`]. Now it always
    /// returns all mount options.
    pub fn mount_options(&self) -> Option<String> {
        log::debug!("Mount::mount_options getting mount options");

        let mut ptr = MaybeUninit::<*const libc::c_char>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_options(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get mount options";
                log::debug!("Mount::mount_options {}. libmount::mnt_context_get_options returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::mount_options got mount options");
                let options = ffi_utils::c_char_array_to_string(ptr);

                Some(options)
            }
        }
    }

    /// Returns the mode of `fstab` mount options.
    pub fn mount_options_mode(&self) -> Option<MountOptionsMode> {
        log::debug!("Mount::mount_options_mode getting mount options mode");

        let result = unsafe { libmount::mnt_context_get_optsmode(self.inner) };

        match result {
            0 => {
                let err_msg = "no mount options mode set";
                log::debug!("Mount::mount_options_mode {}. libmount::mnt_context_get_optsmode returned error code: 0", err_msg);

                None
            }
            mode => {
                log::debug!("Mount::mount_options_mode got mount options mode");

                MountOptionsMode::try_from(mode).ok()
            }
        }
    }

    /// Returns the set  of mount flags set during configuration, or `None` if they were
    /// not provided.
    pub fn mount_flags(&self) -> Option<HashSet<MountFlag>> {
        log::debug!("Mount::mount_flags getting mount flags");

        let mut bits = MaybeUninit::<libc::c_ulong>::zeroed();

        let result = unsafe { libmount::mnt_context_get_mflags(self.inner, bits.as_mut_ptr()) };

        match result {
            0 => {
                log::debug!("Mount::mount_flags got mount flags");
                let bits = unsafe { bits.assume_init() };
                let flags: HashSet<_> = all::<MountFlag>()
                    .filter(|&flag| (flag as u64) & bits != 0)
                    .collect();

                Some(flags)
            }
            code => {
                let err_msg = "failed to get mount flags";
                log::debug!("Mount::mount_flags {}. libmount::mnt_context_get_mflags returned error code: {:?}", err_msg, code);

                None
            }
        }
    }

    /// Returns the exit status of a mount helper (mount.*filesytem*) called by the user. The
    /// resulting value is pertinent only when the method [`Mount::has_run_mount_helper`] returns
    /// `true`.
    pub fn mount_helper_exit_status(&self) -> i32 {
        let status = unsafe { libmount::mnt_context_get_helper_status(self.inner) };
        log::debug!("Mount::mount_helper_exit_status value: {:?}", status);

        status
    }

    /// Returns the number of the last error,
    /// [errno](https://www.man7.org/linux/man-pages/man3/errno.3.html), if invoking the
    /// [`mount` syscall](https://www.man7.org/linux/man-pages/man2/mount.2.html) syscall resulted in a
    /// failure.
    pub fn mount_syscall_errno(&self) -> Option<i32> {
        log::debug!("Mount::mount_syscall_errno getting mount(2) syscall error number");

        let result = unsafe { libmount::mnt_context_get_syscall_errno(self.inner) };

        match result {
            0 => {
                let err_msg = "mount(2) syscall was never invoked, or ran successfully";
                log::debug!("Mount::mount_syscall_errno {}. libmount::mnt_context_get_syscall_errno returned error code: 0", err_msg);

                None
            }
            errno => {
                log::debug!("Mount::mount_syscall_errno got mount(2) syscall error number");

                Some(errno)
            }
        }
    }

    /// Returns the set of userspace mount flags set during configuration, or `None` if they were
    /// not provided.
    pub fn userspace_mount_flags(&self) -> Option<HashSet<UserspaceMountFlag>> {
        log::debug!("Mount::userspace_mount_flags getting user space mount flags");

        let mut bits = MaybeUninit::<libc::c_ulong>::zeroed();

        let result =
            unsafe { libmount::mnt_context_get_user_mflags(self.inner, bits.as_mut_ptr()) };

        match result {
            0 => {
                log::debug!("Mount::userspace_mount_flags got user space mount flags");
                let bits = unsafe { bits.assume_init() };
                let flags: HashSet<_> = all::<UserspaceMountFlag>()
                    .filter(|&flag| (flag as u64) & bits != 0)
                    .collect();

                Some(flags)
            }
            code => {
                let err_msg = "failed to get user space mount flags";
                log::debug!("Mount::userspace_mount_flags {}. libmount::mnt_context_get_user_mflags returned error code: {:?}", err_msg, code);

                None
            }
        }
    }

    /// Returns a reference the associated [`Cache`], or `None` if it was not set.
    pub fn cache(&self) -> Option<&Cache> {
        log::debug!("Mount::cache getting associated cache");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_cache>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_cache(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get associated cache";
                log::debug!(
                    "Mount::cache {}. libmount::mnt_context_get_cache returned a NULL pointer",
                    err_msg
                );

                None
            }
            ptr => {
                log::debug!("Mount::cache got associated cache");
                let cache = owning_ref_from_ptr!(self, Cache, ptr);

                Some(cache)
            }
        }
    }

    /// Returns the file system's description table, or `None` if it can't
    /// find one.
    pub fn fstab(&self) -> Option<FsTab> {
        log::debug!("Mount::fstab getting file system description file `fstab`");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_table>::zeroed();

        let result = unsafe { libmount::mnt_context_get_fstab(self.inner, ptr.as_mut_ptr()) };

        match result {
            0 => {
                log::debug!("Mount::fstab got file system description file `fstab`");
                let ptr = unsafe { ptr.assume_init() };
                let table = FsTab::from_ptr(ptr);

                Some(table)
            }
            code => {
                let err_msg = "failed to get file system description file `fstab`";
                log::debug!(
                    "Mount::fstab {}. libmount::mnt_context_get_fstab returned error code: {:?}",
                    err_msg,
                    code
                );

                None
            }
        }
    }

    /// Returns the user data associated to this `Mount`'s `fstab` table, or `None` if it does
    /// not exist.
    pub fn fstab_user_data(&self) -> Option<NonNull<libc::c_void>> {
        log::debug!("Mount::fstab_user_data getting `fstab` associated user data");

        let mut ptr = MaybeUninit::<*mut libc::c_void>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_fstab_userdata(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no associated user data";
                log::debug!("Mount::fstab_user_data {}. libmount::mnt_context_get_fstab_userdata returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::fstab_user_data got `fstab` associated user data");

                NonNull::new(ptr)
            }
        }
    }

    /// Returns this `Mount`'s file system type, or `None` if it was not set.
    pub fn file_system_type(&self) -> Option<FileSystem> {
        log::debug!("Mount::file_system_type getting file system type");

        let mut ptr = MaybeUninit::<*const libc::c_char>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_fstype(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get file system type";
                log::debug!("Mount::file_system_type {}. libmount::mnt_context_get_fstype returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::file_system_type got file system type");
                let fs_type_cstr = ffi_utils::c_char_array_to_string(ptr);

                match FileSystem::from_str(fs_type_cstr.as_ref()) {
                    Ok(fs_type) => Some(fs_type),
                    Err(e) => {
                        log::debug!("Mount::file_system_type {:?}", e);

                        None
                    }
                }
            }
        }
    }

    /// Returns an instance of the `/proc/self/mountinfo`, or `None` if it can't find
    /// one.
    pub fn mountinfo(&self) -> Option<MountInfo> {
        log::debug!("Mount::mountinfo getting `mountinfo` table");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_table>::zeroed();

        let result = unsafe { libmount::mnt_context_get_mtab(self.inner, ptr.as_mut_ptr()) };

        match result {
            0 => {
                log::debug!("Mount::mountinfo got `mountinfo` table");
                let ptr = unsafe { ptr.assume_init() };
                let table = MountInfo::from_ptr(ptr);

                Some(table)
            }
            code => {
                let err_msg = "failed to get `mountinfo` table";
                log::debug!(
                    "Mount::mountinfo {}. libmount::mnt_context_get_mtab returned error code: {:?}",
                    err_msg,
                    code
                );

                None
            }
        }
    }

    /// Returns the user data associated to this `Mount`'s `mountinfo` table, or `None` if it does
    /// not exist.
    pub fn mountinfo_user_data(&self) -> Option<NonNull<libc::c_void>> {
        log::debug!("Mount::mountinfo_user_data getting `mountinfo` associated user data");

        let mut ptr = MaybeUninit::<*mut libc::c_void>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_mtab_userdata(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no associated user data";
                log::debug!("Mount::mountinfo_user_data {}. libmount::mnt_context_get_mtab_userdata returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::mountinfo_user_data got `mountinfo` associated user data");

                NonNull::new(ptr)
            }
        }
    }

    /// Returns this `Mount`'s original [`MountNamespace`], or `None` if it is
    /// not set.
    pub fn original_namespace(&self) -> Option<MountNamespace<'_>> {
        log::debug!("Mount::original_namespace getting mount namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_origin_ns(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no original namespace";
                log::debug!("Mount::original_namespace {}. libmount::mnt_context_get_origin_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Mount::original_namespace got mount namespace");
                let ns = MountNamespace::from_raw_parts(ptr, self);

                Some(ns)
            }
        }
    }
    //---- END getters

    //---- BEGIN iterators

    /// Tries to sequentially mount entries in `/etc/fstab`.
    ///
    /// To filter devices to mount by file system type and/or mount options, use the
    /// methods [`MountBuilder::match_file_systems`] and/or [`MountBuilder::match_mount_options`]
    /// when instantiating a new `Mount` object.
    pub fn seq_mount(&mut self) -> MountIter<'_> {
        MountIter::new(self).unwrap()
    }

    /// Tries to sequentially remount entries in `/proc/self/mountinfo`.
    ///
    /// To filter devices to remount by file system type and/or mount options, use the
    /// methods [`MountBuilder::match_file_systems`] and/or [`MountBuilder::match_mount_options`]
    /// when instantiating a new `Mount` object.
    pub fn seq_remount(&mut self) -> ReMountIter<'_> {
        ReMountIter::new(self).unwrap()
    }

    //---- END iterators

    //---- BEGIN predicates

    /// Returns `true` if this `Mount`'s internal [`FsTab`] has a matching `entry`. This
    /// function compares the `source`, `target`, and `root` fields of the function parameter
    /// against those of each entry in the [`FsTab`].
    ///
    /// **Note:** the `source`, and `target` fields are canonicalized if a [`Cache`] is set for
    /// this `Mount`.
    ///
    /// **Note:** swap partitions are ignored.
    ///
    /// **Warning:** on `autofs` mount points, canonicalizing the `target` field may trigger
    /// an automount.
    pub fn is_entry_mounted(&self, entry: &FsTabEntry) -> bool {
        log::debug!("Mount::is_entry_mounted checking if mount table entry was mounted");

        let mut status = MaybeUninit::<libc::c_int>::zeroed();

        let result = unsafe {
            libmount::mnt_context_is_fs_mounted(self.inner, entry.inner, status.as_mut_ptr())
        };

        match result {
            0 => {
                log::debug!("Mount::is_entry_mounted checked if mount table entry was mounted");
                let status = unsafe { status.assume_init() };

                status == 1
            }
            code => {
                let err_msg = "failed to check if mount table entry was mounted";
                log::debug!("Mount::is_entry_mounted {}. libmount::mnt_context_is_fs_mounted returned error code: {:?}", err_msg, code);

                false
            }
        }
    }

    /// Returns `true` when this `Mount` is configured to mount devices in parallel and is the
    /// parent process.
    pub fn is_parent_process(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_parent(self.inner) == 1 };
        log::debug!("Mount::is_parent_process value: {:?}", state);

        state
    }

    /// Returns `true` when this `Mount` is configured to mount devices in parallel and is a
    /// child process.
    pub fn is_child_process(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_child(self.inner) == 1 };
        log::debug!("Mount::is_child_process value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured to perform a dry run.
    pub fn is_dry_run(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_fake(self.inner) == 1 };
        log::debug!("Mount::is_dry_run value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured to be verbose.
    pub fn is_verbose(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_verbose(self.inner) == 1 };
        log::debug!("Mount::is_verbose value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is set to perform unprivileged mounts (mon-root mounts).
    pub fn is_user_mount(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_restricted(self.inner) == 1 };
        log::debug!("Mount::is_user_mount value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured NOT to canonicalize paths.
    pub fn disabled_path_canonicalization(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_nocanonicalize(self.inner) == 1 };
        log::debug!("Mount::disabled_path_canonicalization value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured NOT to lookup a device or mount point in
    /// `/etc/fstab` if one is not provided when setting this `Mount`'s source or target.
    pub fn disabled_mount_point_lookup(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_swapmatch(self.inner) == 1 };
        log::debug!("Mount::disabled_mount_point_lookup value: {:?}", state);

        state
    }

    /// Returns `true` if the [`mount` syscall](https://www.man7.org/linux/man-pages/man2/mount.2.html)
    /// was invoked.
    pub fn has_called_mount_syscall(&self) -> bool {
        let state = unsafe { libmount::mnt_context_syscall_called(self.inner) == 1 };
        log::debug!("Mount::has_called_mount_syscall value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured NOT to use mount helpers.
    pub fn has_disabled_helpers(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_nohelpers(self.inner) == 1 };
        log::debug!("Mount::has_disabled_helpers value: {:?}", state);

        state
    }

    /// Returns `true` if a mount helper was run.
    pub fn has_run_mount_helper(&self) -> bool {
        let state = unsafe { libmount::mnt_context_helper_executed(self.inner) == 1 };
        log::debug!("Mount::has_run_mount_helper value: {:?}", state);

        state
    }

    /// Returns `true` if mount helpers, or the
    /// [`mount` syscall](https://www.man7.org/linux/man-pages/man2/mount.2.html) were run successfully.
    pub fn is_mount_successful(&self) -> bool {
        let state = unsafe { libmount::mnt_context_get_status(self.inner) == 1 };
        log::debug!("Mount::is_mount_successful value: {:?}", state);

        state
    }

    /// Returns `true` if a write protected device is mounted in read-only mode.
    pub fn is_mounted_read_only(&self) -> bool {
        let state = unsafe { libmount::mnt_context_forced_rdonly(self.inner) == 1 };
        log::debug!("Mount::is_mounted_read_only value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured to disable userpace mount table updates.
    pub fn does_not_update_utab(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_nohelpers(self.inner) == 1 };
        log::debug!("Mount::does_not_update_utab value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured to mount devices in parallel.
    pub fn does_parallel_mount(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_fork(self.inner) == 1 };
        log::debug!("Mount::does_parallel_mount value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured to force mount devices in read-write mode.
    pub fn forces_mount_read_write(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_rwonly_mount(self.inner) == 1 };
        log::debug!("Mount::forces_mount_read_write value: {:?}", state);

        state
    }

    /// Returns `true` if this `Mount` is configured to ignore mount options unsupported by a
    /// device's file system.
    pub fn ignores_unsupported_mount_options(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_sloppy(self.inner) == 1 };
        log::debug!(
            "Mount::ignores_unsupported_mount_options value: {:?}",
            state
        );

        state
    }

    #[cfg(mount = "v2_39")]
    /// Returns `true` if this `Mount` is configured to check that a device is not already mounted
    /// before mounting it.
    pub fn mounts_only_once(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_onlyonce(self.inner) == 1 };
        log::debug!("Mount::mounts_only_once value: {:?}", state);

        state
    }

    //---- END predicates
}

impl AsRef<Mount> for Mount {
    fn as_ref(&self) -> &Mount {
        self
    }
}

impl Drop for Mount {
    fn drop(&mut self) {
        log::debug!("Mount::drop deallocating `Mount` instance");

        unsafe {
            libmount::mnt_free_context(self.inner);
        }

        // Free objects allocated on the heap for returned references.
        while let Some(gc_item) = self.gc.pop() {
            gc_item.destroy();
        }
    }
}

#[cfg(test)]
#[allow(unused_imports)]
mod tests {
    use pretty_assertions::{assert_eq, assert_ne};
    use tempfile::Builder;
    use tempfile::NamedTempFile;

    use std::fs::File;
    use std::io::Write;

    use super::*;
    use crate::core::device::BlockDevice;
    use crate::mount::ExitCode;

    //---- Helper functions

    static BASE_DIR_TEST_IMG_FILES: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/third-party/vendor/util-linux/blkid/images"
    );

    fn decode_into<P, W>(xz_file_path: P, writer: &mut W) -> std::io::Result<u64>
    where
        P: AsRef<Path>,
        W: Write + ?Sized,
    {
        let xz_file_path = xz_file_path.as_ref();

        // Copy decompressed image to temporary file
        let compressed_image_file = std::fs::File::open(xz_file_path)?;
        let mut decompressed = xz2::read::XzDecoder::new(compressed_image_file);

        std::io::copy(&mut decompressed, writer)
    }

    /// Creates a named temporary image file with one of the supported file systems from the
    /// compressed samples.
    fn disk_image(fs_type: &str) -> NamedTempFile {
        let img_path = format!("{BASE_DIR_TEST_IMG_FILES}/filesystems/{fs_type}.img.xz");
        let mut named_file = NamedTempFile::new().expect("failed to get new NamedTempFile");

        decode_into(img_path, named_file.as_file_mut()).expect("failed to create named disk image");
        named_file
    }

    //-------------------------------------------------------------------------

    // #[test]
    // #[should_panic(
    //     expected = "you MUST call at least one of the following functions: `MountBuilder::source`, `MountBuilder::target`"
    // )]
    // fn mount_must_have_a_source_or_target() {
    //     let _ = Mount::builder().build().unwrap();
    // }

    #[test]
    fn mount_can_mount_an_image_file() -> crate::Result<()> {
        if inside_vm::inside_vm() {
            let image_file = disk_image("ext3");
            let source = BlockDevice::from(image_file.path());
            let tmp_dir = Builder::new().prefix("rsmount-test-").tempdir().unwrap();
            let mut mount = Mount::builder()
                .source(source)
                .target(tmp_dir.path())
                .build()?;

            let status = mount.mount_device()?;

            let actual = mount.is_mount_successful();
            let expected = true;
            assert_eq!(actual, expected);

            let actual = status.exit_code();
            let expected = ExitCode::Success;
            assert_eq!(actual, &expected);
        }

        Ok(())
    }
}