wasm_vfs/
process.rs

1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3use std::io::{Read, Write, Seek, SeekFrom};
4use std::path::PathBuf;
5use crate::filesystem::*;
6
7pub struct Process {
8    open_files: HashMap<FileDescriptor, OpenFile>,
9    fds: FileDescriptor,
10}
11
12impl Process {
13    pub fn new() -> Self {
14        Self {
15            open_files: HashMap::new(),
16            fds: 0,
17        }
18    }
19
20    pub fn open(&mut self, fs: &mut FileSystem, inode: Inode) -> Result<FileDescriptor, ()> {
21        for (&fd, open_file) in self.open_files.iter() {
22            if open_file.file.inode == inode {
23                // File is already open, return the existing FileDescriptor
24                return Ok(fd);
25            }
26        }
27
28        // If the file is not open, check if it exists in the filesystem
29        if let Some(file) = fs.files.get(&inode) {
30            let fd = self.fds;
31            self.open_files.insert(
32                fd,
33                OpenFile {
34                    file: Arc::clone(file),
35                    position: 0,
36                },
37            );
38            self.fds += 1;
39            return Ok(fd);
40        }
41
42        // If the inode is not provided or the file doesn't exist, create a new file
43        let new_inode = fs.create_file(vec![]);
44        let new_file = fs.files.get(&new_inode).ok_or(())?;
45        let new_fd = self.fds;
46        self.open_files.insert(
47            new_fd,
48            OpenFile {
49                file: Arc::clone(new_file),
50                position: 0,
51            },
52        );
53        self.fds += 1;
54        Ok(new_fd)
55}
56
57
58    pub fn read(&mut self, fd: FileDescriptor, buf: &mut [u8]) -> Result<usize, ()> {
59        let open_file = self.open_files.get_mut(&fd).ok_or(())?;
60        open_file.read(buf).map_err(|_| ())
61    }
62
63    pub fn write(&mut self, fd: FileDescriptor, buf: &[u8]) -> Result<usize, ()> {
64       let open_file = self.open_files.get_mut(&fd).ok_or(())?;
65       open_file.write(buf).map_err(|_| ())
66    }
67
68    pub fn close(&mut self, fd: FileDescriptor) -> Result<i32, i32> {
69        if self.open_files.remove(&fd).is_some() {
70            Ok(0)
71        } else {
72            Err(-1)
73        }
74    }
75}
76