forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

window.rs89 lines, 2.7 KiBHistoryRawDownload
1//! A sliding read window over a `Read + Seek`, so the demuxer can look at bytes
2//! around an offset without a syscall per transport packet.
3
4use std::io::{Read, Seek, SeekFrom};
5
6use ec_core::{Error, Result};
7
8/// Bytes fetched per read.
9const CHUNK: usize = 256 * 1024;
10/// Consumed bytes kept behind the cursor before the buffer is compacted.
11const KEEP: usize = 512 * 1024;
12
13pub(crate) struct Window<R> {
14 r: R,
15 /// File offset of `buf[0]`.
16 base: u64,
17 buf: Vec<u8>,
18 /// True once a read returned zero bytes at `base + buf.len()`.
19 at_eof: bool,
20}
21
22impl<R: Read + Seek> Window<R> {
23 pub(crate) fn new(r: R) -> Window<R> {
24 Window {
25 r,
26 base: 0,
27 buf: Vec::new(),
28 at_eof: false,
29 }
30 }
31
32 /// Total length of the file.
33 pub(crate) fn len(&mut self) -> Result<u64> {
34 let end = self.r.seek(SeekFrom::End(0)).map_err(Error::Io)?;
35 self.reposition()?;
36 Ok(end)
37 }
38
39 fn reposition(&mut self) -> Result<()> {
40 self.r
41 .seek(SeekFrom::Start(self.base + self.buf.len() as u64))
42 .map_err(Error::Io)?;
43 Ok(())
44 }
45
46 /// Up to `n` bytes at `off`; shorter only at the end of the file.
47 pub(crate) fn get(&mut self, off: u64, n: usize) -> Result<&[u8]> {
48 let inside = off >= self.base && off - self.base <= self.buf.len() as u64;
49 if !inside {
50 self.r.seek(SeekFrom::Start(off)).map_err(Error::Io)?;
51 self.base = off;
52 self.buf.clear();
53 self.at_eof = false;
54 }
55 let mut rel = (off - self.base) as usize;
56 if rel > KEEP {
57 self.buf.drain(..rel);
58 self.base = off;
59 rel = 0;
60 }
61 while self.buf.len() < rel + n && !self.at_eof {
62 let old = self.buf.len();
63 self.buf.resize(old + CHUNK.max(n), 0);
64 let mut filled = old;
65 loop {
66 match self.r.read(&mut self.buf[filled..]) {
67 Ok(0) => {
68 self.at_eof = true;
69 break;
70 }
71 Ok(k) => {
72 filled += k;
73 if filled >= old + CHUNK.min(self.buf.len() - old) {
74 break;
75 }
76 }
77 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
78 Err(e) => {
79 self.buf.truncate(old);
80 return Err(Error::Io(e));
81 }
82 }
83 }
84 self.buf.truncate(filled);
85 }
86 let end = (rel + n).min(self.buf.len());
87 Ok(&self.buf[rel.min(end)..end])
88 }
89}