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
//! Raw structures and functions implementations.

use core::{fmt, mem::MaybeUninit};

use linux_raw_sys::general::{
    S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG, S_IFSOCK,
};

use crate::{CStr, Dev, DevSplit, FileType, Mode, RawFd, StatAtFlags, Timestamp};

#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "aarch64"),
    path = "aarch64.rs"
)]
#[cfg_attr(all(not(feature = "linux_4_11"), target_arch = "arm"), path = "arm.rs")]
#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "mips"),
    path = "mips.rs"
)]
#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "mips64"),
    path = "mips64.rs"
)]
#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "powerpc"),
    path = "powerpc.rs"
)]
#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "powerpc64"),
    path = "powerpc64.rs"
)]
#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "riscv64"),
    path = "riscv64.rs"
)]
#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "s390x"),
    path = "s390x.rs"
)]
#[cfg_attr(all(not(feature = "linux_4_11"), target_arch = "x86"), path = "x86.rs")]
#[cfg_attr(
    all(not(feature = "linux_4_11"), target_arch = "x86_64"),
    path = "x86_64.rs"
)]
mod stat_imp;

#[cfg(all(not(feature = "linux_4_11"), not(target_arch = "loongarch64")))]
pub use stat_imp::stat;

use linux_syscalls::{bitflags, syscall, Errno, Sysno};

bitflags! {
    /// A mask to tell the kernel which fields the caller is interested in.
    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub enum StatXMask: u32 {
        /// Want stx_mode & S_IFMT
        TYPE = linux_raw_sys::general::STATX_TYPE,
        /// Want stx_mode & ~S_IFMT
        MODE = linux_raw_sys::general::STATX_MODE,
        /// Want stx_nlink
        NLINK = linux_raw_sys::general::STATX_NLINK,
        /// Want stx_uid
        UID = linux_raw_sys::general::STATX_UID,
        /// Want stx_gid
        GID = linux_raw_sys::general::STATX_GID,
        /// Want stx_atime
        ATIME = linux_raw_sys::general::STATX_ATIME,
        /// Want stx_mtime
        MTIME = linux_raw_sys::general::STATX_MTIME,
        /// Want stx_ctime
        CTIME = linux_raw_sys::general::STATX_CTIME,
        /// Want stx_ino
        INO = linux_raw_sys::general::STATX_INO,
        /// Want stx_size
        SIZE = linux_raw_sys::general::STATX_SIZE,
        /// Want stx_blocks
        BLOCKS = linux_raw_sys::general::STATX_BLOCKS,
        /// [All of the above]
        BASIC_STATS = linux_raw_sys::general::STATX_BASIC_STATS,
        /// Want stx_btime
        BTIME = linux_raw_sys::general::STATX_BTIME,
        /// The same as STATX_BASIC_STATS | STATX_BTIME.
        ALL = linux_raw_sys::general::STATX_ALL,
        /// Want stx_mnt_id (since Linux 5.8)
        MNT_ID = linux_raw_sys::general::STATX_MNT_ID,
        /// Want stx_dio_mem_align and stx_dio_offset_align
        /// (since Linux 6.1; support varies by filesystem)
        DIOALIGN = linux_raw_sys::general::STATX_DIOALIGN,
    }
}

