1
0

94 lines
2.6 KiB
Rust
Raw Normal View History

2025-01-04 02:56:46 -05:00
use std::io::{self, stdin, stdout, Write};
2024-12-17 07:10:47 -05:00
use std::ops::Range;
use crate::vm::{get_next_action, Register, ThreadSignal};
2024-12-17 03:22:44 -05:00
use crate::{vm::Record, ConcreteValue, NativeFunctionError, Value};
2024-12-17 03:22:44 -05:00
pub fn read_line(
record: &mut Record,
2024-12-17 07:10:47 -05:00
destination: Option<u8>,
_argument_range: Range<u8>,
) -> Result<ThreadSignal, NativeFunctionError> {
let destination = destination.unwrap();
let mut buffer = String::new();
match stdin().read_line(&mut buffer) {
Ok(_) => {
let length = buffer.len();
buffer.truncate(length.saturating_sub(1));
2024-12-17 07:10:47 -05:00
let register = Register::Value(Value::Concrete(ConcreteValue::string(buffer)));
record.set_register(destination, register);
}
Err(error) => {
return Err(NativeFunctionError::Io {
error: error.kind(),
position: record.current_position(),
})
}
}
2024-12-17 07:10:47 -05:00
let next_action = get_next_action(record);
Ok(ThreadSignal::Continue(next_action))
}
pub fn write(
2024-12-17 03:22:44 -05:00
record: &mut Record,
2024-12-17 07:10:47 -05:00
_destination: Option<u8>,
argument_range: Range<u8>,
) -> Result<ThreadSignal, NativeFunctionError> {
let mut stdout = stdout();
2024-12-17 07:10:47 -05:00
for register_index in argument_range {
if let Some(value) = record.open_register_allow_empty_unchecked(register_index) {
let string = value.display(record);
stdout
.write(string.as_bytes())
.map_err(|io_error| NativeFunctionError::Io {
error: io_error.kind(),
position: record.current_position(),
})?;
}
}
2024-12-17 07:10:47 -05:00
stdout.flush().map_err(|io_error| NativeFunctionError::Io {
error: io_error.kind(),
position: record.current_position(),
})?;
let next_action = get_next_action(record);
Ok(ThreadSignal::Continue(next_action))
}
pub fn write_line(
2024-12-17 03:22:44 -05:00
record: &mut Record,
2024-12-17 07:10:47 -05:00
_destination: Option<u8>,
argument_range: Range<u8>,
) -> Result<ThreadSignal, NativeFunctionError> {
2025-01-04 02:56:46 -05:00
let map_err = |io_error: io::Error| NativeFunctionError::Io {
error: io_error.kind(),
position: record.current_position(),
};
2024-12-17 07:10:47 -05:00
let mut stdout = stdout().lock();
2024-12-17 07:10:47 -05:00
for register_index in argument_range {
if let Some(value) = record.open_register_allow_empty_unchecked(register_index) {
let string = value.display(record);
2025-01-04 02:56:46 -05:00
stdout.write(string.as_bytes()).map_err(map_err)?;
stdout.write(b"\n").map_err(map_err)?;
}
}
2025-01-04 02:56:46 -05:00
stdout.flush().map_err(map_err)?;
let next_action = get_next_action(record);
Ok(ThreadSignal::Continue(next_action))
}