Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@paulsmith
Last active December 7, 2022 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulsmith/23bb21b1878814e0a51191e7a1acbc8f to your computer and use it in GitHub Desktop.
Save paulsmith/23bb21b1878814e0a51191e7a1acbc8f to your computer and use it in GitHub Desktop.
enum Kind {
File,
Directory,
}
struct Entry {
name: String,
kind: Kind,
size: usize,
parent: Option<usize>,
children: Option<Vec<usize>>,
}
impl Entry {
fn add_entry(&mut self, entry: usize) {
match &mut self.children {
None => {
self.children = Some(vec![entry]);
},
Some(ref mut children) => children.push(entry),
}
}
}
struct Filesystem {
entries: Vec<Entry>,
}
impl Filesystem {
fn new_entry(&mut self, name: &str, kind: Kind, size: usize) -> usize {
let handle = self.entries.len();
self.entries.push(Entry { name: name.to_string(), kind, size, parent: None, children: None });
handle
}
}
fn main() {
let mut fs = Filesystem { entries: vec![] };
let root_handle = fs.new_entry("/", Kind::Directory, 0);
let file_a = fs.new_entry("file.txt", Kind::File, 42);
fs.entries[root_handle].add_entry(file_a);
let dir_b = fs.new_entry("b", Kind::Directory, 0);
fs.entries[dir_b].parent = Some(root_handle);
fs.entries[root_handle].add_entry(dir_b);
let file_b = fs.new_entry("another.txt", Kind::File, 100);
fs.entries[dir_b].add_entry(file_b);
let mut stack = vec![root_handle];
while stack.len() > 0 {
let handle = stack.pop().unwrap();
let entry = &fs.entries[handle];
match entry.kind {
Kind::File => println!("FILE: {} ({})", entry.name, entry.size),
Kind::Directory => {
println!("DIR: {}", entry.name);
if let Some(children) = &entry.children {
for handle in children {
stack.push(*handle);
}
}
},
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment