1use std::borrow::Cow;
4use std::fs::File;
5use std::sync::Mutex;
6
7use coip_format::FormatError;
8
9use crate::error::Result;
10
11pub enum Backing<'a> {
12 Slice(&'a [u8]),
13 Owned(Vec<u8>),
14 #[cfg(feature = "mmap")]
15 Mmap(memmap2::Mmap),
16 File {
17 file: Mutex<File>,
18 len: u64,
19 },
20}
21
22impl<'a> Backing<'a> {
23 #[inline]
24 pub fn len(&self) -> u64 {
25 match self {
26 Self::Slice(s) => s.len() as u64,
27 Self::Owned(v) => v.len() as u64,
28 #[cfg(feature = "mmap")]
29 Self::Mmap(m) => m.len() as u64,
30 Self::File { len, .. } => *len,
31 }
32 }
33
34 #[inline]
35 pub fn is_empty(&self) -> bool {
36 self.len() == 0
37 }
38
39 #[inline]
41 pub fn read_slice(&self, offset: u64, len: usize) -> Result<Cow<'_, [u8]>> {
42 let end = offset
43 .checked_add(len as u64)
44 .ok_or(FormatError::UnexpectedEof)?;
45 if end > self.len() {
46 return Err(FormatError::UnexpectedEof.into());
47 }
48 match self {
49 Self::Slice(s) => {
50 let start = offset as usize;
51 Ok(Cow::Borrowed(&s[start..start + len]))
52 }
53 Self::Owned(v) => {
54 let start = offset as usize;
55 Ok(Cow::Borrowed(&v[start..start + len]))
56 }
57 #[cfg(feature = "mmap")]
58 Self::Mmap(m) => {
59 let start = offset as usize;
60 Ok(Cow::Borrowed(&m[start..start + len]))
61 }
62 Self::File { file, .. } => {
63 use std::io::{Read, Seek, SeekFrom};
64 let mut buf = vec![0u8; len];
65 let mut guard = file.lock().expect("file lock poisoned");
66 guard.seek(SeekFrom::Start(offset))?;
67 guard.read_exact(&mut buf)?;
68 Ok(Cow::Owned(buf))
69 }
70 }
71 }
72}