CStringArray

Struct CStringArray 

Source
pub struct CStringArray { /* private fields */ }
Expand description

Safe wrapper for passing string arrays to C FFI as char**.

This structure provides a safe abstraction over the common C pattern of null-terminated arrays of strings (char**), often used for command-line arguments (argv).

§Memory Safety

  • Guarantees proper memory layout compatible with C’s char**
  • Automatically manages lifetime of all C strings
  • Ensures null-termination of the pointer array
  • Prevents dangling pointers through RAII
  • Zero-copy when constructed from Vec<CString>

§Example

use std::ffi::c_char;

use cstring_array::CStringArray;

let args = vec![
    "program".to_string(),
    "--verbose".to_string(),
    "file.txt".to_string(),
];
let array = CStringArray::new(args).unwrap();

// Safe to pass to C FFI
let ptr: *const *const c_char = array.as_ptr();
assert_eq!(array.len(), 3);

Implementations§

Source§

impl CStringArray

Source

pub fn new(strings: Vec<String>) -> Result<Self, CStringArrayError>

Creates a new CStringArray from a vector of strings.

§Arguments
  • strings - Vector of strings to convert into C-compatible format
§Errors

Returns CStringArrayError::NulError if any string contains an interior null byte. Returns CStringArrayError::EmptyArray if the input vector is empty.

§Example
use cstring_array::CStringArray;

let args = vec!["foo".to_string(), "bar".to_string()];
let array = CStringArray::new(args).unwrap();
assert_eq!(array.len(), 2);
Source

pub fn from_cstrings(strings: Vec<CString>) -> Result<Self, CStringArrayError>

Creates a new CStringArray from a vector of CStrings (zero-copy).

This is the most efficient constructor as it takes ownership of already-allocated CString instances without re-allocation.

§Arguments
  • strings - Vector of CString instances
§Errors

Returns CStringArrayError::EmptyArray if the input vector is empty.

§Example
use std::ffi::CString;

use cstring_array::CStringArray;

let cstrings = vec![
    CString::new("hello").unwrap(),
    CString::new("world").unwrap(),
];
let array = CStringArray::from_cstrings(cstrings).unwrap();
assert_eq!(array.len(), 2);
Source

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

Returns a pointer suitable for passing to C functions expecting char**.

The returned pointer is valid for the lifetime of this CStringArray. The pointer array is null-terminated as required by C conventions.

§Safety

The caller must ensure that:

  • The pointer is not used after this CStringArray is dropped
  • The pointer is not used to modify the strings (use as_mut_ptr for that)
§Example
use std::ffi::c_char;

use cstring_array::CStringArray;

let array = CStringArray::new(vec!["test".to_string()]).unwrap();
let ptr: *const *const c_char = array.as_ptr();

// Safe to pass to C FFI functions like execve, etc.
Source

pub fn as_mut_ptr(&mut self) -> *mut *const c_char

Returns a mutable pointer suitable for C functions expecting char**.

§Safety

The caller must ensure that:

  • The pointer is not used after this CStringArray is dropped
  • C code does not replace pointers in the array (undefined behavior)
  • C code only modifies string contents, not pointer values
§Example
use std::ffi::c_char;

use cstring_array::CStringArray;

let mut array = CStringArray::new(vec!["test".to_string()]).unwrap();
let ptr: *mut *const c_char = array.as_mut_ptr();
Source

pub fn len(&self) -> usize

Returns the number of strings in the array.

This count does not include the null terminator.

§Example
use cstring_array::CStringArray;

let array = CStringArray::new(vec!["a".to_string(), "b".to_string()]).unwrap();
assert_eq!(array.len(), 2);
Source

pub fn is_empty(&self) -> bool

Returns true if the array contains no strings.

Note: Due to the constructor constraints, this will always return false for successfully constructed instances, but is provided for completeness.

§Example
use cstring_array::CStringArray;

let array = CStringArray::new(vec!["x".to_string()]).unwrap();
assert!(!array.is_empty());
Source

pub fn get(&self, index: usize) -> Option<&CString>

Returns a reference to the underlying CString at the specified index.

§Arguments
  • index - The index of the string to retrieve
§Returns

Returns Some(&CString) if the index is valid, None otherwise.

§Example
use cstring_array::CStringArray;

let array = CStringArray::new(vec!["first".to_string(), "second".to_string()]).unwrap();
assert_eq!(array.get(0).unwrap().to_str().unwrap(), "first");
assert_eq!(array.get(1).unwrap().to_str().unwrap(), "second");
assert!(array.get(2).is_none());
Source