bitflags! {
    /// A set of ORed flags that indicate additional attributes of the file.
    /// Note that any attribute that is not indicated as supported by
    /// stx_attributes_mask has no usable value here.
    /// The bits in stx_attributes_mask correspond bit-by-bit to stx_attributes.
    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub enum StatXAttr: u64 {
        /// The file is compressed by the filesystem and may take extra
        /// resources to access
        COMPRESSED = linux_raw_sys::general::STATX_ATTR_COMPRESSED as u64,
        /// The file cannot be modified: it cannot be deleted or renamed, no
        /// hard links can be created to this file and no data can be
        /// written to it.  See chattr(1).
        IMMUTABLE = linux_raw_sys::general::STATX_ATTR_IMMUTABLE as u64,
        /// The file can only be opened in append mode for writing.  Random
        /// access writing is not permitted.  See chattr(1).
        APPEND = linux_raw_sys::general::STATX_ATTR_APPEND as u64,
        /// File is not a candidate for backup when a backup program such as
        /// dump(8) is run.  See chattr(1).
        NODUMP = linux_raw_sys::general::STATX_ATTR_NODUMP as u64,
        /// A key is required for the file to be encrypted by the
        /// filesystem.
        ENCRYPTED = linux_raw_sys::general::STATX_ATTR_ENCRYPTED as u64,
        AUTOMOUNT = linux_raw_sys::general::STATX_ATTR_AUTOMOUNT as u64,
        MOUNT_ROOT = linux_raw_sys::general::STATX_ATTR_MOUNT_ROOT as u64,
        /// The file has fs-verity enabled.  It cannot be written to, and
        /// all reads from it will be verified against a cryptographic hash
        /// that covers the entire file (e.g., via a Merkle tree).
        VERITY = linux_raw_sys::general::STATX_ATTR_VERITY as u64,
        /// The file is in the DAX (cpu direct access) state.  DAX state
        /// attempts to minimize software cache effects for both I/O and
        /// memory mappings of this file.  It requires a file system which
        /// has been configured to support DAX.
        ///
        /// DAX generally assumes all accesses are via CPU load / store
        /// instructions which can minimize overhead for small accesses, but
        /// may adversely affect CPU utilization for large transfers.
        ///
        /// File I/O is done directly to/from user-space buffers and memory
        /// mapped I/O may be performed with direct memory mappings that
        /// bypass the kernel page cache.
        ///
        /// While the DAX property tends to result in data being transferred
        /// synchronously, it does not give the same guarantees as the
        /// O_SYNC flag (see open(2)), where data and the necessary metadata
        /// are transferred together.
        ///
        /// A DAX file may support being mapped with the MAP_SYNC flag,
        /// which enables a program to use CPU cache flush instructions to
        /// persist CPU store operations without an explicit fsync(2).  See
        /// mmap(2) for more information
        DAX = linux_raw_sys::general::STATX_ATTR_DAX as u64,
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
#[allow(non_camel_case_types)]
struct timestamp {
    tv_sec: i64,
    tv_nsec: u32,
    __pad: u32,
}

impl fmt::Debug for timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("timestamp")
            .field("tv_sec", &self.tv_sec)
            .field("tv_nsec", &self.tv_nsec)
            .finish()
    }
}

/// `statx()` file informations representation.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Statx {
    stx_mask: StatXMask,
    stx_blksize: i32,
    stx_attributes: u64,
    stx_nlink: u32,
    stx_uid: u32,
    stx_gid: u32,
    stx_mode: u16,
    stx_ino: u64,
    stx_size: i64,
    stx_blocks: i64,
    stx_attributes_mask: StatXAttr,
    stx_atime: timestamp,
    stx_btime: timestamp,
    stx_ctime: timestamp,
    stx_mtime: timestamp,
    stx_rdev_major: u32,
    stx_rdev_minor: u32,
    stx_dev_major: u32,
    stx_dev_minor: u32,
    stx_mnt_id: u64,
    stx_dio_mem_align: u32,
    stx_dio_offset_align: u32,
    spare: [u64; 14],
}

#[inline(always)]
const fn file_type(mode: u16) -> FileType {
    match mode as u32 & S_IFMT {
        S_IFSOCK => FileType::Socket,
        S_IFLNK => FileType::Link,
        S_IFREG => FileType::Regular,
        S_IFBLK => FileType::Block,
        S_IFDIR => FileType::Directory,
        S_IFCHR => FileType::Character,
        S_IFIFO => FileType::Fifo,
        _ => FileType::Unknown,
    }
}

impl Statx {
    /// Returns the "preferred" block size for efficient filesystem I/O.
    /// (Writing to a file in smaller chunks may cause an inefficient
    /// read-modify-rewrite.)
    #[inline]
    pub const fn block_size(&self) -> i32 {
        self.stx_blksize
    }
    /// Returns further status information about the file (see below for more
    /// information).
    #[inline]
    pub const fn attributes(&self) -> u64 {
        self.stx_attributes
    }

    /// Returns the number of hard links on a file.
    #[inline]
    pub const fn nlink(&self) -> u32 {
        self.stx_nlink
    }

    /// Returns the user ID of the owner of the file.
    #[inline]
    pub const fn uid(&self) -> u32 {
        self.stx_uid
    }

    /// Returns the ID of the group owner of the file.
    #[inline]
    pub const fn gid(&self) -> u32 {
        self.stx_gid
    }

    /// Returns the file mode.
    #[inline]
    pub const fn mode(&self) -> Mode {
        Mode(self.stx_mode & !(S_IFMT as u16))
    }

