Expand description
hifmt - Format output without Rust code segment in binary
§Design objective:
- The print output depends on the API of C
- Eliminate the dependency on Display/Debug trait.
§Examples
#[link(name = "c")]
extern "C" {
fn dprintf(fd: i32, format: *const u8, ...) -> i32;
#[cfg(not(feature = "nolibc"))]
fn snprintf(buf: *mut u8, size: usize, format: *const u8, ...) -> i32;
}
#[cfg(feature = "nolibc")]
fn write_buf(buf: &[u8]) -> usize {
unsafe { dprintf(1, b"%.*s\0".as_ptr(), buf.len() as i32, buf.as_ptr()) as usize }
}
#[cfg(feature = "nolibc")]
hifmt::make_nolibc_formatter!(write_buf);
hifmt::println!("hello world");
hifmt::println!("signed decimal {:d}", -1);
hifmt::println!("unsigned decimal {:u}", -1);
hifmt::println!("hexadecimal {:x}", -1);
hifmt::println!("pointer {:p}", &1);
hifmt::println!("float {:e}", -1.0);
hifmt::println!("rust &str {:rs}", "hello world");
hifmt::println!("rust &[u8] {:rb}", b"hello world");
hifmt::println!("rust char {:rc}", '中');
hifmt::println!("c str {:cs}", b"hello world\0");
hifmt::println!("c char {:cc}", b'0');
let mut buf = [0_u8; 100];
hifmt::bprint!(&mut buf, "snprintf rust string {:rs}", "hello world");
hifmt::println!("c str {:cs}", &buf);
//test_retn_length
let s = "hello world";
let len = hifmt::bprint!(&mut [], "{:rs}", s);
assert_eq!(len as usize, s.len());
let len = hifmt::print!("{:rs}", s);
assert_eq!(len as usize, s.len());
// test_fat_pointer
let mut buf = [0_u8; 100];
let s = "hello";
let n = s as *const _ as *const u8 as usize;
hifmt::bprint!(&mut buf[0..], "{:p} {:p}", s, s);
let s = format!("0x{:x} 0x{:x}\0", n, n);
assert_eq!(s.as_bytes(), &buf[0..s.len()]);
Macros§
- bprint
- cbprint
- ceprint
- ceprintln
- cprint
- cprintln
- csprint
- eprint
- eprintln
- make_
nolibc_ formatter - feature = “nolibc”
用户必须提供一个字符串输出函数: fn(&u8) -> usize
这里将此输出函数适配到
hifmt::Formatter
用户hifmt::print
系列, 适用于无多线程并发输出场景. - nolibc_
formatter - feature = “nolibc”
用户实现支持hifmt::Formater的类型用于
hifmt::print
系列. 如果打印输出有多线程同步需求,应该完整实现Formatter
接口并接口nolibc_formatter
使用. - println
- sprint