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#![cfg_attr(feature = "bindings", allow(non_camel_case_types))]
7
8#[cfg(feature = "bindings")]
9include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
10
11// Unit tests
12#[cfg(test)]
13mod tests {
14    use crate::{printf, set_putchar};
15    use {core::ffi::c_char, once_cell::sync::Lazy, std::sync::Mutex};
16
17    static OUTPUT: Lazy<Mutex<String>> = Lazy::new(|| Mutex::new(String::new()));
18
19    #[unsafe(no_mangle)]
20    unsafe extern "C" fn putchar(c: c_char) {
21        let c = c as u8 as char;
22        OUTPUT.lock().unwrap().push(c);
23    }
24
25    fn setup() {
26        OUTPUT.lock().unwrap().clear();
27        unsafe {
28            set_putchar(Some(putchar));
29        }
30    }
31
32    fn expect(expected: &str) {
33        assert_eq!(OUTPUT.lock().unwrap().as_str(), expected);
34    }
35
36    #[test]
37    fn test_printf() {
38        setup();
39        unsafe {
40            printf(c"%s-%d\n".as_ptr(), c"test".as_ptr(), 123);
41            expect("test-123\n");
42        }
43    }
44}