CArrayString

Enum CArrayString 

Source
pub enum CArrayString<const N: usize> {
    Stack(ArrayString<N>),
    Heap(CString),
}

Variants§

§

Stack(ArrayString<N>)

§

Heap(CString)

Implementations§

Source§

impl<const N: usize> CArrayString<N>

A C-compatible string type that can be stored on the stack or heap.

CArrayString<N> provides a unified abstraction over two storage strategies:

  1. Stack-allocated: Uses ArrayString<N> for small strings that fit into a fixed-size buffer. This avoids heap allocation and is very efficient.
  2. Heap-allocated: Uses CString when the string exceeds the stack buffer, ensuring the string is always valid and null-terminated.

This type guarantees:

  • [as_ptr] always returns a valid, null-terminated C string pointer for the lifetime of self.
  • [as_c_str] always returns a valid CStr reference.

§Stack vs Heap Behavior

When creating a CArrayString via [new], the string is first attempted to be stored on the stack. If it does not fit, it falls back to a heap allocation:

┌───────────────┐
│ Stack Buffer  │  (ArrayString<N>)
└───────────────┘
      │ fits
      └─> use stack

      │ does not fit
      └─> allocate heap (CString)

§Performance Considerations

  • Small strings that fit in the stack buffer avoid heap allocations and are faster.
  • Large strings trigger heap allocation, which may be slower and use more memory.
  • Prefer choosing N large enough for your common use case to minimize heap fallbacks.

§Examples

use std::ffi::CStr;
 
use stack_cstr::CArrayString;

// Small string fits on stack
let stack_str = CArrayString::<16>::new(format_args!("hello"));
assert!(matches!(stack_str, CArrayString::Stack(_)));

// Large string falls back to heap
let heap_str = CArrayString::<4>::new(format_args!("this is too long"));
assert!(matches!(heap_str, CArrayString::Heap(_)));

// Accessing as CStr
let cstr: &CStr = heap_str.as_c_str();
assert_eq!(cstr.to_str().unwrap(), "this is too long");

// Raw pointer for FFI
let ptr = stack_str.as_ptr();
unsafe {
    assert_eq!(CStr::from_ptr(ptr).to_str().unwrap(), "hello");
}
Source

pub fn new(fmt: Arguments<'_>) -> CArrayString<N>

Creates a new C-compatible string using format_args!.

Attempts to store the formatted string in a stack buffer of size N. Falls back to a heap allocation if the string does not fit.

§Parameters
  • fmt: The formatted arguments, typically produced by format_args!.
§Returns

A CArrayString<N> containing the formatted string.

§Notes
  • If the stack buffer overflows or writing fails, the string is stored on the heap.
§Examples
use stack_cstr::CArrayString;

let s = CArrayString::<8>::new(format_args!("hi {}!", "you"));
assert!(s.as_c_str().to_str().unwrap().starts_with("hi"));
Source

pub fn as_ptr(&self) -> *const c_char

Returns a raw pointer to the null-terminated C string.

The pointer is valid for the lifetime of self. This is useful for passing the string to C APIs via FFI.

§Examples
use std::ffi::CStr;
 
use stack_cstr::CArrayString;

let s = CArrayString::<8>::new(format_args!("hello"));
let ptr = s.as_ptr();
unsafe {
    assert_eq!(CStr::from_ptr(ptr).to_str().unwrap(), "hello");
}
Source

pub fn as_c_str(&self) -> &CStr

Returns a reference to the underlying CStr.

Provides safe access to the string as a &CStr without exposing the underlying storage strategy.

§Examples
use std::ffi::CStr;
 
use stack_cstr::CArrayString;

let s = CArrayString::<8>::new(format_args!("hello"));
let cstr: &CStr = s.as_c_str();
assert_eq!(cstr.to_str().unwrap(), "hello");

Trait Implementations§

Source§

impl<const N: usize> Clone for CArrayString<N>

Source§

fn clone(&self) -> CArrayString<N>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<const N: usize> Debug for CArrayString<N>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<const N: usize> From<&CStr> for CArrayString<N>

Source§

fn from(value: &CStr) -> Self

Converts to this type from the input type.
Source§

impl<const N: usize> From<&CString> for CArrayString<N>

Source§

fn from(value: &CString) -> Self

Converts to this type from the input type.
Source§

impl<const N: usize> From<CString> for CArrayString<N>

Source§

fn from(value: CString) -> Self

Converts to this type from the input type.
Source§

impl<const N: usize> Hash for CArrayString<N>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<const N: usize> Ord for CArrayString<N>

Source§

fn cmp(&self, other: &CArrayString<N>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<const N: usize> PartialEq for CArrayString<N>

Source§

fn eq(&self, other: &CArrayString<N>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<const N: usize> PartialOrd for CArrayString<N>

Source§

fn partial_cmp(&self, other: &CArrayString<N>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<const N: usize> TryFrom<&[u8]> for CArrayString<N>

Source§

type Error = CStrError

The type returned in the event of a conversion error.
Source§

fn try_from(value: &[u8]) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<const N: usize> TryFrom<&String> for CArrayString<N>

Source§

type Error = CStrError

The type returned in the event of a conversion error.
Source§

fn try_from(value: &String) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<const N: usize> TryFrom<&str> for CArrayString<N>

Source§

type Error = CStrError

The type returned in the event of a conversion error.
Source§

fn try_from(value: &str) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<const N: usize> Eq for CArrayString<N>

Source§

impl<const N: usize> StructuralPartialEq for CArrayString<N>

Auto Trait Implementations§

§

impl<const N: usize> Freeze for CArrayString<N>

§

impl<const N: usize> RefUnwindSafe for CArrayString<N>

§

impl<const N: usize> Send for CArrayString<N>

§

impl<const N: usize> Sync for CArrayString<N>

§

impl<const N: usize> Unpin for CArrayString<N>

§

impl<const N: usize> UnwindSafe for CArrayString<N>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.