use std::fs::File;
use std::io::{BufReader, Read as _};
use std::path::Path;
use crate::error::{LpParseError, LpResult};
#[inline]
pub fn parse_file(path: &Path) -> LpResult<String> {
let file = File::open(path).map_err(|e| LpParseError::io_error(format!("Failed to open file '{}': {}", path.display(), e)))?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader
.read_to_string(&mut contents)
.map_err(|e| LpParseError::io_error(format!("Failed to read file '{}': {}", path.display(), e)))?;
Ok(contents)
}
#[cfg(feature = "mmap")]
pub struct MappedFile {
_mmap: memmap2::Mmap,
content: *const str,
}
#[cfg(feature = "mmap")]
unsafe impl Send for MappedFile {}
#[cfg(feature = "mmap")]
unsafe impl Sync for MappedFile {}
#[cfg(feature = "mmap")]
impl MappedFile {
pub fn open(path: &Path) -> LpResult<Self> {
let file = File::open(path).map_err(|e| LpParseError::io_error(format!("Failed to open file '{}': {}", path.display(), e)))?;
let mmap = unsafe {
memmap2::Mmap::map(&file).map_err(|e| LpParseError::io_error(format!("Failed to mmap file '{}': {}", path.display(), e)))?
};
let content_str = std::str::from_utf8(&mmap)
.map_err(|e| LpParseError::io_error(format!("File '{}' is not valid UTF-8: {}", path.display(), e)))?;
let content: *const str = content_str;
Ok(Self { _mmap: mmap, content })
}
#[inline]
#[must_use]
pub const fn as_str(&self) -> &str {
unsafe { &*self.content }
}
}