1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//! Forwarding to host stdin/stdout

use lazy_static::lazy_static;
use slos_filesystem::{FsError, FsFileHandle};
use slos_hal::SystemConsole;
use slos_helpers::UnsafeContainer;
use std::io::{self, Read, Write};

lazy_static! {
	/// Global [`Console`] instance
	pub static ref CONSOLE: UnsafeContainer<Console> = UnsafeContainer::new(Console);
}

/// Hosted [`SystemConsole`] implementation
///
/// This just forwards read/write to the host's stdin/stdout.
#[derive(Debug)]
pub struct Console;

impl FsFileHandle for Console {
	fn raw_read(&mut self, offset: usize, length: Option<usize>) -> Result<Vec<u8>, FsError> {
		if offset != 0 {
			return Err(FsError::InvalidArgument);
		}

		let mut buffer = Vec::new();
		if let Some(len) = length {
			buffer.reserve(len);
		}

		io::stdin().read(&mut buffer[..])?;
		Ok(buffer)
	}

	fn raw_write(&mut self, offset: usize, data: &[u8]) -> Result<(), FsError> {
		if offset != 0 {
			return Err(FsError::InvalidArgument);
		}

		let mut stdout = io::stdout();
		stdout.write_all(data)?;
		stdout.flush()?;

		Ok(())
	}
}

impl SystemConsole for Console {}