use crate::graphics::*;
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "alloc")]
use alloc::vec;
#[cfg(feature = "alloc")]
pub struct FileBuf {
pub(crate) raw: Box<[u8]>,
}
#[cfg(feature = "alloc")]
impl FileBuf {
#[must_use]
pub fn data(&self) -> &[u8] {
&self.raw
}
#[must_use]
pub fn as_font(&self) -> Font {
Font { raw: &self.raw }
}
#[must_use]
pub fn as_image(&self) -> Image {
Image { raw: &self.raw }
}
}
pub struct File<'a> {
pub(crate) raw: &'a [u8],
}
impl File<'_> {
#[must_use]
pub const fn data(&self) -> &[u8] {
self.raw
}
#[must_use]
pub const fn as_font(&self) -> Font {
Font { raw: self.raw }
}
#[must_use]
pub const fn as_image(&self) -> Image {
Image { raw: self.raw }
}
}
#[must_use]
pub fn get_file_size(name: &str) -> usize {
let path_ptr = name.as_ptr();
let size = unsafe { bindings::get_file_size(path_ptr as u32, name.len() as u32) };
size as usize
}
pub fn load_file<'a>(name: &str, buf: &'a mut [u8]) -> File<'a> {
let path_ptr = name.as_ptr();
let buf_ptr = buf.as_mut_ptr();
unsafe {
bindings::load_file(
path_ptr as u32,
name.len() as u32,
buf_ptr as u32,
buf.len() as u32,
);
}
File { raw: buf }
}
#[cfg(feature = "alloc")]
#[must_use]
pub fn load_file_buf(name: &str) -> Option<FileBuf> {
let size = get_file_size(name);
if size == 0 {
return None;
}
let mut buf = vec![0; size];
load_file(name, &mut buf);
Some(FileBuf {
raw: buf.into_boxed_slice(),
})
}
pub fn dump_file(name: &str, buf: &[u8]) {
let path_ptr = name.as_ptr();
let buf_ptr = buf.as_ptr();
unsafe {
bindings::dump_file(
path_ptr as u32,
name.len() as u32,
buf_ptr as u32,
buf.len() as u32,
);
}
}
pub fn remove_file(name: &str) {
let path_ptr = name.as_ptr();
unsafe {
bindings::remove_file(path_ptr as u32, name.len() as u32);
}
}
pub struct Font<'a> {
pub(crate) raw: &'a [u8],
}
impl<'a> From<File<'a>> for Font<'a> {
fn from(value: File<'a>) -> Self {
Self { raw: value.raw }
}
}
#[cfg(feature = "alloc")]
impl<'a> From<&'a FileBuf> for Font<'a> {
fn from(value: &'a FileBuf) -> Self {
Self { raw: &value.raw }
}
}
mod bindings {
#[link(wasm_import_module = "fs")]
extern {
pub(crate) fn get_file_size(path_ptr: u32, path_len: u32) -> u32;
pub(crate) fn load_file(path_ptr: u32, path_len: u32, buf_ptr: u32, buf_len: u32) -> u32;
pub(crate) fn dump_file(path_ptr: u32, path_len: u32, buf_ptr: u32, buf_len: u32) -> u32;
pub(crate) fn remove_file(path_ptr: u32, path_len: u32);
}
}