2024-12-10 01:34:53 -05:00
|
|
|
use std::io::{stdin, stdout, Write};
|
|
|
|
|
|
|
|
use smallvec::SmallVec;
|
|
|
|
|
2024-12-14 08:49:02 -05:00
|
|
|
use crate::{ConcreteValue, NativeFunctionError, Value, Vm};
|
2024-12-10 01:34:53 -05:00
|
|
|
|
2024-12-14 08:49:02 -05:00
|
|
|
pub fn read_line(vm: &Vm, _: SmallVec<[&Value; 4]>) -> Result<Option<Value>, NativeFunctionError> {
|
2024-12-10 01:34:53 -05:00
|
|
|
let mut buffer = String::new();
|
|
|
|
|
|
|
|
match stdin().read_line(&mut buffer) {
|
|
|
|
Ok(_) => {
|
|
|
|
let length = buffer.len();
|
|
|
|
|
|
|
|
buffer.truncate(length.saturating_sub(1));
|
|
|
|
|
|
|
|
Ok(Some(Value::Concrete(ConcreteValue::string(buffer))))
|
|
|
|
}
|
|
|
|
Err(error) => Err(NativeFunctionError::Io {
|
|
|
|
error: error.kind(),
|
|
|
|
position: vm.current_position(),
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn write(
|
|
|
|
vm: &Vm,
|
2024-12-14 08:49:02 -05:00
|
|
|
arguments: SmallVec<[&Value; 4]>,
|
2024-12-10 01:34:53 -05:00
|
|
|
) -> Result<Option<Value>, NativeFunctionError> {
|
|
|
|
let mut stdout = stdout();
|
|
|
|
|
|
|
|
for argument in arguments {
|
2024-12-14 16:17:02 -05:00
|
|
|
let string = argument.display(vm);
|
2024-12-10 01:34:53 -05:00
|
|
|
|
|
|
|
stdout
|
|
|
|
.write_all(string.as_bytes())
|
|
|
|
.map_err(|io_error| NativeFunctionError::Io {
|
|
|
|
error: io_error.kind(),
|
|
|
|
position: vm.current_position(),
|
|
|
|
})?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn write_line(
|
|
|
|
vm: &Vm,
|
2024-12-14 08:49:02 -05:00
|
|
|
arguments: SmallVec<[&Value; 4]>,
|
2024-12-10 01:34:53 -05:00
|
|
|
) -> Result<Option<Value>, NativeFunctionError> {
|
|
|
|
let mut stdout = stdout();
|
|
|
|
|
|
|
|
for argument in arguments {
|
2024-12-14 16:17:02 -05:00
|
|
|
let string = argument.display(vm);
|
2024-12-10 01:34:53 -05:00
|
|
|
|
|
|
|
stdout
|
|
|
|
.write_all(string.as_bytes())
|
|
|
|
.map_err(|io_error| NativeFunctionError::Io {
|
|
|
|
error: io_error.kind(),
|
|
|
|
position: vm.current_position(),
|
|
|
|
})?;
|
|
|
|
}
|
|
|
|
|
|
|
|
stdout
|
|
|
|
.write(b"\n")
|
|
|
|
.map_err(|io_error| NativeFunctionError::Io {
|
|
|
|
error: io_error.kind(),
|
|
|
|
position: vm.current_position(),
|
|
|
|
})?;
|
|
|
|
|
|
|
|
Ok(None)
|
|
|
|
}
|