positioned_io/
vec.rs

1use std::{cmp::min, io};
2
3use super::{ReadAt, Size, WriteAt};
4
5impl ReadAt for Vec<u8> {
6    fn read_at(&self, pos: u64, buf: &mut [u8]) -> io::Result<usize> {
7        self.as_slice().read_at(pos, buf)
8    }
9}
10
11impl WriteAt for Vec<u8> {
12    fn write_at(&mut self, pos: u64, buf: &[u8]) -> io::Result<usize> {
13        // Ensure no overflow.
14        if pos > (usize::max_value() as u64) {
15            return Err(io::Error::new(
16                io::ErrorKind::InvalidInput,
17                "vector size too big",
18            ));
19        }
20        let pos = pos as usize;
21
22        // Resize the vector so pos <= self.len().
23        if pos >= self.len() {
24            self.resize(pos as usize, 0);
25        }
26
27        // Copy anything that fits into existing space.
28        let avail = min(self.len() - pos, buf.len());
29        if avail > 0 {
30            self[pos..(pos + avail)].copy_from_slice(&buf[..avail]);
31        }
32
33        // Extend with anything leftover.
34        if avail < buf.len() {
35            self.extend_from_slice(&buf[avail..]);
36        }
37
38        Ok(buf.len())
39    }
40
41    fn flush(&mut self) -> io::Result<()> {
42        Ok(())
43    }
44}
45
46impl Size for Vec<u8> {
47    fn size(&self) -> io::Result<Option<u64>> {
48        Ok(Some(self.len() as u64))
49    }
50}