use std::hash::Hash;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use thiserror::Error;
pub use rust_silos_macros::embed_silo;
#[derive(Debug, Error)]
pub enum Error {
#[error("Failed to decode file contents: {source}")]
DecodeError {
#[from]
source: std::string::FromUtf8Error,
},
#[error("File not found")]
NotFound,
#[error("I/O error: {source}")]
IoError {
#[from]
source: std::io::Error,
},
}
#[derive(Debug)]
pub struct EmbedEntry {
pub path: &'static str,
pub contents: &'static [u8],
pub size: usize,
pub modified: u64,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct FileMeta {
pub size: usize,
pub modified: u64,
}
#[derive(Copy, Clone, Debug)]
struct EmbedFile {
inner: &'static EmbedEntry,
}
impl EmbedFile {
pub fn path(&self) -> &Path {
Path::new(self.inner.path)
}
}
#[derive(Debug, Clone)]
enum FileKind {
Embed(EmbedFile),
Dynamic(DynFile),
}
#[derive(Debug, Clone)]
pub struct File {
inner: FileKind,
}
impl File {
pub fn reader(&self) -> Result<FileReader, Error> {
match &self.inner {
FileKind::Embed(embed) => Ok(FileReader::Embed(Cursor::new(embed.inner.contents))),
FileKind::Dynamic(dyn_file) => Ok(FileReader::Dynamic(std::fs::File::open(
dyn_file.absolute_path(),
)?)),
}
}
pub fn path(&self) -> &Path {
match &self.inner {
FileKind::Embed(embed) => embed.path(),
FileKind::Dynamic(dyn_file) => dyn_file.path(),
}
}
pub fn is_embedded(&self) -> bool {
matches!(self.inner, FileKind::Embed(_))
}
pub fn absolute_path(&self) -> Option<&Path> {
match &self.inner {
FileKind::Embed(_) => None,
FileKind::Dynamic(dyn_file) => Some(dyn_file.absolute_path()),
}
}
pub fn extension(&self) -> Option<&str> {
self.path().extension().and_then(|s| s.to_str())
}
pub fn meta(&self) -> Result<FileMeta, Error> {
match &self.inner {
FileKind::Embed(embed) => Ok(FileMeta {
size: embed.inner.size,
modified: embed.inner.modified,
}),
FileKind::Dynamic(dyn_file) => {
let metadata = std::fs::metadata(dyn_file.absolute_path())?;
let len = metadata.len();
let size = usize::try_from(len).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, "file size overflows usize")
})?;
let mtime = metadata.modified()?;
let dur = mtime.duration_since(std::time::UNIX_EPOCH).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"file modified time is before UNIX epoch",
)
})?;
Ok(FileMeta {
size,
modified: dur.as_secs(),
})
}
}
}
}
impl PartialEq for File {
fn eq(&self, other: &Self) -> bool {
self.path() == other.path()
}
}
impl Hash for File {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.path().hash(state);
}
}
impl Eq for File {}
#[derive(Debug, Clone)]
struct EmbedSilo {
entries: &'static [(&'static str, EmbedEntry)],
root: &'static str,
}
impl EmbedSilo {
pub const fn new(entries: &'static [(&'static str, EmbedEntry)], root: &'static str) -> Self {
Self { entries, root }
}
pub fn get_file(&self, path: &str) -> Option<EmbedFile> {
self.entries
.binary_search_by_key(&path, |(k, _)| k)
.ok()
.map(|idx| EmbedFile { inner: &self.entries[idx].1 })
}
pub fn iter(&self) -> impl Iterator<Item = File> + '_ {
self.entries.iter().map(|(_, entry)| File {
inner: FileKind::Embed(EmbedFile { inner: entry }),
})
}
}
#[derive(Debug, Clone)]
struct DynFile {
rel_path: Arc<str>,
full_path: Arc<str>,
}
fn normalize_rel_path(path: &str) -> Arc<str> {
Arc::from(path.replace('\\', "/"))
}
impl DynFile {
pub fn new<S: AsRef<str>>(full_path: S, rel_path: S) -> Self {
Self {
rel_path: Arc::from(rel_path.as_ref()),
full_path: Arc::from(full_path.as_ref()),
}
}
pub fn path(&self) -> &Path {
Path::new(&*self.rel_path)
}
pub fn absolute_path(&self) -> &Path {
Path::new(&*self.full_path)
}
}
fn get_file_for_root(root: &str, path: &str) -> Option<DynFile> {
let root_canon = Path::new(root).canonicalize().ok()?;
let normalized_rel = normalize_rel_path(path);
let joined = root_canon.join(normalized_rel.as_ref());
let candidate = joined.canonicalize().ok()?;
if !candidate.starts_with(&root_canon) {
return None;
}
if !candidate.is_file() {
return None;
}
let rel_path = candidate
.strip_prefix(&root_canon)
.ok()?
.to_str()?
.replace('\\', "/");
let full_path = candidate.to_str()?;
Some(DynFile::new(Arc::from(full_path), Arc::from(rel_path)))
}
fn iter_root(root: &str) -> impl Iterator<Item = File> {
let root_path = PathBuf::from(root);
walkdir::WalkDir::new(&root_path)
.into_iter()
.filter_map(move |entry| {
let entry = entry.ok()?;
if entry.file_type().is_file() {
let relative_path = entry.path().strip_prefix(&root_path).ok()?;
Some(File {
inner: FileKind::Dynamic(DynFile::new(
Arc::from(entry.path().to_str()?),
normalize_rel_path(relative_path.to_str()?),
)),
})
} else {
None
}
})
}
#[derive(Debug, Clone)]
struct DynamicSilo {
root: Arc<str>,
}
impl DynamicSilo {
pub fn new(root: &str) -> Self {
Self { root: Arc::from(root) }
}
pub fn get_file(&self, path: &str) -> Option<DynFile> {
get_file_for_root(self.root.as_ref(), path)
}
pub fn iter(&self) -> impl Iterator<Item = File> {
iter_root(self.root.as_ref())
}
}
#[derive(Debug, Clone)]
struct StaticSilo {
root: &'static str,
}
impl StaticSilo {
pub const fn new(root: &'static str) -> Self {
Self { root }
}
pub fn get_file(&self, path: &str) -> Option<DynFile> {
get_file_for_root(self.root, path)
}
pub fn iter(&self) -> impl Iterator<Item = File> {
iter_root(self.root)
}
}
#[derive(Debug, Clone)]
enum InnerSilo {
Embed(EmbedSilo),
Static(StaticSilo),
Dynamic(DynamicSilo),
}
#[derive(Debug, Clone)]
pub struct Silo {
inner: InnerSilo,
}
impl Silo {
#[doc(hidden)]
pub const fn from_embedded(entries: &'static [(&'static str, EmbedEntry)], root: &'static str) -> Self {
Self {
inner: InnerSilo::Embed(EmbedSilo::new(entries, root)),
}
}
#[doc(hidden)]
pub const fn from_static(path: &'static str) -> Self {
Self {
inner: InnerSilo::Static(StaticSilo::new(path)),
}
}
pub fn new(path: &str) -> Self {
Self {
inner: InnerSilo::Dynamic(DynamicSilo::new(path)),
}
}
pub fn into_dynamic(self) -> Self {
match self.inner {
InnerSilo::Embed(emb_silo) => Self::from_static(emb_silo.root),
InnerSilo::Static(_) => self,
InnerSilo::Dynamic(_) => self,
}
}
pub fn auto_dynamic(self) -> Self {
if cfg!(debug_assertions) {
self.into_dynamic()
} else {
self
}
}
pub fn is_dynamic(&self) -> bool {
matches!(self.inner, InnerSilo::Static(_) | InnerSilo::Dynamic(_))
}
pub fn is_embedded(&self) -> bool {
matches!(self.inner, InnerSilo::Embed(_))
}
pub fn get_file(&self, path: &str) -> Option<File> {
match &self.inner {
InnerSilo::Embed(embed) => embed.get_file(path).map(|f| File {
inner: FileKind::Embed(f),
}),
InnerSilo::Static(dyn_silo) => dyn_silo.get_file(path).map(|f| File {
inner: FileKind::Dynamic(f),
}),
InnerSilo::Dynamic(dyn_silo) => dyn_silo.get_file(path).map(|f| File {
inner: FileKind::Dynamic(f),
}),
}
}
pub fn iter(&self) -> Box<dyn Iterator<Item = File> + '_> {
match &self.inner {
InnerSilo::Embed(embd) => Box::new(embd.iter()),
InnerSilo::Static(dynm) => Box::new(dynm.iter()),
InnerSilo::Dynamic(dynm) => Box::new(dynm.iter()),
}
}
}
#[derive(Debug, Clone)]
pub struct SiloSet {
pub silos: Vec<Silo>,
}
impl SiloSet {
pub fn new(dirs: Vec<Silo>) -> Self {
Self { silos: dirs }
}
pub fn get_file(&self, name: &str) -> Option<File> {
for silo in self.silos.iter().rev() {
if let Some(file) = silo.get_file(name) {
return Some(file);
}
}
None
}
pub fn iter(&self) -> impl Iterator<Item = File> + '_ {
self.silos.iter().rev().flat_map(|silo| silo.iter())
}
pub fn iter_override(&self) -> impl Iterator<Item = File> + '_ {
let mut history = std::collections::HashSet::new();
self.iter().filter(move |file| history.insert(file.clone()))
}
}
pub enum FileReader {
Embed(std::io::Cursor<&'static [u8]>),
Dynamic(std::fs::File),
}
impl std::io::Read for FileReader {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
FileReader::Embed(c) => c.read(buf),
FileReader::Dynamic(f) => f.read(buf),
}
}
}