stack_cstr/macros.rs
1/// A macro to create a C-compatible string (`&CStr`) with stack allocation fallback.
2///
3/// The `cstr!` macro constructs a [`CArrayString`] with a default internal stack buffer.
4/// If the string does not fit in the stack buffer, it automatically falls back to
5/// allocating a [`CString`] on the heap.
6///
7/// This makes it ergonomic to create FFI-safe strings with minimal overhead.
8/// Short strings will typically stay on the stack, while longer strings automatically
9/// use the heap.
10///
11/// # Syntax
12///
13/// ```ignore
14/// cstr!("format string", args...) // uses default stack size 128
15/// ```
16///
17/// - `"format string", args...`: A format string and its arguments, just like in `format!`.
18///
19/// # Returns
20///
21/// A `CArrayString<128>`, which can be used to obtain:
22/// - a raw pointer (`*const c_char`) via [`CArrayString::as_ptr`]
23/// - a reference to the [`CStr`] via [`CArrayString::as_c_str`]
24///
25/// # Examples
26///
27/// ```
28/// use std::ffi::CStr;
29///
30/// use stack_cstr::cstr;
31///
32/// let s = cstr!("Pi = {:.2}", 3.14159);
33/// assert_eq!(s.as_c_str().to_str().unwrap(), "Pi = 3.14");
34///
35/// unsafe {
36/// // Pass to FFI as *const c_char
37/// let ptr = s.as_ptr();
38/// assert_eq!(CStr::from_ptr(ptr).to_str().unwrap(), "Pi = 3.14");
39/// }
40/// ```
41///
42/// # Notes
43///
44/// - The macro uses a default stack buffer of 128 bytes. Strings that fit in this buffer
45/// do not require heap allocation.
46/// - If the formatted string is too long, the macro falls back to a heap allocation internally.
47/// - The returned type is `CArrayString<128>`. The actual storage may be stack- or heap-based
48/// depending on the string length.
49///
50/// # See also
51///
52/// - [`CArrayString`] for more control over stack/heap allocation.
53#[macro_export]
54macro_rules! cstr {
55 ( $($args:tt)* ) => {
56 $crate::CArrayString::<128>::new(format_args!($($args)*))
57 };
58}