    /// Returns the file type.
    pub const fn file_type(&self) -> FileType {
        file_type(self.stx_mode)
    }

    /// Returns true if file type is socket.
    #[inline]
    pub const fn is_socket(&self) -> bool {
        self.stx_mode as u32 & S_IFMT == S_IFSOCK
    }

    /// Returns true if file type is link.
    #[inline]
    pub const fn is_link(&self) -> bool {
        self.stx_mode as u32 & S_IFMT == S_IFLNK
    }

    /// Returns true if file type is regular.
    #[inline]
    pub const fn is_regular(&self) -> bool {
        self.stx_mode as u32 & S_IFMT == S_IFREG
    }

    /// Returns true if file type is block.
    #[inline]
    pub const fn is_block(&self) -> bool {
        self.stx_mode as u32 & S_IFMT == S_IFBLK
    }

    /// Returns true if file type is directory.
    #[inline]
    pub const fn is_directory(&self) -> bool {
        self.stx_mode as u32 & S_IFMT == S_IFDIR
    }

    /// Alias for `Self::is_directory()`.
    #[inline]
    pub const fn is_dir(&self) -> bool {
        self.is_directory()
    }

    /// Returns true if file type is character.
    #[inline]
    pub const fn is_character(&self) -> bool {
        self.stx_mode as u32 & S_IFMT == S_IFCHR
    }

    /// Alias for `Self::is_character()`.
    #[inline]
    pub const fn is_char(&self) -> bool {
        self.is_character()
    }

    /// Returns true if file type is FIFO.
    #[inline]
    pub const fn is_fifo(&self) -> bool {
        self.stx_mode as u32 & S_IFMT == S_IFIFO
    }

    /// Returns the inode number of the file.
    #[inline]
    pub const fn inode(&self) -> u64 {
        self.stx_ino
    }

    /// Returns the size of the file (if it is a regular file or a symbolic
    /// link) in bytes. The size of a symbolic link is the length of
    /// the pathname it contains, without a terminating null byte.
    #[inline]
    pub const fn size(&self) -> i64 {
        self.stx_size
    }

    /// Returns the number of blocks allocated to the file on the medium, in
    /// 512-byte units. (This may be smaller than stx_size/512 when the
    /// file has holes.)
    #[inline]
    pub const fn blocks(&self) -> i64 {
        self.stx_blocks
    }

    /// A mask indicating which bits in stx_attributes are supported by
    /// the VFS and the filesystem.
    #[inline]
    pub const fn attributes_mask(&self) -> StatXAttr {
        self.stx_attributes_mask
    }

    /// Returns the file's last access timestamp.
    #[inline]
    pub const fn atime(&self) -> Timestamp {
        Timestamp {
            secs: self.stx_atime.tv_sec,
            nsecs: self.stx_atime.tv_nsec,
        }
    }

    /// Returns the file's creation timestamp
    #[inline]
    pub const fn btime(&self) -> Timestamp {
        Timestamp {
            secs: self.stx_btime.tv_sec,
            nsecs: self.stx_btime.tv_nsec,
        }
    }

    /// Returns the file's last status change timestamp.
    #[inline]
    pub const fn ctime(&self) -> Timestamp {
        Timestamp {
            secs: self.stx_ctime.tv_sec,
            nsecs: self.stx_ctime.tv_nsec,
        }
    }

    /// Returns the file's last modification timestamp.
    #[inline]
    pub const fn mtime(&self) -> Timestamp {
        Timestamp {
            secs: self.stx_mtime.tv_sec,
            nsecs: self.stx_mtime.tv_nsec,
        }
    }

    /// Returns the major device that this file (inode) represents if the file
    /// is of block or character device type
    #[inline]
    pub const fn rdev_major(&self) -> u32 {
        self.stx_rdev_major
    }

    /// Returns the minor device that this file (inode) represents if the file
    /// is of block or character device type
    #[inline]
    pub const fn rdev_minor(&self) -> u32 {
        self.stx_rdev_minor
    }

    /// Returns the device that this file (inode) represents if the file is of
    /// block or character device type
    #[inline]
    pub const fn rdev(&self) -> Dev {
        Dev::Split(DevSplit::new(self.rdev_major(), self.rdev_minor()))
    }

    /// Returns the major device on which this file (inode) resides.
    #[inline]
    pub const fn dev_major(&self) -> u32 {
        self.stx_dev_major
    }

