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}", unsafe { c"hello world" });
hifmt::println!("c char {:cc}", b'0');
hifmt::println!("debug number {:?}", &&100);
hifmt::println!("default number {}", &200);
let n = 100;
hifmt::println!("default number {n}");
let n = "hell";
hifmt::println!("rust &str {n:rs}");
let mut buf = [0_u8; 100];
hifmt::bprint!(&mut buf, "snprintf rust string {:rs}", "hello world");
hifmt::println!("c str {:cs}", unsafe { core::ffi::CStr::from_ptr(buf.as_ptr().cast::<i8>()) });
//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
Structs§
Traits§
- Formatter
- ToBytes
- ToCStr
- ToChar
- ToDouble
- ToNumber
- 所有数字都按照i64处理, 包括boo,i8,u8,i16,u16,i32,u32,i64,u64,i128,u128.所有浮点数都按照f64处理, 包括f32, f64.所有指针都转换为
*const i8所有无\0结束的字符串都转换为(usize, *const u8). - ToPointer