/ src / main.rs
main.rs
 1  #![no_std]
 2  #![no_main]
 3  
 4  #![allow(dead_code)]
 5  #![allow(unused)]
 6  
 7  use core::ffi::*;
 8  use core::panic::{PanicInfo};
 9  use core::fmt::{self, Write};
10  
11  #[panic_handler]
12  unsafe fn panic(info: &PanicInfo) -> ! {
13      loop {}
14  }
15  
16  unsafe extern "C" {
17      pub unsafe fn printf(format: *const c_char, ...) -> c_int;
18  }
19  
20  struct Buffer<const N: usize> {
21      buf: [u8; N],
22      pos: usize,
23  }
24  
25  impl<const N: usize> Buffer<N> {
26      fn new() -> Self {
27          Buffer {
28              buf: [0; N],
29              pos: 0,
30          }
31      }
32  }
33  
34  struct StringBuffer<const N: usize> {
35      buffer: Buffer<N>,
36  }
37  
38  impl<const N: usize> StringBuffer<N> {
39      fn new() -> Self {
40          StringBuffer {
41              buffer: Buffer::new(),
42          }
43      }
44  }
45  
46  impl<const N: usize> StringBuffer<N> {
47      fn as_c_str(&mut self) -> *const c_char {
48          if self.buffer.pos < N {
49              self.buffer.buf[self.buffer.pos] = 0;
50          }
51          self.buffer.buf.as_ptr() as *const c_char
52      }
53  }
54  
55  impl<const N: usize> fmt::Write for StringBuffer<N> {
56      fn write_str(&mut self, s: &str) -> fmt::Result {
57          let bytes = s.as_bytes();
58          let remaining = N - self.buffer.pos;
59  
60          if bytes.len() >= remaining {
61              return Err(fmt::Error);
62          }
63  
64          self.buffer.buf[self.buffer.pos..self.buffer.pos + bytes.len()].copy_from_slice(bytes);
65          self.buffer.pos += bytes.len();
66  
67          return Ok(());
68      }
69  }
70  
71  pub mod stdio {
72      #[macro_export]
73      macro_rules! printf {
74          ($($arg:tt)*) => {
75              let mut buffer = StringBuffer::<128>::new();
76              match write!(buffer, $($arg)*) {
77                  Ok(_) => unsafe { printf(buffer.as_c_str()) },
78                  Err(_) => -1,
79              }
80          }
81      }
82  }
83  
84  
85  #[no_mangle]
86  pub unsafe extern "C" fn main(argc: i32, argv: *mut *mut c_char) -> i32 {
87      let test = 1337;
88      printf!("Hello from Rust: {test}!\n{}\n", 42);
89      return 0;
90  }
91