rtoolbox/
print_tty.rs

1#[cfg(target_family = "wasm")]
2mod wasm {
3    use std::io::Write;
4
5    /// Displays a message on the STDOUT
6    pub fn print_tty(prompt: impl ToString) -> std::io::Result<()> {
7        let mut stdout = std::io::stdout();
8        write!(stdout, "{}", prompt.to_string().as_str())?;
9        stdout.flush()?;
10        Ok(())
11    }
12}
13
14#[cfg(target_family = "unix")]
15mod unix {
16    use std::io::Write;
17
18    /// Displays a message on the TTY
19    pub fn print_tty(prompt: impl ToString) -> std::io::Result<()> {
20        let mut stream = std::fs::OpenOptions::new().write(true).open("/dev/tty")?;
21        stream
22            .write_all(prompt.to_string().as_str().as_bytes())
23            .and_then(|_| stream.flush())
24    }
25}
26
27#[cfg(target_family = "windows")]
28mod windows {
29    use std::io::Write;
30    use std::os::windows::io::FromRawHandle;
31    use winapi::um::fileapi::{CreateFileA, OPEN_EXISTING};
32    use winapi::um::handleapi::INVALID_HANDLE_VALUE;
33    use winapi::um::winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE};
34
35    /// Displays a message on the TTY
36    pub fn print_tty(prompt: impl ToString) -> std::io::Result<()> {
37        let handle = unsafe {
38            CreateFileA(
39                b"CONOUT$\x00".as_ptr() as *const i8,
40                GENERIC_READ | GENERIC_WRITE,
41                FILE_SHARE_READ | FILE_SHARE_WRITE,
42                std::ptr::null_mut(),
43                OPEN_EXISTING,
44                0,
45                std::ptr::null_mut(),
46            )
47        };
48        if handle == INVALID_HANDLE_VALUE {
49            return Err(std::io::Error::last_os_error());
50        }
51
52        let mut stream = unsafe { std::fs::File::from_raw_handle(handle) };
53
54        stream
55            .write_all(prompt.to_string().as_str().as_bytes())
56            .and_then(|_| stream.flush())
57    }
58}
59
60/// Prints a message to a writer
61pub fn print_writer(stream: &mut impl Write, prompt: impl ToString) -> std::io::Result<()> {
62    stream
63        .write_all(prompt.to_string().as_str().as_bytes())
64        .and_then(|_| stream.flush())
65}
66
67use std::io::Write;
68#[cfg(target_family = "unix")]
69pub use unix::print_tty;
70#[cfg(target_family = "wasm")]
71pub use wasm::print_tty;
72#[cfg(target_family = "windows")]
73pub use windows::print_tty;