positioned_io2/
vec.rs

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