lethe_gadget_fat/
block_io.rs

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use alloc::{vec, vec::Vec};

use layout::{io::SeekFrom, ApplyLayout, Read, Seek, Write, IO};

use crate::{
    filesystem::{FSError, FileSystem},
    schema::FATEntry,
};

pub struct BlockIO<'a, S> {
    fs: &'a mut FileSystem<S>,
    block_size: u64,

    blocks: Vec<u64>,

    cur_block_idx: u64,
    cur_offset: u64,

    fixed_size: bool,
}

impl<'a, S: Read + Write + Seek + IO> BlockIO<'a, S> {
    pub fn from_block(
        fs: &'a mut FileSystem<S>,
        start_block: u64,
        fixed_size: bool,
    ) -> Result<Self, FSError<S::Error>> {
        let block_size = fs.frame()?.super_block()?.block_size()? as u64;

        let mut this = Self {
            fs,
            block_size,

            blocks: vec![start_block],

            cur_block_idx: 0,
            cur_offset: 0,

            fixed_size,
        };

        this.seek(SeekFrom::Start(0))?;

        Ok(this)
    }

    pub fn create(
        fs: &'a mut FileSystem<S>,
        fixed_size: Option<u64>,
    ) -> Result<Self, FSError<S::Error>> {
        let block_size = fs.frame()?.super_block()?.block_size()? as u64;
        let head = fs.alloc_block()?;
        let mut this = Self {
            fs,
            block_size,
            blocks: vec![head],
            cur_block_idx: 0,
            cur_offset: 0,
            fixed_size: fixed_size.is_some(),
        };

        if let Some(len) = fixed_size {
            this.fill_blocks_to(Some(len / this.block_size + 1), true)?;
        }

        this.seek(SeekFrom::Start(0))?;
        Ok(this)
    }

    pub fn start_block(&self) -> u64 {
        self.blocks[0]
    }

    pub fn align_stream(&mut self) -> Result<(), <Self as IO>::Error> {
        self.seek(SeekFrom::Start(self.cur_offset)).map(|_| ())
    }
}

impl<'a, S: IO> BlockIO<'a, S> {
    pub fn as_frame<L: ApplyLayout<'a, Self>>(
        &'a mut self,
    ) -> Result<L::Frame, <Self as IO>::Error> {
        L::apply_layout(self, 0)
    }
}

impl<'a, S: Read + Write + Seek + IO> BlockIO<'a, S> {
    // warning: this ruins the current position in the stream
    fn fill_blocks_to(
        &mut self,
        block_count: Option<u64>,
        expand: bool,
    ) -> Result<(), FSError<S::Error>> {
        let max = block_count.unwrap_or(u64::max_value());

        let mut cur_block = *self.blocks.last().unwrap();
        while max > self.blocks.len() as u64 {
            match self.fs.frame()?.fat()?.get(cur_block)?.unwrap() {
                Some(next_block) => {
                    self.blocks.push(next_block);
                    cur_block = next_block;
                }
                None if block_count.is_none() || !expand => break,
                None => {
                    let next_block = self.fs.alloc_block()?;
                    self.blocks.push(next_block);

                    self.fs
                        .frame()?
                        .fat()?
                        .set(cur_block, FATEntry::Block(next_block))?;

                    cur_block = next_block;
                }
            }
        }

        Ok(())
    }
}

impl<'a, S: IO> IO for BlockIO<'a, S> {
    type Error = FSError<S::Error>;
}

