starina_api/
print.rs

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! Low-level printing utilities.
//!
//! # Prefer [`mod@crate::log`] over `print!`
//!
//! This module is a low-level utilities for [`mod@crate::log`] module. Use [`mod@crate::log`]
//! instead of this module.
use alloc::string::String;

use spin::Mutex;

use crate::syscall;

const MAX_BUFFER_SIZE: usize = 1024;

pub static GLOBAL_PRINTER: Mutex<Printer> = Mutex::new(Printer {
    buffer: String::new(),
});

pub struct Printer {
    buffer: String,
}

impl core::fmt::Write for Printer {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        for c in s.chars() {
            if c == '\n' || self.buffer.len() >= MAX_BUFFER_SIZE {
                let _ = syscall::console_write(self.buffer.as_bytes());
                self.buffer.clear();
            } else {
                self.buffer.push(c);
            }
        }

        Ok(())
    }
}

/// Prints a string without a newline.
#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => {{
        #![allow(unused_imports)]
        use core::fmt::Write;

        let mut printer = $crate::print::GLOBAL_PRINTER.lock();
        write!(printer, $($arg)*).ok();
    }};
}

/// Prints a string and a newline.
#[macro_export]
macro_rules! println {
    () => {{
        $crate::print!(
            "\n"
        );
    }};
    ($fmt:expr) => {{
        $crate::print!(
            concat!($fmt, "\n")
        );
    }};
    ($fmt:expr, $($arg:tt)*) => {{
        $crate::print!(
            concat!($fmt, "\n"),
            $($arg)*
        );
    }};
}