openat/
metadata.rs

1use std::fs::Permissions;
2use std::os::unix::fs::PermissionsExt;
3
4use libc;
5
6use SimpleType;
7
8
9/// A file metadata
10///
11/// Because we can't freely create a `std::fs::Metadata` object we have to
12/// implement our own structure.
13pub struct Metadata {
14    stat: libc::stat,
15}
16
17impl Metadata {
18    /// Returns simplified type of the directory entry
19    pub fn simple_type(&self) -> SimpleType {
20        let typ = self.stat.st_mode & libc::S_IFMT;
21        match typ {
22            libc::S_IFREG => SimpleType::File,
23            libc::S_IFDIR => SimpleType::Dir,
24            libc::S_IFLNK => SimpleType::Symlink,
25            _ => SimpleType::Other,
26        }
27    }
28    /// Returns underlying stat structure
29    pub fn stat(&self) -> &libc::stat {
30        &self.stat
31    }
32    /// Returns `true` if the entry is a regular file
33    pub fn is_file(&self) -> bool {
34        self.simple_type() == SimpleType::File
35    }
36    /// Returns `true` if the entry is a directory
37    pub fn is_dir(&self) -> bool {
38        self.simple_type() == SimpleType::Dir
39    }
40    /// Returns permissions of the entry
41    pub fn permissions(&self) -> Permissions {
42        Permissions::from_mode(self.stat.st_mode as u32)
43    }
44    /// Returns file size
45    pub fn len(&self) -> u64 {
46        self.stat.st_size as u64
47    }
48}
49
50pub fn new(stat: libc::stat) -> Metadata {
51    Metadata { stat: stat }
52}
53
54#[cfg(test)]
55mod test {
56    use super::*;
57
58    #[test]
59    fn dir() {
60        let d = ::Dir::open(".").unwrap();
61        let m = d.metadata("src").unwrap();
62        assert_eq!(m.simple_type(), SimpleType::Dir);
63        assert!(m.is_dir());
64        assert!(!m.is_file());
65    }
66
67    #[test]
68    fn file() {
69        let d = ::Dir::open("src").unwrap();
70        let m = d.metadata("lib.rs").unwrap();
71        assert_eq!(m.simple_type(), SimpleType::File);
72        assert!(!m.is_dir());
73        assert!(m.is_file());
74    }
75}