Files
kramer/src/io.rs
2025-12-31 17:22:57 -05:00

68 lines
1.8 KiB
Rust

use std::fs::{File, OpenOptions};
use std::io::{self, Seek, SeekFrom};
use crate::cli::CONFIG;
use anyhow::Context;
/// Get length of data stream.
/// Physical length of data stream in bytes
/// (multiple of sector_size, rather than actual).
///
/// This will attempt to return the stream to its current read position.
pub fn get_stream_length<S: Seek>(stream: &mut S) -> io::Result<u64> {
let pos = stream.stream_position()?;
let len = stream.seek(SeekFrom::End(0));
stream.seek(SeekFrom::Start(pos))?;
len
}
pub fn load_input() -> anyhow::Result<File> {
OpenOptions::new()
.read(true)
.open(&CONFIG.input)
.with_context(|| format!("Failed to open input file: {}", &CONFIG.input.display()))
}
pub fn load_output() -> anyhow::Result<File> {
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(crate::path::OUTPUT_PATH.clone())
.with_context(|| {
format!(
"Failed to open/create output file at: {}",
crate::path::OUTPUT_PATH.display()
)
})
}
pub fn load_map_read() -> anyhow::Result<File> {
OpenOptions::new()
.read(true)
.open(crate::path::MAP_PATH.clone())
.with_context(|| {
format!(
"Failed to open/create mapping file at: {}",
crate::path::MAP_PATH.display()
)
})
}
pub fn load_map_write() -> anyhow::Result<File> {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true) // Wipe old map. Should really make a backup first.
.open(crate::path::MAP_PATH.clone())
.with_context(|| {
format!(
"Failed to open map file at: {}",
crate::path::MAP_PATH.display()
)
})
}