1use std::ops::Deref;
8use std::path::Path;
9
10use kh_runtime::MappedFile;
11
12use crate::error::LoadError;
13
14#[derive(Debug)]
16pub enum FileImage {
17 Map(MappedFile),
19 Heap(Vec<u8>),
21}
22
23impl FileImage {
24 pub fn open(path: &Path) -> Result<Self, LoadError> {
26 match MappedFile::open(path) {
27 Ok(m) => Ok(Self::Map(m)),
28 Err(_mmap_err) => {
29 let bytes = std::fs::read(path)?;
30 Ok(Self::Heap(bytes))
31 }
32 }
33 }
34
35 #[must_use]
37 pub fn as_slice(&self) -> &[u8] {
38 match self {
39 Self::Map(m) => m.as_slice(),
40 Self::Heap(v) => v.as_slice(),
41 }
42 }
43
44 #[must_use]
46 pub fn len(&self) -> usize {
47 self.as_slice().len()
48 }
49
50 #[must_use]
52 pub fn is_empty(&self) -> bool {
53 self.as_slice().is_empty()
54 }
55}
56
57impl Deref for FileImage {
58 type Target = [u8];
59
60 fn deref(&self) -> &Self::Target {
61 self.as_slice()
62 }
63}