Format string in a fixed-length array instead using dynamic allocator

The code that runs in #[no_std] always has no dynamic allocator available. For such a circumstance, things are getting complex when the user wants to format a string in stack memory.

Is there any handy crate which suitable for this scenario?

1 Like

&mut [u8] has std::io::Write impl so you can write!() to the stack allocated buffer. nvm the trait is not available on no_std.

I'm actually quite surprised about that. Also, fmt is unavailable on #![no_std]. I don't see what the reason for that is – the trivial Write impl for byte slices doesn't require an allocator or an OS, and neither does the formatting infrastructure (since it is a compiler plugin/builtin).

Would it be possible to move write!(), format_args!(), and fmt::Write to core?

They are available in core though, in this case the problem is that &mut [u8] doesn't implement core::fmt::Write/std::fmt::Write, but only std::io::Write. I would use the ArrayString type from the arrayvec crate, it stores its data on the stack and implements core::fmt::Write.

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