#![allow(clippy::arc_with_non_send_sync)]
mod memory;
#[cfg(any(feature = "native-host", test))]
pub(crate) mod native;
pub(crate) mod protocol;
pub mod testing;
pub use memory::{MemoryFilesystem, MemoryOptions, memory_filesystem};
#[cfg(feature = "native-host")]
pub use native::{NativeFilesystem, NativeOptions, native_host};
pub use protocol::{CapabilityPoll, CapabilityRequest, CapabilityValue, EffectClass};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ResourceId(pub u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingToken(pub u64);
#[derive(Clone, Debug, PartialEq)]
pub enum Completion<T> {
Ready(Result<T, HostIoError>),
Pending(PendingToken),
}
impl<T> Completion<T> {
pub(crate) fn map<U>(self, f: impl FnOnce(T) -> U) -> Completion<U> {
match self {
Self::Ready(r) => Completion::Ready(r.map(f)),
Self::Pending(t) => Completion::Pending(t),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HostIoErrorKind {
NotFound,
PermissionDenied,
AlreadyExists,
IsDirectory,
InvalidInput,
Unsupported,
Other,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct HostIoError {
pub kind: HostIoErrorKind,
pub code: i32,
pub message: Vec<u8>,
}
impl HostIoError {
pub fn new(kind: HostIoErrorKind, message: impl Into<Vec<u8>>) -> Self {
let code = match kind {
HostIoErrorKind::NotFound => 2,
HostIoErrorKind::PermissionDenied => 13,
HostIoErrorKind::AlreadyExists => 17,
HostIoErrorKind::IsDirectory => 21,
HostIoErrorKind::InvalidInput => 22,
HostIoErrorKind::Unsupported => 38,
HostIoErrorKind::Other => 5,
};
Self {
kind,
code,
message: message.into(),
}
}
pub(crate) fn unsupported() -> Self {
Self::new(
HostIoErrorKind::Unsupported,
b"operation not supported".to_vec(),
)
}
pub(crate) fn invalid() -> Self {
Self::new(
HostIoErrorKind::InvalidInput,
b"invalid resource or input".to_vec(),
)
}
pub(crate) fn denied() -> Self {
Self::new(
HostIoErrorKind::PermissionDenied,
b"host access denied".to_vec(),
)
}
}
impl std::fmt::Display for HostIoError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf8_lossy(&self.message))
}
}
impl std::error::Error for HostIoError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HandlePolicy {
Rebind,
Refuse,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OpenMode {
pub read: bool,
pub write: bool,
pub append: bool,
pub create: bool,
pub truncate: bool,
pub binary: bool,
}
impl OpenMode {
pub fn parse(bytes: &[u8]) -> Result<Self, HostIoError> {
let Some((&first, tail)) = bytes.split_first() else {
return Err(HostIoError::invalid());
};
if !matches!(first, b'r' | b'w' | b'a')
|| !matches!(tail, b"" | b"+" | b"b" | b"+b" | b"b+")
{
return Err(HostIoError::invalid());
}
Ok(Self {
read: first == b'r' || tail.contains(&b'+'),
write: first != b'r' || tail.contains(&b'+'),
append: first == b'a',
create: first != b'r',
truncate: first == b'w',
binary: tail.contains(&b'b'),
})
}
pub(crate) fn valid(self) -> bool {
(self.read || self.write)
&& (!self.append || (self.write && self.create && !self.truncate))
&& (!self.truncate || (self.write && self.create))
&& (!self.create || self.write)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stream {
Stdin,
Stdout,
Stderr,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PipeMode {
Read,
Write,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProcessStatus {
Exit(i32),
Signal(i32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CivilOffset {
pub seconds: i32,
pub isdst: bool,
}
pub trait Filesystem: 'static {
fn probe_readable(&self, path: &[u8]) -> Completion<bool> {
let _ = path;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn open(&self, path: &[u8], mode: OpenMode) -> Completion<ResourceId> {
let _ = path;
let _ = mode;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn read_at(&self, id: ResourceId, offset: u64, max: usize) -> Completion<Vec<u8>> {
let _ = id;
let _ = offset;
let _ = max;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn write_at(&self, id: ResourceId, offset: u64, bytes: &[u8]) -> Completion<usize> {
let _ = id;
let _ = offset;
let _ = bytes;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn append(&self, id: ResourceId, bytes: &[u8]) -> Completion<u64> {
let _ = id;
let _ = bytes;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn size(&self, id: ResourceId) -> Completion<u64> {
let _ = id;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn flush(&self, id: ResourceId) -> Completion<()> {
let _ = id;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn close(&self, id: ResourceId) -> Completion<()> {
let _ = id;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn remove(&self, path: &[u8]) -> Completion<()> {
let _ = path;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn rename(&self, from: &[u8], to: &[u8]) -> Completion<()> {
let _ = from;
let _ = to;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn temp_file(&self) -> Completion<ResourceId> {
Completion::Ready(Err(HostIoError::unsupported()))
}
fn temp_name(&self) -> Completion<Vec<u8>> {
Completion::Ready(Err(HostIoError::unsupported()))
}
fn read_file(&self, path: &[u8], max: usize) -> Completion<Vec<u8>> {
let _ = path;
let _ = max;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn read_file_range(&self, path: &[u8], offset: u64, max: usize) -> Completion<Vec<u8>> {
if offset == 0 {
self.read_file(path, max)
} else {
Completion::Ready(Err(HostIoError::unsupported()))
}
}
fn handle_policy(&self) -> HandlePolicy {
HandlePolicy::Refuse
}
fn rebind(&self, id: ResourceId) -> Result<(), HostIoError> {
let _ = id;
Err(HostIoError::unsupported())
}
}
pub(crate) fn filesystem_policy(fs: &dyn Filesystem) -> Result<HandlePolicy, HostIoError> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| fs.handle_policy()))
.map_err(|_| HostIoError::new(HostIoErrorKind::Other, b"host capability panicked".to_vec()))
}
pub trait Stdio: 'static {
fn read_stdin(&self, max: usize) -> Completion<Vec<u8>> {
let _ = max;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn write_stdout(&self, bytes: &[u8]) -> Completion<usize> {
let _ = bytes;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn write_stderr(&self, bytes: &[u8]) -> Completion<usize> {
let _ = bytes;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn flush(&self, stream: Stream) -> Completion<()> {
let _ = stream;
Completion::Ready(Err(HostIoError::unsupported()))
}
}
pub trait Clock: 'static {
fn now_seconds(&self) -> Completion<i64> {
Completion::Ready(Err(HostIoError::unsupported()))
}
fn cpu_seconds(&self) -> Completion<f64> {
Completion::Ready(Err(HostIoError::unsupported()))
}
}
pub trait CivilTime: 'static {
fn zone_name(&self, _utc_seconds: i64) -> Completion<Vec<u8>> {
Completion::Ready(Ok(Vec::new()))
}
fn local_offset(&self, utc_seconds: i64) -> Completion<CivilOffset> {
let _ = utc_seconds;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn utc_seconds(&self, local_seconds: i64, isdst: Option<bool>) -> Completion<i64> {
let _ = local_seconds;
let _ = isdst;
Completion::Ready(Err(HostIoError::unsupported()))
}
}
pub trait Environment: 'static {
fn get(&self, name: &[u8]) -> Completion<Option<Vec<u8>>> {
let _ = name;
Completion::Ready(Err(HostIoError::unsupported()))
}
}
pub trait Process: 'static {
fn shell_available(&self) -> Completion<bool> {
Completion::Ready(Err(HostIoError::unsupported()))
}
fn execute(&self, cmd: &[u8]) -> Completion<ProcessStatus> {
let _ = cmd;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn popen(&self, cmd: &[u8], mode: PipeMode) -> Completion<ResourceId> {
let _ = cmd;
let _ = mode;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn read_at(&self, id: ResourceId, offset: u64, max: usize) -> Completion<Vec<u8>> {
let _ = id;
let _ = offset;
let _ = max;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn write_at(&self, id: ResourceId, offset: u64, bytes: &[u8]) -> Completion<usize> {
let _ = id;
let _ = offset;
let _ = bytes;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn flush(&self, id: ResourceId) -> Completion<()> {
let _ = id;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn close(&self, id: ResourceId) -> Completion<ProcessStatus> {
let _ = id;
Completion::Ready(Err(HostIoError::unsupported()))
}
fn handle_policy(&self) -> HandlePolicy {
HandlePolicy::Refuse
}
fn rebind(&self, id: ResourceId) -> Result<(), HostIoError> {
let _ = id;
Err(HostIoError::unsupported())
}
}
#[cfg(test)]
mod tests;