Skip to main content

capsec_std/
file.rs

1//! Restricted file handles that enforce capability boundaries.
2//!
3//! Unlike `std::fs::File` which implements both `Read` and `Write`,
4//! these wrappers only expose the I/O trait matching the permission
5//! used to obtain them.
6//!
7//! - [`ReadFile`] — returned by [`open()`](crate::fs::open), implements `Read` + `Seek`
8//! - [`WriteFile`] — returned by [`create()`](crate::fs::create), implements `Write` + `Seek`
9
10use std::fs::File;
11use std::io::{self, Read, Seek, Write};
12
13/// A file handle that only supports reading.
14///
15/// Returned by [`capsec::fs::open()`](crate::fs::open). Implements `Read`
16/// and `Seek`, but NOT `Write`.
17///
18/// Wraps a `std::fs::File` internally. Zero overhead beyond the File itself.
19pub struct ReadFile(File);
20
21impl ReadFile {
22    pub(crate) fn new(file: File) -> Self {
23        Self(file)
24    }
25}
26
27impl Read for ReadFile {
28    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
29        self.0.read(buf)
30    }
31}
32
33impl Seek for ReadFile {
34    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
35        self.0.seek(pos)
36    }
37}
38
39/// A file handle that only supports writing.
40///
41/// Returned by [`capsec::fs::create()`](crate::fs::create). Implements `Write`
42/// and `Seek`, but NOT `Read`.
43///
44/// Wraps a `std::fs::File` internally. Zero overhead beyond the File itself.
45pub struct WriteFile(File);
46
47impl WriteFile {
48    pub(crate) fn new(file: File) -> Self {
49        Self(file)
50    }
51}
52
53impl Write for WriteFile {
54    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
55        self.0.write(buf)
56    }
57
58    fn flush(&mut self) -> io::Result<()> {
59        self.0.flush()
60    }
61}
62
63impl Seek for WriteFile {
64    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
65        self.0.seek(pos)
66    }
67}