fdf 0.9.2

A fast, multi-threaded filesystem search tool with regex/glob support and extremely pretty colours!
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
/*!
 A high-performance, parallel directory traversal and file search library.

 This library provides efficient file system traversal with features including:
 - Parallel directory processing using A custom work stealing algorithm (crossbeam)
 - Low-level system calls for optimal performance on supported platforms
 - Flexible filtering by name, size, type, and custom criteria
 - Symbolic link handling with cycle detection
 - Cross-platform support with platform-specific optimisations
 - Provides easy access to `CStr` for FFI use.

 # Examples
 Simple file search example
 ```no_run
 use fdf::{walk::Finder, SearchConfig};
 use std::error::Error;
 use std::sync::Arc;

fn main() -> Result<(), Box<dyn Error>> {
    let finder = Finder::init("/some/path")
        .pattern("*.txt")
        .build()
        .expect("Failed to build finder");

    let entries = finder
        .traverse()
        .expect("Failed to start traversal");

    let mut file_count = 0;

    for entry in entries {
        file_count += 1;
        println!("Found: {}", String::from_utf8_lossy(&entry));
    }

    println!("Discovered {file_count} files");

    Ok(())
}

 ```

 Advanced file search example
 ```no_run
use fdf::{walk::Finder, filters::{SizeFilter, FileTypeFilter}};
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let finder = Finder::init("/some/path")
        .pattern("*.txt")
        .keep_hidden(false)
        .case_insensitive(true)
        .max_depth(Some(5))
        .respect_gitignore(false)
        .follow_symlinks(false)
        .filter_by_size(Some(SizeFilter::Min(1024)))
        .type_filter(Some(FileTypeFilter::File))
        .collect_errors(true) // Gather the errors from iteration, this has some performance cost.
        .build()
        .map_err(|e| format!("Failed to build finder: {e}"))?;

    let entries = finder
        .traverse()
        .map_err(|e| format!("Failed to start traversal: {e}"))?;

    let mut file_count = 0;

    for entry in entries {
        file_count += 1;
        println!("{}",String::from_utf8_lossy(&entry));
    }

    println!("Search completed! Found {file_count} files");

    Ok(())
}
```

*/

use crate::c_char;
use crate::fs::ReadDir;
use crate::fs::{FileDes, FileType, types::Result};
use crate::{DirEntryError, util::BytePath as _};
use chrono::{DateTime, Utc};
use core::cell::Cell;
use core::ffi::CStr;
use core::fmt;

use libc::{
    AT_SYMLINK_FOLLOW, AT_SYMLINK_NOFOLLOW, F_OK, R_OK, W_OK, X_OK, access, fstatat, lstat,
    realpath, stat,
};
use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _, path::Path};

//TODO, test #[align(64)] to check for presence of false sharing/perf improvements
// If so, add extra relevant metadata to the struct...

/**
  A struct representing a directory entry with minimal memory overhead.

  This struct is designed for high-performance file system traversal and analysis.
  It holds metadata and a path to a file or directory, optimised for size
  and efficient access to its components.

  The struct's memory footprint is
  - **Path**: 16 bytes, `Box<CStr>`, retaining compatibility for use in libc but converting to `&[u8]` trivially(as deref)
  - **File type**:  1-byte enum representing the entry's type (file, directory, etc.).
  - **Inode**:  8-byte integer for the file's unique inode number.
  - **Depth**:  4-byte integer indicating the entry's depth from the root.
  - **File name index**:  8-byte integer pointing to the start of the file name within the path buffer.
  - **is traversible cache**:  1 byte `Cell<Option<bool>>` an Implementation detail that avoids recalling stat on symlinks

  # Examples

    ```
    use fdf::fs::DirEntry;
    use std::path::Path;
    use std::fs::File;
    use std::io::Write;
    use std::sync::Arc;



    // Create a temporary directory for the test
    let temp_dir = std::env::temp_dir();


    let file_path = temp_dir.join("test_file.txt");

    // Create a file inside the temporary directory

    let mut file = File::create(&file_path).expect("Failed to create file");
    writeln!(file, "Hello, world!").expect("Failed to write to file");


    // Create a DirEntry from the temporary file path
    let entry = DirEntry::new(&file_path).unwrap();
    assert!(entry.is_regular_file());
    assert_eq!(entry.file_name(), b"test_file.txt");
    ```
*/
#[derive(Clone)] //could probably implement a more specialised clone.
pub struct DirEntry {
    /// Path to the entry, stored as a Boxed `CStr`
    /// This allows easy C ffi by just calling `.as_ptr()`
    //(to avoid storing the capacity, since the path is immutable once set)
    pub(crate) path: Box<CStr>, //16 bytes
    //TODO rewrite CStr manually  due to this FIXME
    /* https://doc.rust-lang.org/src/core/ffi/c_str.rs.html#103
    // FIXME: this should not be represented with a DST slice but rather with
    //        just a raw `c_char` along with some form of marker to make
    //        this an unsized type. Essentially `sizeof(&CStr)` should be the
    //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
     */
    /// File type (file, directory, symlink, etc.).
    pub(crate) file_type: FileType, //1 byte

    /// Inode number of the file.
    pub(crate) inode: u64, //8 bytes
    /// Depth of the directory entry relative to the root.
    pub(crate) depth: u32, //4bytes

    /// Offset in the path buffer where the file name starts.
    ///
    /// This helps quickly extract the file name from the full path.
    pub(crate) file_name_index: usize, //8 bytes
    ///
    /// `None` means not computed yet, `Some(bool)` means cached result.
    pub(crate) is_traversible_cache: Cell<Option<bool>>, //1byte
} //38 bytes, rounded to 40

impl core::ops::Deref for DirEntry {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsRef<[u8]> for DirEntry {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<'drnt> From<&'drnt DirEntry> for &'drnt CStr {
    #[inline]
    fn from(entry: &'drnt DirEntry) -> &'drnt CStr {
        &entry.path
    }
}

impl fmt::Display for DirEntry {
    // TODO: I might need to change this to show other metadata.
    #[allow(clippy::missing_inline_in_public_items)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string_lossy())
    }
}

impl From<DirEntry> for std::path::PathBuf {
    #[inline]
    fn from(entry: DirEntry) -> Self {
        entry.as_os_str().into()
    }
}
impl TryFrom<&[u8]> for DirEntry {
    type Error = DirEntryError;

    #[inline]
    fn try_from(path: &[u8]) -> Result<Self> {
        Self::new(OsStr::from_bytes(path))
    }
}

impl TryFrom<&OsStr> for DirEntry {
    type Error = DirEntryError;

