nostd_printf/
lib.rs

1//! # nostd-printf
2//!
3//! Rust crate containing an embedded version of printf which can be used in
4//! `no_std` projects which aren't linked to `libc`.
5#![cfg_attr(not(test), no_std)]
6#![allow(non_camel_case_types)]
7
8include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
9
10// Unit tests
11#[cfg(test)]
12mod tests {
13    use crate::{printf, set_putchar};
14    use {core::ffi::c_char, once_cell::sync::Lazy, std::sync::Mutex};
15
16    static OUTPUT: Lazy<Mutex<String>> = Lazy::new(|| Mutex::new(String::new()));
17
18    #[unsafe(no_mangle)]
19    unsafe extern "C" fn putchar(c: c_char) {
20        let c = c as u8 as char;
21        OUTPUT.lock().unwrap().push(c);
22    }
23
24    fn setup() {
25        OUTPUT.lock().unwrap().clear();
26        unsafe {
27            set_putchar(Some(putchar));
28        }
29    }
30
31    fn expect(expected: &str) {
32        assert_eq!(OUTPUT.lock().unwrap().as_str(), expected);
33    }
34
35    #[test]
36    fn test_printf() {
37        setup();
38        unsafe {
39            printf(c"%s-%d\n".as_ptr(), c"test".as_ptr(), 123);
40            expect("test-123\n");
41        }
42    }
43}