stack_cstr/
cstr_like.rs

1use std::ffi::{CStr, c_char};
2
3/// A common interface for C-compatible string types used in this crate.
4///
5/// `CStrLike` abstracts over different string storage strategies
6/// (e.g. stack-allocated and heap-allocated C strings) so they can
7/// be used interchangeably.
8///
9/// Types that implement this trait guarantee:
10/// - The returned pointer from [`as_ptr`] is a valid, null-terminated
11///   C string for as long as the implementor is alive.
12/// - The returned [`CStr`] reference from [`as_cstr`] is always valid.
13///
14/// This trait is mainly intended to unify [`CStrHeap`] (heap-allocated)
15/// and `CStrStack<N>` (stack-allocated with a fixed buffer).
16///
17/// # Examples
18///
19/// ```
20/// use std::ffi::{CString, CStr};
21/// use stack_cstr::{CStrHeap, CStrLike};
22///
23/// let cstr = CString::new("hello").unwrap();
24/// let heap = CStrHeap::new(cstr);
25///
26/// // Use the trait methods
27/// let ptr = heap.as_ptr();
28/// let slice: &CStr = heap.as_cstr();
29///
30/// assert_eq!(slice.to_str().unwrap(), "hello");
31/// unsafe {
32///     assert_eq!(CStr::from_ptr(ptr).to_str().unwrap(), "hello");
33/// }
34/// ```
35pub trait CStrLike {
36    /// Returns a raw pointer to the null-terminated C string.
37    ///
38    /// The pointer is valid as long as `self` is alive.  
39    /// This is mainly intended for FFI calls.
40    fn as_ptr(&self) -> *const c_char;
41
42    /// Returns a reference to the underlying [`CStr`].
43    fn as_cstr(&self) -> &CStr;
44}