    #[inline]
    fn try_from(path: &OsStr) -> Result<Self> {
        Self::new(path)
    }
}

impl AsRef<Path> for DirEntry {
    #[inline]
    fn as_ref(&self) -> &Path {
        self.as_path()
    }
}

impl fmt::Debug for DirEntry {
    #[allow(clippy::missing_inline_in_public_items)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Dirent")
            .field("path", &self.to_string_lossy())
            .field("file_name", &String::from_utf8_lossy(self.file_name()))
            .field("depth", &self.depth)
            .field("file_type", &self.file_type)
            .field("file_name_index", &self.file_name_index)
            .field("inode", &self.inode)
            .field("traversible_cache", &self.is_traversible_cache)
            .finish()
    }
}

impl DirEntry {
    /**
    Checks if the entry is an executable file.

     This is a **costly** operation as it performs an `access` system call.

    # Examples

    ```
      use fdf::fs::DirEntry;
      use std::fs::{self, File};
      use std::os::unix::fs::PermissionsExt;
      use std::sync::Arc;

      let temp_dir = std::env::temp_dir();
      let exe_path = temp_dir.join("my_executable");
      File::create(&exe_path).unwrap().set_permissions(fs::Permissions::from_mode(0o755)).unwrap();

      let entry = DirEntry::new(&exe_path).unwrap();
      assert!(entry.is_executable());

      let non_exe_path = temp_dir.join("my_file");
      File::create(&non_exe_path).unwrap();
      let non_exe_entry = DirEntry::new(&non_exe_path).unwrap();
      assert!(!non_exe_entry.is_executable());
      fs::remove_file(exe_path).unwrap();
      fs::remove_file(non_exe_path).unwrap();
      ```
    */
    #[inline]
    pub fn is_executable(&self) -> bool {
        // X_OK is the execute permission, requires access call
        // SAFETY: We know the path is valid because internally it's a cstr
        self.is_regular_file() && unsafe { access(self.as_ptr(), X_OK) == 0 }
    }

    /**
     Returns a raw pointer to the underlying C string.

     This provides access to the null-terminated C string representation
     of the file path for use with FFI functions.
    */
    #[inline]
    pub const fn as_ptr(&self) -> *const c_char {
        self.path.as_ptr() //Have to explicitly override the default deref to bytes
    }

    /// Returns the underlying path as a `Path`
    #[inline]
    pub const fn as_path(&self) -> &Path {
        // SAFETY: bytes <=> OsStr <=> Path on unix
        unsafe { core::mem::transmute(self.as_bytes()) } //admittedly this and below are a const hack. Why not make it const if you can?
    }

    /// Returns the underlying path as an `OsStr`
    #[inline]
    pub const fn as_os_str(&self) -> &OsStr {
        // SAFETY: bytes <=> OsStr <=> Path on unix
        unsafe { core::mem::transmute(self.as_bytes()) }
    }

    /// Cost free check for block devices
    #[inline]
    #[must_use]
    pub const fn is_block_device(&self) -> bool {
        self.file_type.is_block_device()
    }

    #[inline]
    /**
     Opens the directory and returns a file descriptor.

     This is a low-level operation that opens the directory with the following flags:
     - `O_CLOEXEC`: Close the file descriptor on exec
     - `O_DIRECTORY`: Fail if not a directory
     - `O_NONBLOCK`: Open in non-blocking mode

    */
    pub(crate) fn open(&self) -> Result<FileDes> {
        // Opens the file and returns a file descriptor..
        const FLAGS: i32 = libc::O_CLOEXEC | libc::O_DIRECTORY | libc::O_NONBLOCK;
        // SAFETY: the pointer is null terminated
        let fd = unsafe { libc::open(self.as_ptr(), FLAGS) };

        if fd < 0 {
            return_os_error!()
        }
        Ok(FileDes(fd))
    }

    /*
    Commented out temporarily while I work on API
    /**
     Opens the directory relative to a directory file descriptor and returns a file descriptor.

     This function uses the `openat` system call to open a directory relative to an already open
     directory file descriptor. This is useful for avoiding race conditions that can occur when
     using absolute paths, as it ensures the operation is performed relative to a specific directory.

     The directory is opened with the following flags:
     - `O_CLOEXEC`: Close the file descriptor on exec
     - `O_DIRECTORY`: Fail if not a directory
     - `O_NONBLOCK`: Open in non-blocking mode

     # Examples

     ## Basic usage

     ```
     use fdf::{DirEntry, FileDes, Result};
     use std::fs;
     use std::env::temp_dir;

     # fn main() -> Result<()> {
     // Create a temporary directory for testing
     let temp_dir = temp_dir().join("fdf_openat_test");
     let _ = fs::remove_dir_all(&temp_dir);
     fs::create_dir_all(&temp_dir)?;

     // Create a subdirectory inside the temp directory
     let subdir_path = temp_dir.join("test_subdir");
     fs::create_dir(&subdir_path)?;

     // Open the temporary directory
     let temp_dir_entry = DirEntry::new(&temp_dir)?;
     let temp_fd = temp_dir_entry.open()?;

     // Use openat to open the subdirectory relative to the temp directory
     let subdir_entry = DirEntry::new(&subdir_path)?;
     let subdir_fd = subdir_entry.openat(&temp_fd)?;

     // Clean up
     let _ = fs::remove_dir_all(&temp_dir);
     # Ok(())
     # }
     ```
     # Platform-specific behavior

     - On Linux, this uses the `openat` system call directly
     - The behavior may vary on other Unix-like systems, but the interface is standardized in POSIX

     # Errors

     Returns an error if:
     - The directory doesn't exist or can't be opened
     - The path doesn't point to a directory (fails due to `O_DIRECTORY` flag)
     - Permission is denied for the directory
     - The parent file descriptor (`dir_fd`) is invalid or not open
     - The path contains null bytes
     - System resources are exhausted (too many open file descriptors)

     # See also

     - [openat(2) - Linux man page](https://man7.org/linux/man-pages/man2/openat.2.html)
     - [`DirEntry::open`] for opening directories with absolute paths
    */
    #[inline]
    pub fn openat(&self, fd: &FileDes) -> Result<FileDes> {
        // Opens the file and returns a file descriptor.
        // This is a low-level operation that may fail if the file does not exist or cannot be opened.
        const FLAGS: i32 = O_CLOEXEC | O_DIRECTORY | O_NONBLOCK;
        // SAFETY: the pointer is null terminated
        let filedes = unsafe { openat(fd.0, self.file_name_cstr().as_ptr(), FLAGS) };

        if filedes < 0 {
            return_os_error!()
        }
        Ok(FileDes(filedes))
    }*/

