How to get output length from std::fmt without actually writing (no heap allocation)

My initial thought was:

fn write_len<T: std::fmt::Display>(obj: T) -> usize {
   let mut cursor = Cursor::new(sink());
   write!(cursor, "{obj}").unwrap();
   cursor.position() as usize
}

I suppose I could implement Write on my own type that just tracks the amount of data being written, and ignores the data itself.

But did I miss an obviously better way?

Thank you.

I don't think there is another way. Do note however that Display and Debug impls are not required to format text with the same length every time, so if you are using this to preallocate a buffer, be sure to keep bound checks. In practice almost all Display and Debug impls will always use the same length. The Debug impls for atomics are likely to return different sizes though as the inner value may be changed in between both format calls.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.