Closed dhylands closed 7 years ago
I don't like that we rely on so much C and ffi code. Here's a take on a pure Rust version: https://play.rust-lang.org/?gist=86878f3c929136534a4bf60d8b99a75e&version=stable&backtrace=0 It's failing on edge cases where the buffer is too small, but nothing too bad.
One other thing that would be useful would be to print not only in a full buffer, but in a delimited zone. That would let us print into { "temp": XXXXXX, "time": 1234567 } to just replace the XXXXX part.
Yeah - not a problem. I was just trying to get something working and I was familiar with the printf code. I'll look at your stuff, and I'll dig up some other integer formatting code that I can transform into rust and use instead of the sprintf code.
format_float_into already lets you print into a portion of a buffer (that's what the example I posted does).
I see I forgot to checkin the example code. Anyways, it looked something like this:
fn buf_find(buf: &[u8], needle: &str) -> Option<usize> {
unsafe { str::from_utf8_unchecked(buf) }.find(needle)
}
fn test_num(num: f64) {
let mut buf: [u8; 32] = ['@' as u8; 32];
let tmpl = b"Num: >9999.99<";
let num_tmpl = "9999.99";
buf[0..tmpl.len()].copy_from_slice(tmpl);
let num_idx = buf_find(&buf, num_tmpl).unwrap();
Board::format_float_into(&mut buf[num_idx .. num_idx + num_tmpl.len()], num, 2);
println!("{} compared to: >{:7.2}<", unsafe{str::from_utf8_unchecked(&buf[0 .. tmpl.len()])}, num);
}
fn test_main() {
test_num(0.0);
test_num(123.456);
test_num(-1.1);
test_num(-0.1);
test_num(0.1);
test_num(9999.99);
test_num(9999.999);
}
but I'll rework this into a rust-only solution.
Closing this since we now have an all-rust version.
This is the current output of the examples/format_float_into.rs program: