console.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. use core::{
  2. fmt::{self, Write},
  3. str::FromStr,
  4. };
  5. use log::{Level, LevelFilter};
  6. use spin::Mutex;
  7. use uart16550::Uart16550;
  8. #[doc(hidden)]
  9. pub enum MachineConsole {
  10. Uart16550(*const Uart16550<u8>),
  11. }
  12. impl fmt::Write for MachineConsole {
  13. #[inline]
  14. fn write_str(&mut self, s: &str) -> fmt::Result {
  15. let mut bytes = s.as_bytes();
  16. match self {
  17. Self::Uart16550(uart16550) => {
  18. while !bytes.is_empty() {
  19. let count = unsafe { &**uart16550 }.write(bytes);
  20. bytes = &bytes[count..];
  21. }
  22. }
  23. }
  24. Ok(())
  25. }
  26. }
  27. unsafe impl Send for MachineConsole {}
  28. unsafe impl Sync for MachineConsole {}
  29. #[doc(hidden)]
  30. pub static CONSOLE: Mutex<MachineConsole> =
  31. Mutex::new(MachineConsole::Uart16550(0x10000000 as *const _));
  32. pub fn init() {
  33. log::set_max_level(
  34. option_env!("RUST_LOG")
  35. .and_then(|s| LevelFilter::from_str(s).ok())
  36. .unwrap_or(LevelFilter::Info),
  37. );
  38. log::set_logger(&Logger).unwrap();
  39. }
  40. struct Logger;
  41. impl log::Log for Logger {
  42. #[inline]
  43. fn enabled(&self, _metadata: &log::Metadata) -> bool {
  44. true
  45. }
  46. #[inline]
  47. fn log(&self, record: &log::Record) {
  48. let color_code: u8 = match record.level() {
  49. Level::Error => 31,
  50. Level::Warn => 93,
  51. Level::Info => 34,
  52. Level::Debug => 32,
  53. Level::Trace => 90,
  54. };
  55. println!(
  56. "\x1b[{color_code}m[{:>5}] {}\x1b[0m",
  57. record.level(),
  58. record.args(),
  59. );
  60. }
  61. fn flush(&self) {}
  62. }
  63. // pub fn load_console_uart16550(uart16550: &Uart16550<u8>) {
  64. // let mut console = CONSOLE.lock();
  65. // *console = MachineConsole::Uart16550(uart16550);
  66. // drop(console);
  67. // }