monoio/fs/
file_type.rs

1use std::{fmt::Debug, os::unix::fs::FileTypeExt};
2
3use libc::mode_t;
4
5/// A structure representing a type of file with accessors for each file type.
6#[derive(PartialEq, Eq, Clone, Copy, Hash)]
7pub struct FileType {
8    pub(crate) mode: mode_t,
9}
10
11#[cfg(unix)]
12impl FileType {
13    /// Returns `true` if this file type is a directory.
14    pub fn is_dir(&self) -> bool {
15        self.is(libc::S_IFDIR)
16    }
17
18    /// Returns `true` if this file type is a regular file.
19    pub fn is_file(&self) -> bool {
20        self.is(libc::S_IFREG)
21    }
22
23    /// Returns `true` if this file type is a symbolic link.
24    pub fn is_symlink(&self) -> bool {
25        self.is(libc::S_IFLNK)
26    }
27
28    pub(crate) fn is(&self, mode: mode_t) -> bool {
29        self.masked() == mode
30    }
31
32    fn masked(&self) -> mode_t {
33        self.mode & libc::S_IFMT
34    }
35}
36
37impl FileTypeExt for FileType {
38    fn is_block_device(&self) -> bool {
39        self.is(libc::S_IFBLK)
40    }
41
42    fn is_char_device(&self) -> bool {
43        self.is(libc::S_IFCHR)
44    }
45
46    fn is_fifo(&self) -> bool {
47        self.is(libc::S_IFIFO)
48    }
49
50    fn is_socket(&self) -> bool {
51        self.is(libc::S_IFSOCK)
52    }
53}
54
55impl Debug for FileType {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("FileType")
58            .field("is_file", &self.is_file())
59            .field("is_dir", &self.is_dir())
60            .field("is_symlink", &self.is_symlink())
61            .finish_non_exhaustive()
62    }
63}