    /// Returns the minor device on which this file (inode) resides.
    #[inline]
    pub const fn dev_minor(&self) -> u32 {
        self.stx_dev_minor
    }

    /// Returns the device on which this file (inode) resides.
    #[inline]
    pub const fn dev(&self) -> Dev {
        Dev::Split(DevSplit::new(self.dev_major(), self.dev_minor()))
    }

    /// The mount ID of the mount containing the file.  This is the same
    /// number reported by name_to_handle_at(2) and corresponds to the
    /// number in the first field in one of the records in
    /// /proc/self/mountinfo.
    #[inline]
    pub const fn mount_id(&self) -> u64 {
        self.stx_mnt_id
    }

    /// Returns the alignment (in bytes) required for user memory buffers for
    /// direct I/O (O_DIRECT) on this file, or 0 if direct I/O is not
    /// supported on this file.
    ///
    /// STATX_DIOALIGN (stx_dio_mem_align and stx_dio_offset_align) is
    /// supported on block devices since Linux 6.1.  The support on
    /// regular files varies by filesystem; it is supported by ext4,
    /// f2fs, and xfs since Linux 6.1.
    #[inline]
    pub const fn dio_mem_align(&self) -> u32 {
        self.stx_dio_mem_align
    }

    /// Returns the alignment (in bytes) required for file offsets and I/O
    /// segment lengths for direct I/O (O_DIRECT) on this file, or 0 if
    /// direct I/O is not supported on this file.  This will only be
    /// nonzero if stx_dio_mem_align is nonzero, and vice versa.
    #[inline]
    pub const fn dio_offset_align(&self) -> u32 {
        self.stx_dio_offset_align
    }

    pub(crate) fn debug(&self, f: &mut fmt::Formatter<'_>, name: &str) -> fmt::Result {
        f.debug_struct(name)
            .field("dev", &self.dev())
            .field("ino", &self.inode())
            .field("nlink", &self.nlink())
            .field("mode", &self.mode())
            .field("uid", &self.uid())
            .field("gid", &self.gid())
            .field("rdev", &self.rdev())
            .field("size", &self.size())
            .field("block_size", &self.block_size())
            .field("blocks", &self.blocks())
            .field("atime", &self.atime())
            .field("btime", &self.btime())
            .field("mtime", &self.mtime())
            .field("ctime", &self.ctime())
            .field("attributes", &self.attributes())
            .field("attributes_mask", &self.attributes_mask())
            .field("mount_id", &self.mount_id())
            .field("dio_mem_align", &self.dio_mem_align())
            .field("dio_offset_align", &self.dio_offset_align())
            .finish()
    }
}

impl fmt::Debug for Statx {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.debug(f, "Statx")
    }
}

impl Statx {
    #[doc(hidden)]
    pub fn uninit() -> MaybeUninit<Self> {
        let mut buf = MaybeUninit::<Self>::uninit();
        unsafe {
            let buf = &mut *buf.as_mut_ptr();
            core::ptr::write_bytes(
                &mut buf.spare[0] as *mut u64 as *mut u8,
                0,
                core::mem::size_of_val(&buf.spare),
            );
        }
        buf
    }
}

#[cfg(all(not(feature = "linux_4_11"), not(target_arch = "loongarch64")))]
impl stat {
    /// Returns the file mode.
    #[inline]
    pub const fn mode(&self) -> Mode {
        Mode(self.raw_mode() & !(S_IFMT as u16))
    }

    /// Returns the file type.
    pub const fn file_type(&self) -> FileType {
        file_type(self.raw_mode())
    }

    /// Returns true if file type is socket.
    #[inline]
    pub const fn is_socket(&self) -> bool {
        self.raw_mode() as u32 & S_IFMT == S_IFSOCK
    }

    /// Returns true if file type is link.
    #[inline]
    pub const fn is_link(&self) -> bool {
        self.raw_mode() as u32 & S_IFMT == S_IFLNK
    }

    /// Returns true if file type is regular.
    #[inline]
    pub const fn is_regular(&self) -> bool {
        self.raw_mode() as u32 & S_IFMT == S_IFREG
    }

    /// Returns true if file type is block.
    #[inline]
    pub const fn is_block(&self) -> bool {
        self.raw_mode() as u32 & S_IFMT == S_IFBLK
    }

