1use crate::{Error, ErrorKind, Result};
2use std::cell::RefCell;
3use std::collections::{HashMap, VecDeque};
4use std::future::Future;
5use std::pin::Pin;
6
7pub type IoFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
9
10pub trait ByteSource {
12 fn len(&self) -> Option<u64>;
13
14 fn is_empty(&self) -> Option<bool> {
15 self.len().map(|length| length == 0)
16 }
17
18 fn read_at<'a>(&'a self, offset: u64, destination: &'a mut [u8]) -> IoFuture<'a, usize>;
19}
20
21pub trait ByteSink {
32 fn position(&self) -> u64;
33 fn is_seekable(&self) -> bool {
34 true
35 }
36 fn write<'a>(&'a mut self, bytes: &'a [u8]) -> IoFuture<'a, ()>;
37 fn seek<'a>(&'a mut self, position: u64) -> IoFuture<'a, ()>;
38 fn flush<'a>(&'a mut self) -> IoFuture<'a, ()> {
39 Box::pin(async { Ok(()) })
40 }
41}
42
43#[derive(Clone, Debug, Default, Eq, PartialEq)]
45pub struct MemorySource {
46 bytes: Vec<u8>,
47}
48
49impl MemorySource {
50 pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
51 Self {
52 bytes: bytes.into(),
53 }
54 }
55
56 pub fn as_slice(&self) -> &[u8] {
57 &self.bytes
58 }
59}
60
61impl ByteSource for MemorySource {
62 fn len(&self) -> Option<u64> {
63 u64::try_from(self.bytes.len()).ok()
64 }
65
66 fn read_at<'a>(&'a self, offset: u64, destination: &'a mut [u8]) -> IoFuture<'a, usize> {
67 Box::pin(async move {
68 let offset = usize::try_from(offset)
69 .map_err(|_| Error::new(ErrorKind::InvalidInput, "read offset is too large"))?;
70 if offset > self.bytes.len() {
71 return Err(Error::new(
72 ErrorKind::InvalidInput,
73 "read offset is beyond the source",
74 ));
75 }
76 let length = destination.len().min(self.bytes.len() - offset);
77 destination[..length].copy_from_slice(&self.bytes[offset..offset + length]);
78 Ok(length)
79 })
80 }
81}
82
83#[cfg(any(unix, windows))]
90#[derive(Clone, Debug)]
91pub struct FileSource {
92 file: std::sync::Arc<std::fs::File>,
93 length: u64,
94}
95
96#[cfg(any(unix, windows))]
97impl FileSource {
98 pub fn open(path: impl AsRef<std::path::Path>) -> Result<Self> {
99 let path = path.as_ref();
100 let file = std::fs::File::open(path).map_err(|error| {
101 Error::new(
102 ErrorKind::Io,
103 format!("cannot open {}: {error}", path.display()),
104 )
105 })?;
106 Self::from_file(file)
107 }
108
109 pub fn from_file(file: std::fs::File) -> Result<Self> {
110 let length = file
111 .metadata()
112 .map_err(|error| Error::new(ErrorKind::Io, format!("cannot read file size: {error}")))?
113 .len();
114 Ok(Self {
115 file: std::sync::Arc::new(file),
116 length,
117 })
118 }
119
120 fn read_some(&self, offset: u64, destination: &mut [u8]) -> std::io::Result<usize> {
121 #[cfg(unix)]
122 {
123 std::os::unix::fs::FileExt::read_at(&*self.file, destination, offset)
124 }
125 #[cfg(windows)]
126 {
127 std::os::windows::fs::FileExt::seek_read(&*self.file, destination, offset)
128 }
129 }
130}
131
132#[cfg(any(unix, windows))]
133impl ByteSource for FileSource {
134 fn len(&self) -> Option<u64> {
135 Some(self.length)
136 }
137
138 fn read_at<'a>(&'a self, offset: u64, destination: &'a mut [u8]) -> IoFuture<'a, usize> {
139 let result = if offset > self.length {
140 Err(Error::new(
141 ErrorKind::InvalidInput,
142 "read offset is beyond the source",
143 ))
144 } else {
145 let mut filled = 0;
148 loop {
149 if filled == destination.len() {
150 break Ok(filled);
151 }
152 match self.read_some(offset + filled as u64, &mut destination[filled..]) {
153 Ok(0) => break Ok(filled),
154 Ok(read) => filled += read,
155 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
156 Err(error) => {
157 break Err(Error::new(
158 ErrorKind::Io,
159 format!("cannot read file: {error}"),
160 ));
161 }
162 }
163 }
164 };
165 Box::pin(async move { result })
166 }
167}
168
169#[derive(Clone, Debug, Default, Eq, PartialEq)]
171pub struct MemorySink {
172 bytes: Vec<u8>,
173 position: u64,
174}
175
176impl MemorySink {
177 pub fn new() -> Self {
178 Self::default()
179 }
180
181 pub fn into_inner(self) -> Vec<u8> {
182 self.bytes
183 }
184
185 pub fn as_slice(&self) -> &[u8] {
186 &self.bytes
187 }
188}
189
190impl ByteSink for MemorySink {
191 fn position(&self) -> u64 {
192 self.position
193 }
194
195 fn write<'a>(&'a mut self, bytes: &'a [u8]) -> IoFuture<'a, ()> {
196 Box::pin(async move {
197 let position = usize::try_from(self.position)
198 .map_err(|_| Error::new(ErrorKind::ResourceLimit, "sink position is too large"))?;
199 let end = position
200 .checked_add(bytes.len())
201 .ok_or_else(|| Error::new(ErrorKind::ResourceLimit, "sink allocation overflow"))?;
202 if end > self.bytes.len() {
203 self.bytes.resize(end, 0);
204 }
205 self.bytes[position..end].copy_from_slice(bytes);
206 self.position = u64::try_from(end).map_err(|_| {
207 Error::new(
208 ErrorKind::ResourceLimit,
209 "sink position cannot be represented",
210 )
211 })?;
212 Ok(())
213 })
214 }
215
216 fn seek<'a>(&'a mut self, position: u64) -> IoFuture<'a, ()> {
217 Box::pin(async move {
218 usize::try_from(position)
219 .map_err(|_| Error::new(ErrorKind::InvalidInput, "seek position is too large"))?;
220 self.position = position;
221 Ok(())
222 })
223 }
224}
225
226#[doc(hidden)]
230#[derive(Clone, Debug, Default, Eq, PartialEq)]
231pub struct NonSeekableSink {
232 bytes: Vec<u8>,
233}
234
235impl ByteSink for NonSeekableSink {
236 fn position(&self) -> u64 {
237 self.bytes.len() as u64
238 }
239
240 fn is_seekable(&self) -> bool {
241 false
242 }
243
244 fn write<'a>(&'a mut self, bytes: &'a [u8]) -> IoFuture<'a, ()> {
245 Box::pin(async move {
246 self.bytes.extend_from_slice(bytes);
247 Ok(())
248 })
249 }
250
251 fn seek<'a>(&'a mut self, _position: u64) -> IoFuture<'a, ()> {
252 Box::pin(async move {
253 Err(Error::new(
254 ErrorKind::Unsupported,
255 "this sink does not support seeking",
256 ))
257 })
258 }
259}
260
261pub struct CachingByteSource<S> {
276 inner: S,
277 page_size: u64,
278 budget_bytes: u64,
279 pages: RefCell<HashMap<u64, Vec<u8>>>,
280 lru: RefCell<VecDeque<u64>>,
281 resident_bytes: RefCell<u64>,
282}
283
284impl<S: ByteSource> CachingByteSource<S> {
285 pub fn new(inner: S, page_size: u64, budget_bytes: u64) -> Result<Self> {
289 if page_size == 0 || budget_bytes == 0 {
290 return Err(Error::new(
291 ErrorKind::InvalidInput,
292 "caching byte source requires a nonzero page size and budget",
293 ));
294 }
295 Ok(Self {
296 inner,
297 page_size,
298 budget_bytes,
299 pages: RefCell::new(HashMap::new()),
300 lru: RefCell::new(VecDeque::new()),
301 resident_bytes: RefCell::new(0),
302 })
303 }
304
305 pub fn into_inner(self) -> S {
306 self.inner
307 }
308
309 pub fn resident_bytes(&self) -> u64 {
311 *self.resident_bytes.borrow()
312 }
313
314 fn touch(&self, page: u64) {
315 let mut lru = self.lru.borrow_mut();
316 lru.retain(|candidate| *candidate != page);
317 lru.push_back(page);
318 }
319
320 fn evict_until_within_budget(&self) {
321 loop {
322 if *self.resident_bytes.borrow() <= self.budget_bytes {
323 return;
324 }
325 let Some(evicted) = self.lru.borrow_mut().pop_front() else {
326 return;
327 };
328 if let Some(bytes) = self.pages.borrow_mut().remove(&evicted) {
329 *self.resident_bytes.borrow_mut() -= bytes.len() as u64;
330 }
331 }
332 }
333
334 async fn fetch(&self, first: u64, pages: u64) -> Result<Vec<u8>> {
338 let length = usize::try_from(pages * self.page_size).map_err(|_| {
339 Error::new(
340 ErrorKind::ResourceLimit,
341 "caching byte source read is too large",
342 )
343 })?;
344 let mut bytes = vec![0_u8; length];
345 let read = self
346 .inner
347 .read_at(first * self.page_size, &mut bytes)
348 .await?;
349 bytes.truncate(read);
350 for (index, chunk) in bytes.chunks(self.page_size as usize).enumerate() {
351 let page = first + index as u64;
352 *self.resident_bytes.borrow_mut() += chunk.len() as u64;
353 if let Some(replaced) = self.pages.borrow_mut().insert(page, chunk.to_vec()) {
354 *self.resident_bytes.borrow_mut() -= replaced.len() as u64;
355 }
356 self.touch(page);
357 }
358 self.evict_until_within_budget();
359 Ok(bytes)
360 }
361}
362
363impl<S: ByteSource> ByteSource for CachingByteSource<S> {
364 fn len(&self) -> Option<u64> {
365 self.inner.len()
366 }
367
368 fn read_at<'a>(&'a self, offset: u64, destination: &'a mut [u8]) -> IoFuture<'a, usize> {
373 Box::pin(async move {
374 let mut produced = 0_usize;
375 while produced < destination.len() {
376 let position = offset + produced as u64;
377 let page_index = position / self.page_size;
378 let in_page_offset = (position - page_index * self.page_size) as usize;
379 let cached = self.pages.borrow().get(&page_index).cloned();
380 let (bytes, pages) = match cached {
381 Some(page) => {
382 self.touch(page_index);
383 (page, 1)
384 }
385 None => {
386 let last_page = (offset + destination.len() as u64 - 1) / self.page_size;
387 let mut run_end = page_index + 1;
388 while run_end <= last_page && !self.pages.borrow().contains_key(&run_end) {
389 run_end += 1;
390 }
391 let pages = run_end - page_index;
392 (self.fetch(page_index, pages).await?, pages)
393 }
394 };
395 if in_page_offset >= bytes.len() {
396 break;
397 }
398 let available = (bytes.len() - in_page_offset).min(destination.len() - produced);
399 destination[produced..produced + available]
400 .copy_from_slice(&bytes[in_page_offset..in_page_offset + available]);
401 produced += available;
402 if (bytes.len() as u64) < pages * self.page_size {
403 break;
405 }
406 }
407 Ok(produced)
408 })
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415 use std::task::{Context, Poll, Waker};
416
417 fn ready<T>(mut future: IoFuture<'_, T>) -> Result<T> {
418 let waker = Waker::noop();
419 let mut context = Context::from_waker(waker);
420 match future.as_mut().poll(&mut context) {
421 Poll::Ready(result) => result,
422 Poll::Pending => panic!("memory I/O unexpectedly returned a pending future"),
423 }
424 }
425
426 #[test]
427 fn memory_source_reads_partially_at_end_of_source() {
428 let source = MemorySource::new(b"abcdef".to_vec());
429 let mut destination = [0_u8; 4];
430 assert_eq!(ready(source.read_at(4, &mut destination)).unwrap(), 2);
431 assert_eq!(&destination[..2], b"ef");
432 }
433
434 #[test]
435 fn memory_source_rejects_offsets_beyond_end() {
436 let source = MemorySource::new(b"abc".to_vec());
437 let mut destination = [0_u8; 1];
438 let error = ready(source.read_at(4, &mut destination)).unwrap_err();
439 assert_eq!(error.kind(), ErrorKind::InvalidInput);
440 }
441
442 #[test]
443 fn memory_sink_seeks_overwrites_and_zero_fills() {
444 let mut sink = MemorySink::new();
445 ready(sink.write(b"abc")).unwrap();
446 ready(sink.seek(1)).unwrap();
447 ready(sink.write(b"Z")).unwrap();
448 ready(sink.seek(5)).unwrap();
449 ready(sink.write(b"!")).unwrap();
450 assert_eq!(sink.as_slice(), b"aZc\0\0!");
451 }
452
453 #[test]
454 fn non_seekable_sink_writes_but_rejects_seek() {
455 let mut sink = NonSeekableSink::default();
456 assert!(!sink.is_seekable());
457 ready(sink.write(b"abc")).unwrap();
458 assert_eq!(sink.bytes, b"abc");
459 let error = ready(sink.seek(0)).unwrap_err();
460 assert_eq!(error.kind(), ErrorKind::Unsupported);
461 }
462
463 struct CountingSource {
466 inner: MemorySource,
467 reads: std::cell::Cell<u64>,
468 requests: std::cell::Cell<u64>,
469 }
470
471 impl ByteSource for CountingSource {
472 fn len(&self) -> Option<u64> {
473 self.inner.len()
474 }
475
476 fn read_at<'a>(&'a self, offset: u64, destination: &'a mut [u8]) -> IoFuture<'a, usize> {
477 Box::pin(async move {
478 self.requests.set(self.requests.get() + 1);
479 let read = self.inner.read_at(offset, destination).await?;
480 self.reads.set(self.reads.get() + read as u64);
481 Ok(read)
482 })
483 }
484 }
485
486 fn large_source(bytes: u64) -> CountingSource {
487 CountingSource {
488 inner: MemorySource::new((0..bytes).map(|value| value as u8).collect::<Vec<u8>>()),
489 reads: std::cell::Cell::new(0),
490 requests: std::cell::Cell::new(0),
491 }
492 }
493
494 #[test]
498 fn caching_byte_source_fetches_a_run_of_uncached_pages_in_one_request() {
499 let cache = CachingByteSource::new(large_source(1000), 64, 1_000_000).unwrap();
500 let mut destination = [0_u8; 500];
501 assert_eq!(ready(cache.read_at(10, &mut destination)).unwrap(), 500);
502 assert_eq!(cache.inner.requests.get(), 1);
503 let expected: Vec<u8> = (10..510).map(|value| value as u8).collect();
504 assert_eq!(&destination[..], expected.as_slice());
505
506 let mut destination = [0_u8; 1000];
508 assert_eq!(ready(cache.read_at(0, &mut destination)).unwrap(), 1000);
509 assert_eq!(cache.inner.requests.get(), 2);
510 let expected: Vec<u8> = (0..1000).map(|value| value as u8).collect();
511 assert_eq!(&destination[..], expected.as_slice());
512 let mut destination = [0_u8; 1000];
513 assert_eq!(ready(cache.read_at(0, &mut destination)).unwrap(), 1000);
514 assert_eq!(cache.inner.requests.get(), 2);
515
516 let small = CachingByteSource::new(large_source(1000), 64, 128).unwrap();
518 let mut destination = [0_u8; 600];
519 assert_eq!(ready(small.read_at(100, &mut destination)).unwrap(), 600);
520 assert_eq!(small.inner.requests.get(), 1);
521 assert!(small.resident_bytes() <= 128);
522 let expected: Vec<u8> = (100..700).map(|value| value as u8).collect();
523 assert_eq!(&destination[..], expected.as_slice());
524 }
525
526 #[test]
527 fn caching_byte_source_reads_match_the_inner_source_across_page_boundaries() {
528 let cache = CachingByteSource::new(large_source(1000), 64, 1_000_000).unwrap();
529 let mut destination = [0_u8; 100];
530 assert_eq!(ready(cache.read_at(30, &mut destination)).unwrap(), 100);
531 let expected: Vec<u8> = (30..130).map(|value| value as u8).collect();
532 assert_eq!(&destination, expected.as_slice());
533 }
534
535 #[test]
536 fn caching_byte_source_answers_a_repeated_read_without_fetching_again() {
537 let cache = CachingByteSource::new(large_source(1000), 64, 1_000_000).unwrap();
538 let mut destination = [0_u8; 10];
539 ready(cache.read_at(0, &mut destination)).unwrap();
540 let reads_after_first = cache.inner.reads.get();
541 assert!(reads_after_first > 0);
542 ready(cache.read_at(0, &mut destination)).unwrap();
543 assert_eq!(
544 cache.inner.reads.get(),
545 reads_after_first,
546 "a repeated read fetched from the inner source again instead of the cache"
547 );
548 }
549
550 #[test]
554 fn caching_byte_source_stays_within_its_budget_while_scanning_a_large_source() {
555 let total = 1_000_000_u64;
556 let page_size = 4096_u64;
557 let budget = 64 * 1024_u64;
558 let cache = CachingByteSource::new(large_source(total), page_size, budget).unwrap();
559 let mut destination = [0_u8; 1024];
560 let mut offset = 0_u64;
561 while offset + destination.len() as u64 <= total {
562 ready(cache.read_at(offset, &mut destination)).unwrap();
563 assert!(
564 cache.resident_bytes() <= budget,
565 "resident bytes {} exceeded the budget {budget} at offset {offset}",
566 cache.resident_bytes()
567 );
568 offset += 97 * 1024;
571 }
572 }
573
574 #[test]
575 fn caching_byte_source_rejects_a_zero_page_size_or_budget() {
576 assert_eq!(
577 CachingByteSource::new(MemorySource::default(), 0, 1024)
578 .err()
579 .unwrap()
580 .kind(),
581 ErrorKind::InvalidInput
582 );
583 assert_eq!(
584 CachingByteSource::new(MemorySource::default(), 1024, 0)
585 .err()
586 .unwrap()
587 .kind(),
588 ErrorKind::InvalidInput
589 );
590 }
591}