os/util/
stdio.rs

1//! 标准输入输出工具模块
2
3use core::fmt::{self, Write};
4
5use alloc::string::{String, ToString};
6
7use crate::device::console::MAIN_CONSOLE;
8
9pub struct Stdout;
10pub struct Stdin;
11
12pub fn console_putchar(c: usize) {
13    MAIN_CONSOLE
14        .read()
15        .as_ref()
16        .unwrap()
17        .write_str(&(c as u8 as char).to_string());
18}
19
20/// 使用 sbi 调用从控制台获取字符(qemu uart handler)
21/// 返回值:字符的 ASCII 码
22pub fn console_getchar() -> usize {
23    MAIN_CONSOLE.read().as_ref().unwrap().read_char() as usize
24}
25
26impl Write for Stdout {
27    fn write_str(&mut self, s: &str) -> fmt::Result {
28        MAIN_CONSOLE.read().as_ref().unwrap().write_str(s);
29        Ok(())
30    }
31}
32
33impl Stdin {
34    pub fn read_char(&mut self) -> char {
35        MAIN_CONSOLE.read().as_ref().unwrap().read_char()
36    }
37
38    pub fn read_line(&mut self, buf: &mut String) {
39        MAIN_CONSOLE.read().as_ref().unwrap().read_line(buf);
40    }
41}
42
43pub(crate) fn print(args: fmt::Arguments) {
44    Stdout.write_fmt(args).unwrap();
45}
46
47pub fn stdin() -> Stdin {
48    Stdin
49}
50
51/// 打印格式化文本到控制台
52///
53/// 这个宏类似于标准库的 `print!` 宏,但使用 SBI 调用将文本输出到控制台。
54/// 它不会在末尾添加换行符。
55///
56/// # Examples
57///
58/// ```ignore
59/// print!("Hello, world!");
60/// print!("The answer is {}", 42);
61/// ```
62#[cfg(not(test))]
63#[macro_export]
64macro_rules! print {
65    ($fmt: literal $(, $($arg: tt)+)?) => {
66        $crate::tool::stdio::print(format_args!($fmt $(, $($arg)+)?))
67    }
68}
69
70/// 打印格式化文本到控制台并添加换行符
71///
72/// 这个宏类似于标准库的 `println!` 宏,但使用 SBI 调用将文本输出到控制台。
73/// 它会在末尾自动添加换行符。
74///
75/// # Examples
76///
77/// ```ignore
78/// println!("Hello, world!");
79/// println!("The answer is {}", 42);
80/// ```
81#[cfg(not(test))]
82#[macro_export]
83macro_rules! println {
84    ($fmt: literal $(, $($arg: tt)+)?) => {
85        $crate::util::stdio::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?))
86    }
87}
88
89#[cfg(test)]
90#[macro_export]
91/// 测试环境下的打印宏
92macro_rules! println {
93    ($fmt: literal $(, $($arg: tt)+)?) => {
94        $crate::arch::lib::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?))
95    }
96}
97
98#[cfg(test)]
99#[macro_export]
100/// 测试环境下的打印宏
101macro_rules! print {
102    ($fmt: literal $(, $($arg: tt)+)?) => {
103        $crate::arch::lib::console::print(format_args!($fmt $(, $($arg)+)?))
104    }
105}