Skip to main content

virtual_file_transfer/
file_source.rs

1use crate::source_reader::SourceReader;
2use std::io;
3
4/// A provider of virtual file contents.
5///
6/// Each call to [`FileSource::open`] must create a fresh,
7/// independent reader positioned at the beginning of the
8/// file.
9///
10/// A receiving application may request the contents of
11/// the same virtual file multiple times or concurrently.
12///
13/// Implementations must be safe to share across threads.
14pub trait FileSource: Send + Sync {
15    /// Opens a new reader for this file's contents.
16    ///
17    /// The returned reader must not depend on the position of readers returned
18    /// by earlier calls.
19    ///
20    /// # Errors
21    ///
22    /// Returns an I/O error if the contents cannot be opened or prepared.
23    fn open(&self) -> io::Result<SourceReader>;
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29    use std::io::Read;
30
31    struct MemorySource {
32        data: Vec<u8>,
33    }
34
35    impl FileSource for MemorySource {
36        fn open(&self) -> io::Result<SourceReader> {
37            Ok(SourceReader::seekable(std::io::Cursor::new(
38                self.data.clone(),
39            )))
40        }
41    }
42
43    #[test]
44    fn reads_data() {
45        let source = MemorySource {
46            data: b"hello".to_vec(),
47        };
48
49        let mut reader = source.open().unwrap();
50        let mut buffer = [0u8; 3];
51        let count = reader.read(&mut buffer).unwrap();
52
53        assert_eq!(count, 3);
54        assert_eq!(&buffer, b"hel");
55    }
56}