use crate::data::Mem;
use crate::error::Ior;
use crate::host::Io;
use crate::{Error, Result};
use super::context::Context;
use super::{FALSE, MAX_WORD_LEN, TRUE};
#[cfg(feature = "std")]
use crate::host::Clock;
pub fn key<M: Mem, H: Io>(host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
match host.key()? {
Some(c) => ctx.push(c as usize),
None => Err(Error::Io),
}
}
pub fn emit<M: Mem, H: Io>(host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
let c = ctx.pop()? as u8;
host.emit(c)
}
pub fn find<M: Mem, H>(_host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
let len = ctx.pop()?;
let addr = ctx.pop()?;
if len > MAX_WORD_LEN {
ctx.dict().set_diagnostic(addr, len)?;
return Err(Error::Throw(Ior::DEFINITION_NAME_TOO_LONG));
}
match ctx.dict().find_at(addr, len)? {
Some((xt, flag)) => {
ctx.push(xt)?;
ctx.push(flag)
}
None => ctx.push(0),
}
}
pub fn refill<M: Mem, H: Io>(host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
match host.refill(ctx.input_mut()?) {
Ok(Some(len)) => {
ctx.dict().set_source_len(len)?;
ctx.push(TRUE)?;
Ok(())
}
Ok(None) => {
ctx.push(FALSE)?;
Ok(())
}
Err(e) => Err(e),
}
}
pub fn header<M: Mem, H>(_host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
let len = ctx.pop()?;
let addr = ctx.pop()?;
if len > MAX_WORD_LEN {
ctx.dict().set_diagnostic(addr, len)?;
return Err(Error::Throw(Ior::DEFINITION_NAME_TOO_LONG));
}
let code_addr = ctx.dict().create_at(addr, len, 0)?;
ctx.dict().set_latest(code_addr)?;
ctx.dict().set_here(code_addr)
}
#[cfg(feature = "time")]
pub fn time_and_date<M: Mem, H: Clock>(host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
let dt = host.time_and_date();
ctx.push(dt.second)?;
ctx.push(dt.minute)?;
ctx.push(dt.hour)?;
ctx.push(dt.day)?;
ctx.push(dt.month)?;
ctx.push(dt.year)
}
#[cfg(feature = "std")]
pub fn ms<M: Mem, H: Clock>(host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
let ms = ctx.pop()?;
host.sleep_ms(ms);
Ok(())
}
#[cfg(feature = "std")]
pub fn utime<M: Mem, H: Clock>(host: &mut H, ctx: &mut Context<'_, M>) -> Result<()> {
let (lo, hi): (usize, usize) = host.utime().into();
ctx.push(lo)?;
ctx.push(hi)
}