0

I'm trying to format an u64 to a &str, but without dynamically allocating any memory on heap. I want to manually declare a space on stack (e.g., let mut buffer = [0u8; 20] and print the u64 to buffer and get a &str from it with some unsafe.

I tryied write!(&mut buffer[..], "{}", i), but it returns a Result<()> and I couldn't get the length of the formatted string so as to unsafely convert it to &str.

I'm currently straightly coping the implementation of Display for u64 from std library, is there a better way of doing so?

gwy15
  • 23
  • 4

1 Answers1

0

You could use a Cursor:

use std::io::{Write, Cursor};

fn main() {
    let mut cursor = Cursor::new([0u8; 20]);
    let i = 42u64;

    write!(cursor, "{i}").unwrap();
    let pos = cursor.position();
    let buffer = cursor.into_inner();
    let text = std::str::from_utf8(&buffer[..pos as usize]).unwrap();
    println!("{text}");
}

Markus Klein
  • 1,202
  • 12
  • 10
  • Thank you and @Chayim. I did a benchmark with some methods, and here's the results. To format 4096 u64 to &str,`to_string` takes 337us, write to ArrayString takes 137us, coping code from std and suppling a `[0u8; 20]` takes 51us, coping code from std and suppling uninit takes 48us, using Cursor takes 139us (~=ArrayString). I'll go with copying code from std. Thank you guys! – gwy15 Jul 26 '22 at 06:37