impl<'a, S: Read + Write + Seek + IO> Seek for BlockIO<'a, S> {
    fn seek(&mut self, pos: SeekFrom) -> Result<u64, Self::Error> {
        let (target_idx, next_offset) = match pos {
            SeekFrom::Start(off) => {
                let target_block = off / self.block_size;
                self.fill_blocks_to(Some(target_block + 1), false)?;

                (target_block, off)
            }
            SeekFrom::End(off) => {
                let target_block = self.blocks.len() as i64 + off / self.block_size as i64;

                if target_block < 0 {
                    return Err(FSError::OutOfBounds);
                }

                self.fill_blocks_to(None, false)?;

                (
                    target_block as u64,
                    (self.block_size as i64 * self.blocks.len() as i64 + off) as u64,
                )
            }
            SeekFrom::Current(off) => {
                let target_block = self.cur_block_idx as i64 + off / self.block_size as i64;

                if target_block < 0 {
                    return Err(FSError::OutOfBounds);
                }

                self.fill_blocks_to(Some(target_block as u64 + 1), false)?;

                (target_block as u64, (self.cur_offset as i64 + off) as u64)
            }
        };

        self.cur_offset = next_offset;

        if target_idx == self.blocks.len() as u64 && next_offset % self.block_size == 0 {
            self.cur_block_idx = target_idx;

            return Ok(target_idx * self.block_size);
        }

        if let Some(&target) = self.blocks.get(target_idx as usize) {
            self.cur_block_idx = target_idx;

            self.fs.disk.seek(SeekFrom::Start(
                target * self.block_size + next_offset % self.block_size,
            ))?;

            Ok(self.cur_offset)
        } else {
            Err(FSError::OutOfBounds)
        }
    }

    fn stream_len(&mut self) -> Result<u64, Self::Error> {
        self.fill_blocks_to(None, false)?;
        self.align_stream()?;

        Ok(self.blocks.len() as u64 * self.block_size)
    }

    fn stream_position(&mut self) -> Result<u64, Self::Error> {
        Ok(self.cur_offset)
    }
}

impl<'a, S: Read + Write + Seek + IO> Read for BlockIO<'a, S> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        // todo: lol no eof on growable things
        if self.cur_block_idx == self.blocks.len() as u64 {
            self.fill_blocks_to(Some(self.blocks.len() as u64 + 1), !self.fixed_size)?;
            self.align_stream()?;

            if self.fixed_size && self.cur_block_idx == self.blocks.len() as u64 {
                return Ok(0);
            }
        }

        let trunc = buf
            .len()
            .min((self.block_size - self.cur_offset % self.block_size) as usize);
        let cropped_buf = &mut buf[..trunc];
        let read = self.fs.disk.read(cropped_buf)?;

        self.cur_offset += read as u64;
        if self.cur_offset % self.block_size == 0 {
            self.cur_block_idx += 1;
        }

        Ok(read)
    }

    // modified from std::io::Read's provided definition for the corollary function
    // TODO: ignore interrupted reads by using underlying IO's read_exact definition
    fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<(), Self::Error> {
        while !buf.is_empty() {
            match self.read(buf) {
                Ok(0) => break,
                Ok(n) => {
                    let tmp = buf;
                    buf = &mut tmp[n..];
                }
                Err(e) => return Err(e),
            }
        }

        if buf.is_empty() {
            Ok(())
        } else {
            Err(FSError::UnexpectedEof)
        }
    }
}

impl<'a, S: Read + Write + Seek + IO> Write for BlockIO<'a, S> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        if self.cur_block_idx == self.blocks.len() as u64 {
            self.fill_blocks_to(Some(self.blocks.len() as u64 + 1), !self.fixed_size)?;
            self.align_stream()?;

            if self.fixed_size && self.cur_block_idx == self.blocks.len() as u64 {
                return Err(FSError::OutOfBounds);
            }
        }

        let trunc = buf
            .len()
            .min((self.block_size - self.cur_offset % self.block_size) as usize);
        let cropped_buf = &buf[..trunc];

        let written = self.fs.disk.write(cropped_buf)?;

        self.cur_offset += written as u64;
        if self.cur_offset % self.block_size == 0 {
            self.cur_block_idx += 1;
        }

        Ok(written)
    }

    // modified from std::io::Writes's provided definition for the corollary function
    // TODO: ignore interrupted writes by using underlying IO's write_all definition
    fn write_all(&mut self, mut buf: &[u8]) -> Result<(), Self::Error> {
        while !buf.is_empty() {
            match self.write(buf) {
                Ok(0) => {
                    return Err(FSError::WriteZero);
                }
                Ok(n) => buf = &buf[n..],
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        self.fs.disk.flush().map_err(FSError::IO)
    }
}