1use crate::file::{FileMetadata, FileType};
2use alloc::sync::Arc;
3use spin::Mutex;
4
5pub mod permissions {
6 pub const S_IRUSR: u32 = 0o400;
7 pub const S_IWUSR: u32 = 0o200;
8 pub const S_IXUSR: u32 = 0o100;
9 pub const S_IRGRP: u32 = 0o040;
10 pub const S_IWGRP: u32 = 0o020;
11 pub const S_IXGRP: u32 = 0o010;
12 pub const S_IROTH: u32 = 0o004;
13 pub const S_IWOTH: u32 = 0o002;
14 pub const S_IXOTH: u32 = 0o001;
15 pub const S_DEFAULT_FILE: u32 = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
16 pub const S_DEFAULT_DIR: u32 = 0o755;
17}
18
19pub trait Inode: Send + Sync {
20 fn ino(&self) -> usize;
21 fn file_type(&self) -> FileType;
22 fn size(&self) -> usize;
23 fn mode(&self) -> u32;
24}
25
26pub type InodeHandle = Arc<Mutex<dyn Inode>>;
27
28#[derive(Clone)]
29pub struct MemInode {
30 ino: usize,
31 file_type: FileType,
32 mode: u32,
33 size: usize,
34 created: u64,
35 modified: u64,
36 nlinks: usize,
37}
38
39impl MemInode {
40 pub fn new(ino: usize, file_type: FileType, mode: u32) -> Self {
41 Self {
42 ino,
43 file_type,
44 mode,
45 size: 0,
46 created: 0,
47 modified: 0,
48 nlinks: 1,
49 }
50 }
51
52 pub fn new_file(ino: usize) -> Self {
53 Self::new(ino, FileType::RegularFile, permissions::S_DEFAULT_FILE)
54 }
55
56 pub fn new_directory(ino: usize) -> Self {
57 Self::new(ino, FileType::Directory, permissions::S_DEFAULT_DIR)
58 }
59
60 pub fn set_size(&mut self, size: usize) {
61 self.size = size;
62 self.modified = self.modified.saturating_add(1);
63 }
64
65 pub fn inc_nlinks(&mut self) {
66 self.nlinks += 1;
67 }
68
69 pub fn dec_nlinks(&mut self) {
70 self.nlinks = self.nlinks.saturating_sub(1);
71 }
72
73 pub fn nlinks(&self) -> usize {
74 self.nlinks
75 }
76
77 pub fn can_delete(&self) -> bool {
78 self.nlinks == 0
79 }
80
81 pub fn to_metadata(&self) -> FileMetadata {
82 FileMetadata {
83 file_type: self.file_type,
84 size: self.size,
85 mode: self.mode,
86 created: self.created,
87 modified: self.modified,
88 }
89 }
90
91 pub fn is_readable(&self) -> bool {
92 (self.mode & permissions::S_IRUSR) != 0
93 }
94
95 pub fn is_writable(&self) -> bool {
96 (self.mode & permissions::S_IWUSR) != 0
97 }
98
99 pub fn is_executable(&self) -> bool {
100 (self.mode & permissions::S_IXUSR) != 0
101 }
102}
103
104impl Inode for MemInode {
105 fn ino(&self) -> usize {
106 self.ino
107 }
108
109 fn file_type(&self) -> FileType {
110 self.file_type
111 }
112
113 fn size(&self) -> usize {
114 self.size
115 }
116
117 fn mode(&self) -> u32 {
118 self.mode
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::*;
125
126 #[test]
127 fn mem_inode_tracks_metadata_and_links() {
128 let mut inode = MemInode::new_file(7);
129 inode.set_size(128);
130 inode.inc_nlinks();
131 assert_eq!(inode.ino(), 7);
132 assert_eq!(inode.size(), 128);
133 assert_eq!(inode.nlinks(), 2);
134 inode.dec_nlinks();
135 inode.dec_nlinks();
136 assert!(inode.can_delete());
137 assert!(inode.is_readable());
138 }
139}