    /// Returns true if file type is directory.
    #[inline]
    pub const fn is_directory(&self) -> bool {
        self.raw_mode() as u32 & S_IFMT == S_IFDIR
    }

    /// Alias for `Self::is_directory()`.
    #[inline]
    pub const fn is_dir(&self) -> bool {
        self.is_directory()
    }

    /// Returns true if file type is character.
    #[inline]
    pub const fn is_character(&self) -> bool {
        self.raw_mode() as u32 & S_IFMT == S_IFCHR
    }

    /// Alias for `Self::is_character()`.
    #[inline]
    pub const fn is_char(&self) -> bool {
        self.is_character()
    }

    /// Returns true if file type is FIFO.
    #[inline]
    pub const fn is_fifo(&self) -> bool {
        self.raw_mode() as u32 & S_IFMT == S_IFIFO
    }

    /// Returns the minor device on which this file (inode) resides.
    #[inline]
    pub const fn dev_minor(&self) -> u32 {
        self.dev().minor()
    }

    /// Returns the major device on which this file (inode) resides.
    #[inline]
    pub const fn dev_major(&self) -> u32 {
        self.dev().major()
    }

    /// Returns the minor device that this file (inode) represents if the file
    /// is of block or character device type
    #[inline]
    pub const fn rdev_minor(&self) -> u32 {
        self.rdev().minor()
    }

    /// Returns the major device that this file (inode) represents if the file
    /// is of block or character device type
    #[inline]
    pub const fn rdev_major(&self) -> u32 {
        self.rdev().major()
    }

    pub(crate) fn debug(&self, f: &mut fmt::Formatter<'_>, name: &str) -> fmt::Result {
        f.debug_struct(name)
            .field("dev", &self.dev())
            .field("ino", &self.inode())
            .field("nlink", &self.nlink())
            .field("mode", &self.mode())
            .field("uid", &self.uid())
            .field("gid", &self.gid())
            .field("rdev", &self.rdev())
            .field("size", &self.size())
            .field("block_size", &self.block_size())
            .field("blocks", &self.blocks())
            .field("atime", &self.atime())
            .field("mtime", &self.mtime())
            .field("ctime", &self.ctime())
            .finish()
    }
}

#[cfg(all(not(feature = "linux_4_11"), not(target_arch = "loongarch64")))]
impl fmt::Debug for stat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.debug(f, "stat")
    }
}

/// Invoke `fstatat` system call.
///
/// # Safety
///
/// This functions is inherently unsafe because it just wrap the system call
/// and directory file descriptor (`dirfd`) cannot be checked.
#[cfg(all(not(feature = "linux_4_11"), not(target_arch = "loongarch64")))]
#[inline]
pub unsafe fn fstatat<P: AsRef<crate::Path>>(
    dirfd: RawFd,
    path: P,
    flags: StatAtFlags,
) -> Result<stat, Errno> {
    crate::run_with_cstr(path, |path| fstatat_cstr(dirfd, path, flags))
}

/// Invoke `fstatat` system call with `path` as a [crate::CStr].
///
/// # Safety
///
/// This functions is inherently unsafe because it just wrap the system call
/// and directory file descriptor (`dirfd`) cannot be checked.
#[cfg(all(not(feature = "linux_4_11"), not(target_arch = "loongarch64")))]
#[inline]
pub unsafe fn fstatat_cstr(dirfd: RawFd, path: &CStr, flags: StatAtFlags) -> Result<stat, Errno> {
    let mut buf = stat::uninit();
    syscall!(
        stat_imp::SYS_FSTATAT,
        dirfd,
        path.as_ptr(),
        buf.as_mut_ptr(),
        flags.bits()
    )?;
    Ok(buf.assume_init())
}

/// Invoke `statx` system call.
///
/// # Safety
///
/// This functions is inherently unsafe because it just wrap the system call
/// and directory file descriptor (`dirfd`) cannot be checked.
#[inline]
pub unsafe fn statx<P: AsRef<crate::Path>>(
    dirfd: RawFd,
    path: P,
    flags: StatAtFlags,
    mask: StatXMask,
) -> Result<Statx, Errno> {
    crate::run_with_cstr(path, |path| statx_cstr(dirfd, path, flags, mask))
}

