fabricedesre / cc3200-rs

Getting Rust to run on a TI cc3200
Mozilla Public License 2.0
7 stars 2 forks source link

Add format_float_into function for pseudo-floating point formatting #39

Closed dhylands closed 7 years ago

dhylands commented 7 years ago

This is the current output of the examples/format_float_into.rs program:

Num: >   0.00< compared to: >   0.00<
Num: > 123.46< compared to: > 123.46<
Num: >  -1.10< compared to: >  -1.10<
Num: >  -0.10< compared to: >  -0.10<
Num: >   0.10< compared to: >   0.10<
Num: >9999.99< compared to: >9999.99<
Num: >10000.0< compared to: >10000.00<
fabricedesre commented 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.

dhylands commented 7 years ago

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).

dhylands commented 7 years ago

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.

dhylands commented 7 years ago

Closing this since we now have an all-rust version.