ext4_view/
metadata.rs

1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::file_type::FileType;
10use crate::inode::InodeMode;
11
12/// Metadata information about a file.
13#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
14pub struct Metadata {
15    /// Size in bytes of the file data.
16    pub(crate) size_in_bytes: u64,
17
18    /// Raw permissions and file type.
19    pub(crate) mode: InodeMode,
20
21    /// File type parsed from the `mode` bitfield.
22    pub(crate) file_type: FileType,
23
24    /// Owner user ID.
25    pub(crate) uid: u32,
26
27    /// Owner group ID.
28    pub(crate) gid: u32,
29}
30
31impl Metadata {
32    /// Get the file type.
33    #[must_use]
34    pub fn file_type(&self) -> FileType {
35        self.file_type
36    }
37
38    /// Return true if this metadata is for a directory.
39    #[must_use]
40    pub fn is_dir(&self) -> bool {
41        self.file_type.is_dir()
42    }
43
44    /// Return true if this metadata is for a symlink.
45    #[must_use]
46    pub fn is_symlink(&self) -> bool {
47        self.file_type.is_symlink()
48    }
49
50    /// Get the size in bytes of the file.
51    #[allow(clippy::len_without_is_empty)]
52    #[must_use]
53    pub fn len(&self) -> u64 {
54        self.size_in_bytes
55    }
56
57    /// Get the file's UNIX permission bits.
58    ///
59    /// Diagram of the returned value's bits:
60    ///
61    /// ```text
62    ///       top four bits are always zero
63    ///       │   
64    ///       │   set uid, set gid, sticky bit
65    ///       │   │  
66    ///       │   │  owner read/write/execute
67    ///       │   │  │  
68    ///       │   │  │  group read/write/execute
69    ///       │   │  │  │  
70    ///       │   │  │  │  other read/write/execute
71    ///       │   │  │  │  │
72    /// (msb) 0000xxxuuugggooo (lsb)
73    /// ```
74    ///
75    /// See `st_mode` in [inode(7)][inode] for more details.
76    ///
77    /// [inode]: https://www.man7.org/linux/man-pages/man7/inode.7.html
78    #[must_use]
79    pub fn mode(&self) -> u16 {
80        self.mode.bits() & 0o7777
81    }
82
83    /// Owner user ID.
84    #[must_use]
85    pub fn uid(&self) -> u32 {
86        self.uid
87    }
88
89    /// Owner group ID.
90    #[must_use]
91    pub fn gid(&self) -> u32 {
92        self.gid
93    }
94}