positioned_io_preview/
vec.rs

1use std::cmp::min;
2use std::io;
3
4use super::{ReadAt, WriteAt, Size};
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(io::ErrorKind::InvalidInput, "vector size too big"));
17        }
18        let pos = pos as usize;
19
20        // Resize the vector so pos <= self.len().
21        if pos >= self.len() {
22            self.resize(pos as usize, 0);
23        }
24
25        // Copy anything that fits into existing space.
26        let avail = min(self.len() - pos, buf.len());
27        if avail > 0 {
28            self[pos..(pos + avail)].copy_from_slice(&buf[..avail]);
29        }
30
31        // Extend with anything leftover.
32        if avail < buf.len() {
33            self.extend_from_slice(&buf[avail..]);
34        }
35
36        Ok(buf.len())
37    }
38
39    fn flush(&mut self) -> io::Result<()> {
40        Ok(())
41    }
42}
43
44impl Size for Vec<u8> {
45    fn size(&self) -> io::Result<Option<u64>> {
46        Ok(Some(self.len() as u64))
47    }
48}