1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//! FAT filesystem implementation of FileOperations
use crate::LibUserResult;
use super::error::from_driver;
use storage_device::StorageDevice;
use crate::interface::filesystem::*;

use libfat::directory::File;

use spin::Mutex;
use alloc::sync::Arc;
use alloc::boxed::Box;

use sunrise_libuser::error::{Error, FileSystemError};

use core::fmt;

/// A libfat file interface implementing ``FileOperations``.
pub struct FileInterface {
    /// libfat filesystem interface.
    inner_fs: Arc<Mutex<libfat::filesystem::FatFileSystem<Box<dyn StorageDevice<Error = Error> + Send>>>>,

    /// The libfat's directory entry of this file.
    file_inner: File,

    /// File mode flags.
    mode: FileModeFlags
}

impl fmt::Debug for FileInterface {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("FileInterface")
           .field("file_info", &self.file_inner.file_info)
           .field("mode", &self.mode)
           .finish()
    }
}


impl FileInterface {
    /// Create a new FileInterface.
    pub fn new(inner_fs: Arc<Mutex<libfat::filesystem::FatFileSystem<Box<dyn StorageDevice<Error = Error> + Send>>>>, file_inner: File, mode: FileModeFlags) -> Self {
        FileInterface { inner_fs, file_inner, mode }
    }
}

impl FileOperations for FileInterface {
    /// Read the content of a file at a given ``offset`` in ``buf``.
    fn read(&mut self, offset: u64, buf: &mut [u8]) -> LibUserResult<u64> {
        if (self.mode & FileModeFlags::READABLE) != FileModeFlags::READABLE {
            return Err(FileSystemError::AccessDenied.into());
        }

        self.file_inner
            .read(&self.inner_fs.lock(), offset, buf)
            .map_err(from_driver)
    }

    fn write(&mut self, offset: u64, buf: &[u8]) -> LibUserResult<()> {
        if (self.mode & FileModeFlags::WRITABLE) != FileModeFlags::WRITABLE {
            return Err(FileSystemError::AccessDenied.into());
        }

        self.file_inner
            .write(
                &self.inner_fs.lock(),
                offset,
                buf,
                (self.mode & FileModeFlags::APPENDABLE) == FileModeFlags::APPENDABLE,
            )
            .map_err(from_driver)
    }

    fn flush(&mut self) -> LibUserResult<()> {
        // NOP
        Ok(())
    }

    fn set_len(&mut self, size: u64) -> LibUserResult<()> {
        self.file_inner
            .set_len(&self.inner_fs.lock(), size)
            .map_err(from_driver)
    }

    fn get_len(&mut self) -> LibUserResult<u64> {
        Ok(u64::from(self.file_inner.file_info.file_size))
    }
}