/// Invoke `statx` system call with `path` as a [crate::CStr].
///
/// # Safety
///
/// This functions is inherently unsafe because it just wrap the system call
/// and directory file descriptor (`dirfd`) cannot be checked.
#[inline]
pub unsafe fn statx_cstr(
    dirfd: RawFd,
    path: &CStr,
    flags: StatAtFlags,
    mask: StatXMask,
) -> Result<Statx, Errno> {
    let mut buf = Statx::uninit();
    syscall!(
        Sysno::statx,
        dirfd,
        path.as_ptr(),
        flags.bits(),
        mask.bits(),
        buf.as_mut_ptr(),
    )?;
    Ok(buf.assume_init())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(all(not(feature = "linux_4_11"), not(target_arch = "loongarch64")))]
    #[test]
    #[allow(clippy::unnecessary_cast)]
    fn stat64_dev_null() {
        linux_syscalls::init();

        let c_stat = crate::tests::retry(crate::tests::c_stat);
        assert!(c_stat.is_ok());
        let c_stat = c_stat.unwrap();

        let stat = crate::tests::retry(|| unsafe {
            fstatat(
                crate::CURRENT_DIRECTORY,
                crate::tests::dev_null(),
                StatAtFlags::empty(),
            )
        });
        assert!(stat.is_ok());
        let stat = stat.unwrap();

        assert_eq!(stat.dev(), c_stat.st_dev);
        assert_eq!(stat.inode(), c_stat.st_ino as u64);
        assert_eq!(stat.nlink(), c_stat.st_nlink as u32);
        assert_eq!(
            stat.mode().as_u16() | stat.file_type().as_u16(),
            c_stat.st_mode as u16
        );
        assert_eq!(stat.uid(), c_stat.st_uid as u32);
        assert_eq!(stat.gid(), c_stat.st_gid as u32);
        assert_eq!(stat.rdev(), c_stat.st_rdev);
        assert_eq!(stat.size(), c_stat.st_size as i64);
        assert_eq!(stat.block_size(), c_stat.st_blksize as i32);
        assert_eq!(stat.blocks(), c_stat.st_blocks as i64);
        assert_eq!(stat.atime().secs, c_stat.st_atime as i64);
        assert_eq!(stat.atime().nsecs, c_stat.st_atime_nsec as u32);
        assert_eq!(stat.mtime().secs, c_stat.st_mtime as i64);
        assert_eq!(stat.mtime().nsecs, c_stat.st_mtime_nsec as u32);
        assert_eq!(stat.ctime().secs, c_stat.st_ctime as i64);
        assert_eq!(stat.ctime().nsecs, c_stat.st_ctime_nsec as u32);
    }

    #[test]
    #[allow(clippy::unnecessary_cast)]
    #[cfg_attr(target_arch = "s390x", ignore)]
    fn statx_dev_null() {
        linux_syscalls::init();

        let c_stat = crate::tests::retry(crate::tests::c_stat);
        assert!(c_stat.is_ok());
        let c_stat = c_stat.unwrap();

        let statx = crate::tests::retry(|| unsafe {
            statx(
                crate::CURRENT_DIRECTORY,
                crate::tests::dev_null(),
                StatAtFlags::empty(),
                StatXMask::empty(),
            )
        });
        assert!(statx.is_ok());
        let statx = statx.unwrap();

        assert_eq!(statx.dev(), c_stat.st_dev);
        assert_eq!(statx.inode(), c_stat.st_ino as u64);
        assert_eq!(statx.nlink(), c_stat.st_nlink as u32);
        assert_eq!(
            statx.mode().as_u16() | statx.file_type().as_u16(),
            c_stat.st_mode as u16
        );
        assert_eq!(statx.uid(), c_stat.st_uid as u32);
        assert_eq!(statx.gid(), c_stat.st_gid as u32);
        assert_eq!(statx.rdev(), c_stat.st_rdev);
        assert_eq!(statx.size(), c_stat.st_size as i64);
        assert_eq!(statx.block_size(), c_stat.st_blksize as i32);
        assert_eq!(statx.blocks(), c_stat.st_blocks as i64);
        assert_eq!(statx.atime().secs, c_stat.st_atime as i64);
        assert_eq!(statx.atime().nsecs, c_stat.st_atime_nsec as u32);
        assert_eq!(statx.mtime().secs, c_stat.st_mtime as i64);
        assert_eq!(statx.mtime().nsecs, c_stat.st_mtime_nsec as u32);
        assert_eq!(statx.ctime().secs, c_stat.st_ctime as i64);
        assert_eq!(statx.ctime().nsecs, c_stat.st_ctime_nsec as u32);
    }
}