use std::io;
use std::path::{ Path, PathBuf };
pub fn read_to_string( path: impl AsRef<Path> ) -> io::Result<String>
{
String::from_utf8( read( path )? ).map_err( |e| io::Error::new( io::ErrorKind::InvalidData, e ) )
}
#[ cfg( not( target_arch = "wasm32" ) ) ]
pub fn read( path: impl AsRef<Path> ) -> io::Result<Vec<u8>>
{
std::fs::read( path )
}
#[ cfg( not( target_arch = "wasm32" ) ) ]
pub fn read_dir( dir: impl AsRef<Path> ) -> io::Result<Vec<PathBuf>>
{
Ok( std::fs::read_dir( dir )?.filter_map( Result::ok ).map( |entry| entry.path() ).collect() )
}
#[ cfg( not( target_arch = "wasm32" ) ) ]
pub fn is_file( path: impl AsRef<Path> ) -> bool
{
path.as_ref().is_file()
}
#[ cfg( not( target_arch = "wasm32" ) ) ]
pub fn is_dir( path: impl AsRef<Path> ) -> bool
{
path.as_ref().is_dir()
}
#[ cfg( target_arch = "wasm32" ) ]
static FILES: std::sync::Mutex<std::collections::BTreeMap<PathBuf, std::sync::Arc<[u8]>>> = std::sync::Mutex::new( std::collections::BTreeMap::new() );
#[ cfg( target_arch = "wasm32" ) ]
fn files() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<PathBuf, std::sync::Arc<[u8]>>>
{
FILES.lock().unwrap_or_else( std::sync::PoisonError::into_inner )
}
#[ cfg( target_arch = "wasm32" ) ]
pub( crate ) fn insert( path: impl Into<PathBuf>, bytes: Vec<u8> )
{
files().insert( path.into(), bytes.into() );
}
#[ cfg( target_arch = "wasm32" ) ]
pub fn read( path: impl AsRef<Path> ) -> io::Result<Vec<u8>>
{
files().get( path.as_ref() ).map( |bytes| bytes.to_vec() ).ok_or_else( || io::ErrorKind::NotFound.into() )
}
#[ cfg( target_arch = "wasm32" ) ]
pub fn read_dir( dir: impl AsRef<Path> ) -> io::Result<Vec<PathBuf>>
{
let dir = dir.as_ref();
let mut entries: Vec<PathBuf> = files().keys()
.filter_map( |path| path.strip_prefix( dir ).ok()?.components().next() )
.map( |first| dir.join( first ) )
.collect();
entries.dedup();
if entries.is_empty() { return Err( io::ErrorKind::NotFound.into() ); }
Ok( entries )
}
#[ cfg( target_arch = "wasm32" ) ]
pub fn is_file( path: impl AsRef<Path> ) -> bool
{
files().contains_key( path.as_ref() )
}
#[ cfg( target_arch = "wasm32" ) ]
pub fn is_dir( path: impl AsRef<Path> ) -> bool
{
let path = path.as_ref();
files().keys().any( |file| file != path && file.starts_with( path ) )
}