pub struct CStrStack<const N: usize> { /* private fields */ }Expand description
A stack-allocated C string with a fixed buffer size.
CStrStack<N> stores a formatted string directly on the stack
with a buffer of N bytes, avoiding heap allocation.
It always appends a trailing \0 (null terminator) so it can be safely
passed to C FFI functions.
If the formatted string (plus the null terminator) does not fit
into the buffer, [new] will return an error.
§Examples
use std::ffi::CStr;
use stack_cstr::{CStrStack, CStrLike};
// Create a stack-allocated C string with capacity for 32 bytes
let s = CStrStack::<32>::new(format_args!("Hello {}", 123)).unwrap();
let cstr: &CStr = s.as_cstr();
assert_eq!(cstr.to_str().unwrap(), "Hello 123");
unsafe {
// FFI-safe pointer
assert_eq!(CStr::from_ptr(s.as_ptr()).to_str().unwrap(), "Hello 123");
}§Errors
Returns Err("stack buffer overflow") if the formatted string is too
long to fit in the buffer.
Returns Err("format failed") if formatting the string fails
(rare case, usually only if the formatter writes an error).
Implementations§
Source§impl<const N: usize> CStrStack<N>
impl<const N: usize> CStrStack<N>
Sourcepub fn new(fmt: Arguments<'_>) -> Result<CStrStack<N>, &'static str>
pub fn new(fmt: Arguments<'_>) -> Result<CStrStack<N>, &'static str>
Creates a new stack-allocated C string using a format_args! expression.
The string is written into an internal buffer of size N.
If the string does not fit, returns an error.