pub fn iter(&self) -> Iter<'_, CString>

Returns an iterator over the CString references.

§Example
use cstring_array::CStringArray;

let array = CStringArray::new(vec!["a".to_string(), "b".to_string()]).unwrap();
let strings: Vec<_> = array.iter().collect();
assert_eq!(strings.len(), 2);
Source

pub fn as_slice(&self) -> &[CString]

Returns a slice of the underlying CString array.

§Example
use cstring_array::CStringArray;

let array = CStringArray::new(vec!["a".to_string()]).unwrap();
let slice = array.as_slice();
assert_eq!(slice.len(), 1);
Source

pub fn into_strings(self) -> Vec<CString>

Consumes the array and returns the underlying vector of CStrings.

§Example
use cstring_array::CStringArray;

let array = CStringArray::new(vec!["test".to_string()]).unwrap();
let strings = array.into_strings();
assert_eq!(strings.len(), 1);

Trait Implementations§

Source§

impl AsRef<[CString]> for CStringArray

Source§

fn as_ref(&self) -> &[CString]

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for CStringArray

Source§

fn clone(&self) -> Self

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 Debug for CStringArray

Source§

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

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

impl Drop for CStringArray

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl FromIterator<CString> for CStringArray

Source§

fn from_iter<I: IntoIterator<Item = CString>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl FromIterator<String> for CStringArray

Source§

fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl Hash for CStringArray

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 Index<usize> for CStringArray

Source§

type Output = CString

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a> IntoIterator for &'a CStringArray

Source§

type Item = &'a CString

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, CString>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl IntoIterator for CStringArray

Source§

type Item = CString

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<CString>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for CStringArray

Source§

fn eq(&self, other: &Self) -> 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> TryFrom<[&str; N]> for CStringArray

Source§

fn try_from(strings: [&str; N]) -> Result<Self, Self::Error>

Converts an array of string slices into a CStringArray.

§Errors

Returns an error if any string contains an interior null byte or if the array is empty.

§Example
use std::convert::TryFrom;

use cstring_array::CStringArray;

let strings = ["hello", "world"];
let array = CStringArray::try_from(strings).unwrap();
assert_eq!(array.len(), 2);
Source§

type Error = CStringArrayError

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

impl<const N: usize> TryFrom<[String; N]> for CStringArray

Source§

fn try_from(strings: [String; N]) -> Result<Self, Self::Error>

Converts an array of Strings into a CStringArray.

§Errors

Returns an error if any string contains an interior null byte or if the array is empty.

§Example
use std::convert::TryFrom;

use cstring_array::CStringArray;

let strings = ["hello".to_string(), "world".to_string()];
let array = CStringArray::try_from(strings).unwrap();
assert_eq!(array.len(), 2);
Source§

type Error = CStringArrayError

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

impl TryFrom<Vec<&str>> for CStringArray

Source§

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

Converts a Vec<&str> into a CStringArray.

§Errors

Returns an error if any string contains an interior null byte or if the vector is empty.

§Example
use std::convert::TryFrom;

use cstring_array::CStringArray;

let strings = vec!["hello", "world"];
let array = CStringArray::try_from(strings).unwrap();
assert_eq!(array.len(), 2);
Source§

type Error = CStringArrayError

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

impl TryFrom<Vec<CString>> for CStringArray

Source§

fn try_from(strings: Vec<CString>) -> Result<Self, Self::Error>

Converts a Vec<CString> into a CStringArray (zero-copy).

§Errors

Returns an error if the vector is empty.

§Example
use std::{convert::TryFrom, ffi::CString};

use cstring_array::CStringArray;

let cstrings = vec![
    CString::new("hello").unwrap(),
    CString::new("world").unwrap(),
];
let array = CStringArray::try_from(cstrings).unwrap();
assert_eq!(array.len(), 2);
Source§

type Error = CStringArrayError

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

impl TryFrom<Vec<String>> for CStringArray

Source§

fn try_from(strings: Vec<String>) -> Result<Self, Self::Error>

Converts a Vec<String> into a CStringArray.

§Errors

Returns an error if any string contains an interior null byte or if the vector is empty.

§Example
use std::convert::TryFrom;

use cstring_array::CStringArray;

let strings = vec!["hello".to_string(), "world".to_string()];
let array = CStringArray::try_from(strings).unwrap();
assert_eq!(array.len(), 2);
Source§

type Error = CStringArrayError

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

impl Eq for CStringArray

Source§

impl Send for CStringArray

Source§

impl Sync for CStringArray

Auto Trait Implementations§

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.