Skip to content

Commit 2af185f

Browse files
committed
Create enum to hold different sources of file data
1 parent 37c5539 commit 2af185f

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/file_data_source.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
use std::path::{PathBuf};
2+
use alloc::vec::Vec;
3+
use core::fmt::{Debug, Formatter};
4+
use std::{fs, io};
5+
use std::fs::File;
6+
use std::io::Cursor;
7+
use anyhow::Context;
8+
9+
#[derive(Clone)]
10+
pub enum FileDataSource {
11+
File(PathBuf),
12+
Data(Vec<u8>)
13+
}
14+
15+
impl Debug for FileDataSource {
16+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
17+
match self {
18+
FileDataSource::File(file) => f.write_fmt(format_args!("data source: File {}", file.display())),
19+
FileDataSource::Data(d) => f.write_fmt(format_args!("data source: {} raw bytes ", d.len()))
20+
}
21+
}
22+
}
23+
24+
impl FileDataSource {
25+
pub fn len(&self) -> anyhow::Result<u64> {
26+
Ok(match self {
27+
FileDataSource::File(path) => {
28+
fs::metadata(path)
29+
.with_context(|| format!("failed to read metadata of file `{}`", path.display()))?
30+
.len()
31+
}
32+
FileDataSource::Data(v) => v.len() as u64
33+
})
34+
}
35+
36+
pub fn copy_to(&self, target: &mut dyn io::Write) -> anyhow::Result<()> {
37+
match self {
38+
FileDataSource::File(file_path) => {
39+
io::copy(
40+
&mut fs::File::open(file_path)
41+
.with_context(|| format!("failed to open `{}` for copying", file_path.display()))?,
42+
target,
43+
)?;
44+
},
45+
FileDataSource::Data(contents) => {
46+
let mut cursor = Cursor::new(contents);
47+
io::copy(
48+
&mut cursor,
49+
target,
50+
)?;
51+
}
52+
};
53+
54+
Ok(())
55+
}
56+
}

src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ An experimental x86_64 bootloader that works on both BIOS and UEFI systems.
44

55
#![warn(missing_docs)]
66

7+
extern crate alloc;
8+
79
#[cfg(feature = "bios")]
810
mod bios;
911
#[cfg(feature = "uefi")]
@@ -20,6 +22,7 @@ pub use uefi::UefiBoot;
2022
pub use bios::BiosBoot;
2123

2224
mod fat;
25+
mod file_data_source;
2326

2427
use std::{
2528
collections::BTreeMap,

0 commit comments

Comments
 (0)