1#[cfg(target_family = "wasm")]
2mod wasm {
3 use std::io::Write;
4
5 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 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 windows_sys::core::PCSTR;
32 use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE};
33 use windows_sys::Win32::Storage::FileSystem::{
34 CreateFileA, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
35 };
36
37 pub fn print_tty(prompt: impl ToString) -> std::io::Result<()> {
39 let handle = unsafe {
40 CreateFileA(
41 b"CONOUT$\x00".as_ptr() as PCSTR,
42 GENERIC_READ | GENERIC_WRITE,
43 FILE_SHARE_READ | FILE_SHARE_WRITE,
44 std::ptr::null(),
45 OPEN_EXISTING,
46 0,
47 INVALID_HANDLE_VALUE,
48 )
49 };
50 if handle == INVALID_HANDLE_VALUE {
51 return Err(std::io::Error::last_os_error());
52 }
53
54 let mut stream = unsafe { std::fs::File::from_raw_handle(handle as _) };
55
56 stream
57 .write_all(prompt.to_string().as_str().as_bytes())
58 .and_then(|_| stream.flush())
59 }
60}
61
62pub fn print_writer(stream: &mut impl Write, prompt: impl ToString) -> std::io::Result<()> {
64 stream
65 .write_all(prompt.to_string().as_str().as_bytes())
66 .and_then(|_| stream.flush())
67}
68
69use std::io::Write;
70#[cfg(target_family = "unix")]
71pub use unix::print_tty;
72#[cfg(target_family = "wasm")]
73pub use wasm::print_tty;
74#[cfg(target_family = "windows")]
75pub use windows::print_tty;