main/
main.rs

1//! No std + No alloc, create a `Box`, format and print it's contents.
2
3#![no_std]
4#![no_main]
5
6use core::fmt::Write;
7
8#[link(name = "c")]
9extern "C" {
10    fn puts(s: *const ()) -> i32;
11}
12
13#[panic_handler]
14fn panic(_panic: &::core::panic::PanicInfo<'_>) -> ! {
15    loop {}
16}
17
18static BOX_STORE: faux_alloc::BoxStore<u32> = faux_alloc::BoxStore::new();
19
20struct CStringFormatter<const SIZE: usize>([u8; SIZE]);
21
22impl<const SIZE: usize> CStringFormatter<SIZE> {
23    fn new() -> Self {
24        Self([b'\0'; SIZE])
25    }
26}
27
28impl<const SIZE: usize> Write for CStringFormatter<SIZE> {
29    fn write_str(&mut self, s: &str) -> core::fmt::Result {
30        for (src, dst) in s.bytes().zip(self.0.iter_mut()).take(SIZE - 1) {
31            *dst = src;
32        }
33        Ok(())
34    }
35}
36
37#[no_mangle]
38pub extern "C" fn main() {
39    let boxed = BOX_STORE.alloc(12).unwrap();
40    let mut string = CStringFormatter::<3>::new();
41    string.write_fmt(format_args!("{}", *boxed)).unwrap();
42    unsafe { puts(string.0.as_ptr().cast()) };
43}