    // Converts to a lossy string for ease of use
    #[inline]
    #[must_use]
    pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
        String::from_utf8_lossy(self)
    }

    /**
    Returns the underlying bytes as a UTF-8 string slice if valid.
    # Errors
    Returns `Err` if the bytes are not valid UTF-8.
    */
    #[inline]
    pub const fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> {
        core::str::from_utf8(self.as_bytes())
    }

    /// Cost free check for character devices
    #[inline]
    #[must_use]
    pub const fn is_char_device(&self) -> bool {
        self.file_type.is_char_device()
    }

    /// Cost free check for pipes (FIFOs)
    #[inline]
    #[must_use]
    pub const fn is_pipe(&self) -> bool {
        self.file_type.is_pipe()
    }

    /// Cost free check for sockets
    #[inline]
    #[must_use]
    pub const fn is_socket(&self) -> bool {
        self.file_type.is_socket()
    }

    /// Cost free check for regular files
    #[inline]
    #[must_use]
    pub const fn is_regular_file(&self) -> bool {
        self.file_type.is_regular_file()
    }

    /// Cost free check for directories
    #[inline]
    #[must_use]
    pub const fn is_dir(&self) -> bool {
        self.file_type.is_dir()
    }

    /// Cost free check for unknown file types
    #[inline]
    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        self.file_type.is_unknown()
    }

    /// Cost free check for symlinks
    #[inline]
    #[must_use]
    pub const fn is_symlink(&self) -> bool {
        self.file_type.is_symlink()
    }

    /**
    Checks if the entry is empty.

    For files, it checks if the size is zero. For directories, it checks if there are no entries.
    This is a **costly** operation as it requires system calls (`stat` or `getdents`/`readdir`).

    # Examples

    ```
    use fdf::fs::DirEntry;
    use std::fs::{self, File};
    use std::io::Write;
    use std::sync::Arc;
    let temp_dir = std::env::temp_dir();

    // Check an empty file.
    let empty_file_path = temp_dir.join("empty.txt");
    File::create(&empty_file_path).unwrap();
    let empty_entry = DirEntry::new(&empty_file_path).unwrap();
    assert!(empty_entry.is_empty());

    // Check a non-empty file.
    let non_empty_file_path = temp_dir.join("not_empty.txt");
    File::create(&non_empty_file_path).unwrap().write_all(b"Hello").unwrap();
    let non_empty_entry = DirEntry::new(&non_empty_file_path).unwrap();
    assert!(!non_empty_entry.is_empty());

    // Check an empty directory.
    let empty_dir_path = temp_dir.join("empty_dir");
    fs::create_dir(&empty_dir_path).unwrap();
    let empty_dir_entry = DirEntry::new(&empty_dir_path).unwrap();
    assert!(empty_dir_entry.is_empty());

    fs::remove_file(empty_file_path).unwrap();
    fs::remove_file(non_empty_file_path).unwrap();
    fs::remove_dir(empty_dir_path).unwrap();
    ```
    */
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        // because calling getdents on an empty dir should only return 48 on these platforms, meaning we dont have
        // to allocate the vector in getdents, finding empty files is a good use case so even though it's niche
        // it would have appeal to people. Not too hard to implement.
        // (This code is verbose but it's an essential operation so it makes sense to optimise it)
        match self.file_type {
            FileType::RegularFile => self.file_size().is_ok_and(|size| size == 0),
            FileType::Directory => {
                #[cfg(any(
                    target_os = "linux",
                    target_os = "android",
                    target_os = "netbsd",
                    target_os = "solaris",
                    target_os = "illumos"
                ))]
                let result = self.is_empty_getdents();
                #[cfg(not(any(
                    target_os = "linux",
                    target_os = "android",
                    target_os = "netbsd",
                    target_os = "solaris",
                    target_os = "illumos"
                )))]
                let result = self.is_empty_posix(); //Avoid allocating a buffer here or any other ops.
                result
            }
            _ => false,
        }
    }

    #[inline]
    #[must_use]
    #[cfg(not(any(
        target_os = "linux",
        target_os = "android",
        target_os = "netbsd",
        target_os = "solaris",
        target_os = "illumos"
    )))]
    pub(crate) fn is_empty_posix(&self) -> bool {
        //avoid a heapalloc
        use crate::readdir64;
        use libc::closedir;

        debug_assert!(
            self.is_dir(),
            "checking the only entries to this are directories"
        );

        // SAFETY: guaranteed null terminated path
        let dir = unsafe { libc::opendir(self.as_ptr()) };

        if dir.is_null() {
            return false;
        }

        // SAFETY: dir valid to read
        let result = unsafe {
            readdir64(dir); // Skip "."
            readdir64(dir); // Skip ".."
            readdir64(dir).is_null()
        };
        // SAFETY: closing a valid directory
        unsafe { closedir(dir) };
        result
    }

    #[inline]
    #[cfg(any(
        target_os = "linux",
        target_os = "android",
        target_os = "netbsd",
        target_os = "solaris",
        target_os = "illumos"
    ))]
    /// Specialisation for empty checks on linux/android/netbsd (avoid a heap alloc)
    pub(crate) fn is_empty_getdents(&self) -> bool {
        use crate::fs::AlignedBuffer;
        use crate::util::getdents64;
        const BUF_SIZE: usize = 500; //pretty arbitrary.
        // On Linux it's 24, on solaris it's 24/32
        // so either way, 2*32=64>= 2*24 or 2*32, just a better catch all
        const MINIMUM_DIRENT_SIZE: isize = 32;
        debug_assert!(
            self.file_type == FileType::Directory || self.file_type == FileType::Symlink,
            " Only expect dirs/symlinks to pass through this private func"
        );
        let dirfd = self.open();
        if let Ok(fd) = dirfd {
            let mut syscall_buffer = AlignedBuffer::<u8, BUF_SIZE>::new();
            // SAFETY: guaranteed open, valid ptr etc.
            let dents = unsafe { getdents64(fd.0, syscall_buffer.as_mut_ptr().cast(), BUF_SIZE) };

            // SAFETY: Closed only once confirmed open
            unsafe { libc::close(fd.0) };
            // if empty, then only 2 entries expected, . and .., this means only 64 or below (or neg if errors, who cares.)
            return dents <= 2 * MINIMUM_DIRENT_SIZE;
        }
        false //return false is open fails
    }

    /**
    Returns the full path of this directory entry as a `CStr`.

    This function provides direct access to the underlying null-terminated C string
    representing the entry’s absolute or relative path (depending on how it was created).

     The returned reference is valid for the lifetime of the `DirEntry` and does not allocate.

    # Examples

     ```
     use fdf::fs::DirEntry;
     use std::fs::File;
     use std::io::Write;
     use std::os::unix::ffi::OsStrExt;
    // Create a temporary file
    let tmp = std::env::temp_dir().join("as_cstr_test.txt");
     File::create(&tmp).unwrap().write_all(b"data").unwrap();

    // Create a DirEntry from the file path
    let entry = DirEntry::new(&tmp).unwrap();

     // Retrieve full path as a CStr
    let cstr = entry.as_cstr();

    // It should match the full path string plus null terminator
    let expected = std::ffi::CString::new(tmp.as_os_str().as_bytes()).unwrap();
     assert_eq!(cstr.to_bytes_with_nul(), expected.to_bytes_with_nul());

     // The CStr can be converted back to &str (if valid UTF-8)
    let path_str = cstr.to_str().unwrap();
    assert!(path_str.ends_with("as_cstr_test.txt"));
    std::fs::remove_file(tmp).unwrap();
    ```
    */
    #[inline]
    pub const fn as_cstr(&self) -> &CStr {
        &self.path
    }

    // Test inconsistently fails below, pretty weird.
    /**
     Returns the file name component of the entry as a `CStr`.

     This slice is a view into the internal path buffer and includes the null terminator.
     It is guaranteed to be valid UTF-8 if and only if the file name is UTF-8.

    Useful within the openat calls
     # Examples

     ```no_run
     use fdf::fs::DirEntry;
     use std::fs::File;
     use std::io::Write;

     // Create a temporary file
     let tmp = std::env::temp_dir().join("file_name_cstr_test.txt");
     File::create(&tmp).unwrap().write_all(b"abc").unwrap();

     // Build DirEntry
    let entry = DirEntry::new(&tmp).unwrap();

    // Extract file name as CStr
    let cstr = entry.file_name_cstr();

    // It should match the file name plus null terminator
    assert_eq!(cstr.to_bytes_with_nul(), b"file_name_cstr_test.txt\0");

    // We can also convert it to a &str
    assert_eq!(cstr.to_str().unwrap(), "file_name_cstr_test.txt");

    std::fs::remove_file(tmp).unwrap();
    ```

    ```
    use fdf::fs::DirEntry;
    use std::fs::File;

     // File name with spaces
    let tmp = std::env::temp_dir().join("some name.txt");
    File::create(&tmp).unwrap();



    let entry = DirEntry::new(&tmp).unwrap();
    let name = entry.file_name_cstr();

    assert_eq!(name.to_str().unwrap(), "some name.txt");

    std::fs::remove_file(tmp).unwrap();




    let root_dir=DirEntry::new("/");

    assert!(root_dir.is_err() || root_dir.is_ok_and(|x| x.file_name_cstr()==c"/"));

    ```
    */
    #[inline]
    pub const fn file_name_cstr(&self) -> &CStr {
        let path = self.path.to_bytes_with_nul();
        let len = path.len() - self.file_name_index;
        /*SAFETY:
        `file_name_index` returns a valid index within `bytes` bounds
        The slice from this index includes the terminating null byte
        `bytes` contains no interior null bytes before the terminator*/
        unsafe {
            CStr::from_bytes_with_nul_unchecked(core::slice::from_raw_parts(
                path.as_ptr().add(self.file_name_index),
                len,
            ))
            // Rearranged to make const compatible(identical assembly to previous version but wasnt const)
        }
    }

    /**
     Returns a raw pointer to the file name within the internal C string.

     The pointer is valid for the lifetime of the `DirEntry` and points to
     the start of the file name (not the full path). It is null-terminated.

     # Examples

     ```no_run
     use fdf::fs::DirEntry;
     use std::ffi::CStr;
     use std::fs::File;

     let tmp = std::env::temp_dir().join("file_name_ptr_test.txt");
     File::create(&tmp).unwrap();

     let entry = DirEntry::new(&tmp).unwrap();

     // SAFETY: pointer is valid for the lifetime of `entry`.
     let name = entry.file_name_ptr();
     assert_eq!(unsafe{CStr::from_ptr(name)}, c"file_name_ptr_test.txt");

     let root=DirEntry::new("/");

     if let Ok(root_name)=root{

      assert_eq!(unsafe{CStr::from_ptr(root_name.file_name_ptr())}, c"/");
        }



     std::fs::remove_file(tmp).unwrap();
     ```
    */
    #[inline]
    pub const fn file_name_ptr(&self) -> *const c_char {
        // SAFETY: file name index is always within bounds.
        unsafe { self.as_ptr().add(self.file_name_index) }
    }

    // no_run because fails in CI ~1/10 (it's annoying at times...)
    /**
    Returns the name of the file (as bytes, no null terminator)
    ( Returns `/` or `.` when they are the entry)


    ```no_run
    use fdf::fs::DirEntry;
    use std::fs::File;

    // File name with spaces
    let tmp = std::env::temp_dir().join("some name.txt");
    File::create(&tmp).unwrap();



    let entry = DirEntry::new(&tmp).unwrap();
    let name = entry.file_name();

    assert_eq!(name, b"some name.txt");

    std::fs::remove_file(tmp).unwrap();




    let root_dir=DirEntry::new("/");

    assert!(root_dir.is_err() || root_dir.is_ok_and(|x| x.file_name()==b"/"));
    // if on certain systems, root dir requires permissions, so we have to be careful (esp android)

    let dot_dir=DirEntry::new(".");
    assert!(dot_dir.is_err() ||dot_dir.is_ok_and(|x| x.file_name()==b"."));

    ```
    */
    #[inline]
    #[must_use]
    pub const fn file_name(&self) -> &[u8] {
        debug_assert!(
            self.len() >= self.file_name_index(),
            "this should always be equal or below (equal only when root)"
        );

        let path = self.as_bytes();
        let len = path.len() - self.file_name_index;
        /*SAFETY:
        `file_name_index` returns a valid index within `bytes` bounds */
        unsafe {
            core::slice::from_raw_parts(path.as_ptr().add(self.file_name_index), len)
            // Rearranged to make const compatible(identical assembly to previous version but wasnt const)
        }
    }

    /// Takes the value of the path and gives the raw representation as a boxed Cstr
    #[inline]
    pub fn to_inner(self) -> Box<CStr> {
        self.path
    }

    /// Private function  because it invokes a closure (to avoid doubly allocating unnecessary)
    #[inline]
    pub(crate) fn get_realpath<F, T>(&self, f: F) -> Result<T>
    where
        F: Fn(&CStr) -> Result<T>,
    {
        // SAFETY: realpath mallocs a null-terminated string that must be freed, the pointer is null terminated
        let ptr = unsafe { realpath(self.as_ptr(), core::ptr::null_mut()) };

        if ptr.is_null() {
            return_os_error!()
        }

        // SAFETY: ptr is valid and points to a null-terminated C string
        let cstr = unsafe { CStr::from_ptr(ptr) };

        // Run supplied closure; allow propagation of Result errors
        let result = f(cstr);

        // SAFETY: ptr was allocated by realpath(), so we must free it explicitly(only after function is run)
        unsafe { libc::free(ptr.cast()) }

        result
    }

    /**
    Converts a directory entry to a full, canonical path, resolving all symlinks

    This is a **costly** operation as it involves a system call (`realpath`).
    If the filetype is a symlink, it invokes a stat call to find the realtype, otherwise stat is not called.

    # Errors

    Returns an `Err`

    It can be one of the following,
    `FileType::AccessDenied`, (EACCESS)
    `FileType::TooManySymbolicLinks`, ( ELOOP)
    `FileType::InvalidPath` (ENOENT)
    (There may be more, this documentation is not complete) TODO!



    # Examples
    these tests are broken on macos because of funky stuff  with mac's privacy/security settings.
    ```no_run

    use fdf::fs::DirEntry;
    use std::path::Path;
    use std::fs;
    use std::sync::Arc;
    use std::os::unix::ffi::OsStrExt as _;
    use std::os::unix::fs::symlink;
    let temp_dir = std::env::temp_dir();
    let target_path = temp_dir.join("target_file_full_path.txt");
    fs::File::create(&target_path).unwrap();
    let symlink_path = temp_dir.join("link_to_target_full_path.txt");
    symlink(&target_path, &symlink_path).unwrap();

    // Create a DirEntry from the symlink path
    let entry = DirEntry::new(&symlink_path).unwrap();
    assert!(entry.is_symlink());

    // Canonicalise the path
    let full_entry = entry.to_full_path().unwrap();

    // The full path of the canonicalised entry should match the target path.
    assert_eq!(full_entry.as_bytes(), target_path.as_os_str().as_bytes());

    fs::remove_file(&symlink_path).unwrap();
    fs::remove_file(&target_path).unwrap();

    ```
    */
    #[inline]
    #[allow(clippy::cast_possible_truncation)]
    pub fn to_full_path(&self) -> Result<Self> {
        self.get_realpath(|full_path| {
            let file_name_index = full_path.to_bytes().file_name_index();

            let (file_type, ino) = if self.is_symlink() {
                let statted = self.get_stat()?; // only call stat if it's a symlink, because I don't deduplicate normal files, this works well for symlinks
                (FileType::from_stat(&statted), access_stat!(statted, st_ino))
            } else {
                (self.file_type(), self.ino())
            };

            Ok(Self {
                path: full_path.into(),
                file_type,
                inode: ino,
                depth: self.depth,
                file_name_index,
                is_traversible_cache: Cell::new(Some(file_type == FileType::Directory)),
            })
        })
    }
    /**
    Returns the parent path as byte slice, or None if at root.

    # Examples

    Basic usage with a temporary directory and file:

    ```
    use fdf::fs::DirEntry;
    use std::fs::File;
    use std::os::unix::ffi::OsStrExt;
    let tmp = std::env::temp_dir().join("fdf_parent_test_dir");
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).unwrap();
    let file_path = tmp.join("file.txt");
    File::create(&file_path).unwrap();

    let entry = DirEntry::new(&file_path).unwrap();
    assert_eq!(entry.parent().unwrap(), tmp.as_os_str().as_bytes());

    std::fs::remove_file(&file_path).unwrap();
    std::fs::remove_dir_all(&tmp).unwrap();
    ```

    Root path yields `None` for parent (guarded to avoid failing on unusual systems):
    dot entries return an empty byte slice, mirroring semantics from stdlib.

    ```
    use fdf::fs::DirEntry;

    let root = DirEntry::new("/");
    if let Ok(e) = root {
        assert!(e.parent().is_none());
    }

    let dot=DirEntry::new(".");
    if let Ok(dotentry)=dot{
    let parent=dotentry.parent();
    assert!(dotentry.parent().is_some_and(|x| x.is_empty()));
    }

    ```
    */
    #[inline]
    pub fn parent(&self) -> Option<&[u8]> {
        self.as_path()
            .parent()
            .map(|path| path.as_os_str().as_bytes())
        // TODO rewrite this eventually
    }

    /**
    Checks if the file or directory is readable by the current process.

    This uses the `access` system call with `R_OK` to check read permissions
    without actually opening the file. It follows symlinks.

    # Returns

    `true` if the current process has read permission, `false` otherwise.

    `false` if the file doesn't exist or on permission errors.
    */
    #[inline]
    pub fn is_readable(&self) -> bool {
        // SAFETY: The path is guaranteed to be a be null terminated
        unsafe { access(self.as_ptr(), R_OK) == 0 }
    }

    /**
    Checks if the file or directory is writable by the current process.

    This uses the `access` system call with `W_OK` to check write permissions
    without actually opening the file. It follows symlinks.


    # Returns

    `true` if the current process has write permission, `false` otherwise.
    `false` if the file doesn't exist or on permission errors.
    */
    #[inline]
    pub fn is_writable(&self) -> bool {
        //maybe i can automatically exclude certain files from this check to
        //then reduce my syscall total, would need to read into some documentation. zadrot ebaniy
        // SAFETY: The path is guaranteed to be a null terminated
        unsafe { access(self.as_ptr(), W_OK) == 0 }
    }

    /**
    Checks if the file exists.

    This makes a system call to check file existence.
    */
    #[inline]
    pub fn exists(&self) -> bool {
        // SAFETY: The path is guaranteed to be null terminated
        unsafe { access(self.as_ptr(), F_OK) == 0 }
    }

    /**
    Gets file metadata using lstatat for a file relative to a directory file descriptor.

    This function uses `fstatat` with `AT_SYMLINK_NOFOLLOW` to get metadata without
    following symbolic links, similar to `lstat` but relative to a directory fd.

    # Arguments
    `fd` - Directory file descriptor to use as the base for relative path resolution

    # Returns
    A `stat` structure containing file metadata on success.

    # Errors
    Returns `DirEntryError::IOError` if the stat operation fails
    */
    #[inline]
    pub fn get_lstatat(&self, fd: &FileDes) -> Result<stat> {
        stat_syscall!(fstatat, fd.0, self.file_name_ptr(), AT_SYMLINK_NOFOLLOW)
    }

    /**

    Gets file status information without following symlinks.

    This performs an `lstat` system call to retrieve metadata about the file,
    including type, permissions, size, and timestamps. Unlike `stat`,
    `lstat` returns information about the symlink itself rather than the target.



    # Errors

    Returns an error if:
    - The file doesn't exist
    - Permission is denied
    - The path is invalid
    - System call fails for any other reason

    Returns `DirEntryError::IOError` if the stat operation fails

    A `stat` structure containing file metadata on success.
    */
    #[inline]
    pub fn get_lstat(&self) -> Result<stat> {
        stat_syscall!(lstat, self.as_ptr())
    }

    /**
    Gets file status information by following symlinks.

    This performs a `stat` system call to retrieve metadata about the file,
    including type, permissions, size, and timestamps. Unlike `lstat`,
    `stat` follows symbolic links and returns information about the target file
    rather than the link itself.


    # Errors

    Returns an error if:
    - The file doesn't exist
    - Permission is denied
    - The path is invalid
    - A symlink target doesn't exist
    - System call fails for any other reason

    #  Returns `DirEntryError::IOError` if the stat operation fails

    A `stat` structure containing file metadata on success.
    */
    #[inline]
    pub fn get_stat(&self) -> Result<stat> {
        // Simple wrapper to avoid code duplication so I can use the private method within the crate
        stat_syscall!(stat, self.as_ptr())
    }

    /**
    Gets file metadata using statat for a file relative to a directory file descriptor.

    This function uses `fstatat` with `AT_SYMLINK_FOLLOW` to get metadata by
    following symbolic links, similar to `stat` but relative to a directory fd.

    # Arguments
    `fd` - Directory file descriptor to use as the base for relative path resolution

    # Returns
    A `stat` structure containing file metadata on success.

    # Errors
    Returns `DirEntryError::IOError` if the stat operation fails

    */
    #[inline]
    pub fn get_statat(&self, fd: &FileDes) -> Result<stat> {
        stat_syscall!(fstatat, fd.0, self.file_name_ptr(), AT_SYMLINK_FOLLOW)
    }

    /// Cost free conversion to bytes (because it is already is bytes)
    #[inline]
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8] {
        self.path.to_bytes()
    }

    /**
    Returns the length of the path string in bytes.

    The length excludes the internal null terminator, so it matches
    what you'd expect from a regular Rust string slice length.

    # Examples
    ```
    use fdf::fs::DirEntry;
    use std::fs::File;

    let tmp = std::env::temp_dir().join("test_file.txt");
    File::create(&tmp).unwrap();

    let entry = DirEntry::new(&tmp).unwrap();
    // Length matches the path string without null terminator
    assert_eq!(entry.len(), tmp.as_os_str().len());

    std::fs::remove_file(tmp).unwrap();
    ```
    */
    #[inline]
    pub const fn len(&self) -> usize {
        self.path.count_bytes()
    }

    /// Returns the file type of the file (eg directory, regular file, etc)
    #[inline]
    #[must_use]
    pub const fn file_type(&self) -> FileType {
        self.file_type
    }

    ///Returns the depth relative to the start directory, this is cost free
    #[inline]
    #[must_use]
    pub const fn depth(&self) -> usize {
        self.depth as _
    }

    /// Returns the inode number of the file, cost free check
    ///
    ///
    /// This is a unique identifier for the file on the filesystem, it is not the same
    /// as the file name or path, it is a number that identifies the file on the
    // It should be u32 on BSD's but I use u64 for consistency across platforms
    #[inline]
    #[must_use]
    pub const fn ino(&self) -> u64 {
        self.inode
    }

    /// Applies a filter condition
    #[inline]
    #[must_use]
    pub fn filter<F: Fn(&Self) -> bool>(&self, func: F) -> bool {
        func(self)
    }

    /// Returns the length of the base path (eg /home/user/ is 6 '/home/') and '/' is 0
    #[inline]
    #[must_use]
    pub const fn file_name_index(&self) -> usize {
        self.file_name_index
    }

    /// Checks if the file is a directory or symlink (but internally a directory)
    #[inline]
    #[must_use]
    pub fn is_traversible(&self) -> bool {
        match self.file_type {
            FileType::Directory => true,
            FileType::Symlink => self.check_symlink_traversibility(), // we essentially use a cache to avoid recalling this for subsequent calls, see below.
            _ => false,
        }
    }

    /// Checks if a symlink points to a traversible directory, caching the result.
    #[inline]
    pub(crate) fn check_symlink_traversibility(&self) -> bool {
        debug_assert!(
            self.file_type() == FileType::Symlink,
            "we only expect symlinks to use this function(hence private)"
        );
        // Return cached result if available
        if let Some(cached) = self.is_traversible_cache.get() {
            return cached;
        }

        // Compute and cache the result
        let is_traversible = self
            .get_stat()
            .is_ok_and(|entry| FileType::from_stat(&entry) == FileType::Directory);

        self.is_traversible_cache.set(Some(is_traversible));
        is_traversible
    }

    /** Checks if the file is hidden (e.g., `.gitignore`, `.config`).

    A file is considered hidden if its filename (not the full path)
    starts with a dot ('.') character.

    Useful for filtering out hidden files in directory listings.

    # Examples

    ```
    use fdf::fs::DirEntry;
    use std::fs::File;
    use std::io::Write;

    // Create a temporary hidden file
    let tmp = std::env::temp_dir().join(".hidden_file.txt");
    File::create(&tmp).unwrap().write_all(b"content").unwrap();

    // Build DirEntry
    let entry = DirEntry::new(&tmp).unwrap();

    // Check if it's hidden
    assert!(entry.is_hidden());

    std::fs::remove_file(tmp).unwrap();
    ```

    ```
    use fdf::fs::DirEntry;
    use std::fs::File;

    // Regular non-hidden file
    let tmp = std::env::temp_dir().join("visible_file.txt");
    File::create(&tmp).unwrap();

    let entry = DirEntry::new(&tmp).unwrap();
    assert!(!entry.is_hidden());

    std::fs::remove_file(tmp).unwrap();
    ```

    ```
    use fdf::fs::DirEntry;
    use std::fs::File;

    // File with multiple dots but not hidden
    let tmp = std::env::temp_dir().join("backup.old.txt");
    File::create(&tmp).unwrap();

    let entry = DirEntry::new(&tmp).unwrap();
    assert!(!entry.is_hidden());

    std::fs::remove_file(tmp).unwrap();
    ```

    ```
    use fdf::fs::DirEntry;
    use std::fs::File;

    // Edge case: just a dot
    let tmp = std::env::temp_dir().join(".helo");
    File::create(&tmp).unwrap();

    let entry = DirEntry::new(&tmp).unwrap();
    assert!(entry.is_hidden());

    std::fs::remove_file(tmp).unwrap();
    ```
    */
    #[inline]
    #[must_use]
    pub const fn is_hidden(&self) -> bool {
        // SAFETY: file_name_index is guaranteed to be within bounds
        // and we're using pointer arithmetic which is const-compatible (slight const hack)
        unsafe { self.as_ptr().cast::<u8>().add(self.file_name_index).read() == b'.' }
    }

    /**
    Returns the directory name of the file (as bytes)
    ```
    use fdf::fs::DirEntry;
    use std::fs::File;
    use std::io::Write;

    // Test 1: Regular file path with directory structure
    let tmp = std::env::temp_dir().join("test_dir/file.txt");
    if let Some(parent) = tmp.parent() {
       std::fs::create_dir_all(parent).unwrap();
       }
       File::create(&tmp).unwrap();

       let entry = DirEntry::new(&tmp).unwrap();
       assert_eq!(entry.dirname(), b"test_dir");

       std::fs::remove_file(&tmp).unwrap();
       std::fs::remove_dir_all(tmp.parent().unwrap()).unwrap();


       let root_dir=DirEntry::new("/");
       assert!(root_dir.is_err() || root_dir.is_ok_and(|x| x.dirname()==b"/"));

       ```
       */
    #[inline]
    #[must_use]
    pub fn dirname(&self) -> &[u8] {
        debug_assert!(
            self.file_name_index() <= self.len(),
            "Indexing should always be within bounds"
        );

        if self.len() == 1 && self.as_bytes() == b"/" {
            return b"/";
        }

        // SAFETY: the index is below the length of the path trivially
        unsafe {
            self //this is why we store the baseline, to check this and is hidden as above, its very useful and cheap
                .get_unchecked(..self.file_name_index().saturating_sub(1))
                .rsplit(|&b| b == b'/')
                .next()
                .unwrap_or(self.as_bytes())
        }
    }

    /**
      Extracts the extension of the file name, if any.

     The extension is defined as the substring after the last dot (`.`) character
     in the file name, excluding cases where the dot is the final character.

     # Examples

     ```
     use fdf::fs::DirEntry;
     use std::env::temp_dir;

     let tmp=std::env::temp_dir();
     let file_test=tmp.join("file.txt");
      std::fs::File::create(&file_test).unwrap();

     let path = DirEntry::new(&file_test).unwrap();
     assert_eq!(path.extension(), Some(b"txt".as_ref()));
      std::fs::remove_file(&file_test).unwrap();

     let root_dir=DirEntry::new("/");
     assert!(root_dir.is_err() || root_dir.is_ok_and(|path| path.extension().is_none()));
     ```
    */
    #[inline]
    pub fn extension(&self) -> Option<&[u8]> {
        let filename = self.file_name();
        let len = filename.len();

        if len <= 1 {
            return None;
        }

        // Search for the last dot in the filename, excluding the last character ('.''s dont count if they're the final character)
        // SAFETY: len is guaranteed within bounds
        let search_range = unsafe { &filename.get_unchecked(..len.saturating_sub(1)) };

        crate::util::memrchr(b'.', search_range).map(|pos| {
            // SAFETY:
            // - `pos` comes from `memrchr` which searches within `search_range`
            // - `search_range` is a subslice of `filename` (specifically `filename[..len-1]`)
            // - Therefore `pos` is a valid index in `filename`
            // - `pos + 1` is guaranteed to be ≤ len-1, so `pos + 1..` is a valid range
            unsafe { filename.get_unchecked(pos + 1..) }
        })
    }

    /**
    Creates a new [`DirEntry`] from the given path.

    This constructor attempts to resolve metadata for the provided path using
    a `lstat` call. If successful, it initialises a `DirEntry` with the path,
    file type, inode, and some derived metadata such as depth and file name index.



    # Examples
    ```
    use fdf::fs::DirEntry;
    use std::env;

    # fn main() -> Result<(), fdf::DirEntryError> {
       // Use the system temporary directory
       let tmp = env::temp_dir();

       // Create a DirEntry from the temporary directory path
       let entry = DirEntry::new(tmp)?;

       println!("inode: {}", entry.ino());
       Ok(())
       }
    ```



    # Errors

    The following returns an `DirEntryError::IOError` error when the file doesn't exist:

    ```
    use fdf::{fs::DirEntry, DirEntryError};
    use std::fs;

    // Verify the path doesn't exist first
    let nonexistent_path = "/definitely/not/a/real/file/lalalalalalalalalalalal";
    assert!(!fs::metadata(nonexistent_path).is_ok());

       // This will return an DirEntry::IOError because the file does not exist
    let result = DirEntry::new(nonexistent_path);
    match result {
           Ok(_) => panic!("this should never happen!"),
           Err(DirEntryError::IOError(_)) => {}, // Expected error
           Err(_) => panic!("Expected  error, got different error"),
           }

    ```
    */
    #[inline]
    pub fn new<T: AsRef<OsStr>>(path: T) -> Result<Self> {
        // It doesn't really matter if this constructor is 'expensive' mostly because the iterator constructs
        // this without lstat.
        let mut path_ref = path.as_ref().as_bytes();
        // Strip trailing slash

        if path_ref != b"/"
            && let Some(stripped) = path_ref.strip_suffix(b"/")
        {
            path_ref = stripped;
        }

        let cstring = std::ffi::CString::new(path_ref).map_err(DirEntryError::NulError)?;

        // extract information from successful stat
        let get_stat = stat_syscall!(lstat, cstring.as_ptr()).map_err(DirEntryError::IOError)?;
        let inode = access_stat!(get_stat, st_ino);
        let file_name_index = path_ref.file_name_index();
        let file_type = FileType::from_stat(&get_stat);
        Ok(Self {
            path: cstring.into(),
            file_type,
            inode,
            depth: 0,
            file_name_index,
            is_traversible_cache: Cell::new(None), //no need to check(we'd need to call stat instead!)
        })
    }

    /**
      Returns the last modification time of the file in UTC.

     This method performs an `lstat` system call to retrieve metadata for the entry.
     Unlike `stat`, it does **not** follow symbolic links. If the entry is a symlink,
     the modification time of the link itself is returned rather than that of its target.

     # Errors

     Returns an [`Err`] if:
     - The `lstat` call fails (for example, due to insufficient permissions or an invalid path).
     - The timestamp retrieved from the OS cannot be represented as a valid [`DateTime<Utc>`].

     # Notes

     The timestamp is constructed using seconds (`st_mtime`) and nanoseconds (`st_mtimensec`)
     from the underlying `stat` structure. These values are cast to `u32` internally
     to match the expected type for [`chrono::DateTime::from_timestamp`].

     # Examples

     ```no_run
     use fdf::fs::DirEntry;
     use chrono::Utc;

     let entry = DirEntry::new("/tmp/example.txt").unwrap();
     let modified = entry.modified_time().unwrap();

     println!("Last modified at: {}", modified.with_timezone(&Utc));
     ```
    */
    #[inline]
    #[expect(
        clippy::cast_sign_loss,
        clippy::cast_possible_truncation,
        reason = "needs to be in u32 for chrono"
    )]
    pub fn modified_time(&self) -> Result<DateTime<Utc>> {
        let statted = self.get_lstat()?;

        DateTime::from_timestamp(
            access_stat!(statted, st_mtime),
            access_stat!(statted, st_mtimensec),
        )
        .ok_or(DirEntryError::TimeError)
    }

    /**
    Gets the file size in bytes.

    This method retrieves the file size by calling `get_lstat()` and extracting
    the `st_size` field from the stat structure. Unlike `get_stat()`, this
    method does not follow symbolic links - it returns the size of the symlink
    itself rather than the target file.

    # Errors

    Returns an error if:
    - The file doesn't exist
    - Permission is denied
    - The path is invalid
    - The lstat system call fails for any other reason

    # Returns

    The size of the file in bytes as an `u64`. For symbolic links, this returns
    the length of the symlink path itself, not the target file size.
    */
    #[inline]
    #[expect(clippy::cast_sign_loss, reason = "Size is a u64")]
    pub fn file_size(&self) -> Result<u64> {
        //https://github.com/rust-lang/rust/blob/bbb6f68e2888eea989337d558b47372ecf110e08/library/std/src/sys/fs/unix.rs#L442
        self.get_lstat().map(|s| s.st_size as _)
    }

    /**
     Returns an iterator over directory entries using the `readdir` API.

     This provides a higher-level, more portable interface for directory iteration
     compared to `getdents`. Suitable for most use cases where maximum performance
     isn't critical.

     # Errors

     Returns `Err` if:
     - The entry is not a directory
     - Permission restrictions prevent reading the directory
     - The directory has been removed or become inaccessible
     - Any other system error occurs during directory opening/reading

     # Examples

     ```
     use fdf::fs::DirEntry;
     use std::fs::{self, File};
     use std::io::Write;
     use std::sync::Arc;

     // Create a temporary directory with test files
     let temp_dir = std::env::temp_dir().join("test_readdir");
     fs::create_dir(&temp_dir).unwrap();

     // Create test files
     File::create(temp_dir.join("file1.txt")).unwrap().write_all(b"test").unwrap();
     File::create(temp_dir.join("file2.txt")).unwrap().write_all(b"test").unwrap();
     fs::create_dir(temp_dir.join("subdir")).unwrap();

     // Create DirEntry for the temporary directory
     let entry = DirEntry::new(&temp_dir).unwrap();

     // Use readdir to iterate through directory contents
     let mut entries: Vec<_> = entry.readdir().unwrap().collect();
     entries.sort_by_key(|e| e.file_name().to_vec());

     // Should contain 3 entries: 2 files and 1 directory
     assert_eq!(entries.len(), 3);
     assert!(entries.iter().any(|e| e.file_name() == b"file1.txt"));
     assert!(entries.iter().any(|e| e.file_name() == b"file2.txt"));
     assert!(entries.iter().any(|e| e.file_name() == b"subdir"));
     fs::remove_dir_all(&temp_dir).unwrap();
    ```
    */
    #[inline]
    pub fn readdir(&self) -> Result<ReadDir> {
        ReadDir::new(self)
    }

    /**
     Low-level directory iterator using the `getdents(64)` system call.

     This method provides high-performance directory scanning by using a large buffer
     generally faster than `readdir` for bulk directory operations due to lack of needing to call stat.

     # Errors

     Returns `Err` if:
     - The entry is not a directory
     - Permission restrictions prevent reading the directory
     - The directory file descriptor cannot be opened
     - Buffer allocation fails
     - Any other system error occurs during the `getdents` operation

     # Platform Specificity

     This method is only available on Linux/Android/OpenBSD/NetBSD/Illumos/Solaris.

     # Examples

     ```
     use fdf::fs::DirEntry;
     use std::fs::{self, File};
     use std::io::Write;

     // Create a temporary directory with test files
     let temp_dir = std::env::temp_dir().join("test_getdents");
     fs::create_dir(&temp_dir).unwrap();

     // Create test files
     File::create(temp_dir.join("file1.txt")).unwrap().write_all(b"test").unwrap();
     File::create(temp_dir.join("file2.txt")).unwrap().write_all(b"test").unwrap();
     fs::create_dir(temp_dir.join("subdir")).unwrap();

     // Create DirEntry for the temporary directory
     let entry= DirEntry::new(&temp_dir).unwrap();

     // Use getdents to iterate through directory contents
     let mut entries: Vec<_> = entry.getdents().unwrap().collect();
     entries.sort_by_key(|e| e.file_name().to_vec());

     // Should contain 3 entries: 2 files and 1 directory
     assert_eq!(entries.len(), 3);
     assert!(entries.iter().any(|e| e.file_name() == b"file1.txt"));
     assert!(entries.iter().any(|e| e.file_name() == b"file2.txt"));
     assert!(entries.iter().any(|e| e.file_name() == b"subdir"));

     // Clean up
     fs::remove_dir_all(&temp_dir).unwrap();
    ```
    */
    #[inline]
    #[cfg(any(
        target_os = "linux",
        target_os = "android",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "illumos",
        target_os = "solaris"
    ))]
    pub fn getdents(&self) -> Result<crate::fs::GetDents> {
        crate::fs::GetDents::new(self)
    }

    //TODO add dragonflybsd
    /**
    Low-level directory iterator using macOS/FreeBSD `getdirentries64`/`getdirentries` system calls.

    This method provides a macOS/BSD-specific, high-performance streaming iterator
    over directory entries by leveraging the platform's `getdirentries(2)`
    family. It is analogous to the Linux `getdents` specialisation

    It implements a specialised EOF trick to avoid an extra syscall to terminate reading on macOS


    # Platform
    - macOS only/FreeBSD only (future plans to expand to NetBSD/DragonFlyBSD)

    # Errors
    Returns `Err` when the directory cannot be opened or read, when the
    target is not a directory, or when permissions prevent iteration.


    For examples: See documentation on `readdir`
    ```
    */
    #[inline]
    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
    pub fn getdirentries(&self) -> Result<crate::fs::GetDirEntries> {
        crate::fs::GetDirEntries::new(self)
    }
}