Struct ndless::ffi::CString

source ·
pub struct CString { /* private fields */ }
Expand description

A type representing an owned C-compatible string.

This type serves the primary purpose of being able to safely generate a C-compatible string from a Rust byte slice or vector. An instance of this type is a static guarantee that the underlying bytes contain no interior 0 bytes and the final byte is 0.

A CString is created from either a byte slice or a byte vector. A u8 slice can be obtained with the as_bytes method. Slices produced from a CString do not contain the trailing nul terminator unless otherwise specified.

§Examples

use cstr_core::CString;
use cstr_core::c_char;

extern {
    fn my_printer(s: *const c_char);
}

let c_to_print = CString::new("Hello, world!").unwrap();
unsafe {
    my_printer(c_to_print.as_ptr());
}

§Safety

CString is intended for working with traditional C-style strings (a sequence of non-null bytes terminated by a single null byte); the primary use case for these kinds of strings is interoperating with C-like code. Often you will need to transfer ownership to/from that external code. It is strongly recommended that you thoroughly read through the documentation of CString before use, as improper ownership management of CString instances can lead to invalid memory accesses, memory leaks, and other memory errors.

Implementations§

source§

impl CString

source

pub fn new<T>(t: T) -> Result<CString, NulError>
where T: Into<Vec<u8>>,

Creates a new C-compatible string from a container of bytes.

This method will consume the provided data and use the underlying bytes to construct a new string, ensuring that there is a trailing 0 byte.

§Examples
use cstr_core::CString;
use cstr_core::c_char;

extern { fn puts(s: *const c_char); }

let to_print = CString::new("Hello!").unwrap();
unsafe {
    puts(to_print.as_ptr());
}
§Errors

This function will return an error if the bytes yielded contain an internal 0 byte. The error returned will contain the bytes as well as the position of the nul byte.

source

pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> CString

Creates a C-compatible string from a byte vector without checking for interior 0 bytes.

This method is equivalent to new except that no runtime assertion is made that v contains no 0 bytes, and it requires an actual byte vector, not anything that can be converted to one with Into.

§Examples
use cstr_core::CString;

let raw = b"foo".to_vec();
unsafe {
    let c_string = CString::from_vec_unchecked(raw);
}
source

pub unsafe fn from_raw(ptr: *mut i8) -> CString

Retakes ownership of a CString that was transferred to C.

Additionally, the length of the string will be recalculated from the pointer.

§Safety

This should only ever be called with a pointer that was earlier obtained by calling into_raw on a CString. Other usage (e.g. trying to take ownership of a string that was allocated by foreign code) is likely to lead to undefined behavior or allocator corruption.

§Examples

Create a CString, pass ownership to an extern function (via raw pointer), then retake ownership with from_raw:

use cstr_core::CString;
use cstr_core::c_char;

extern {
    fn some_extern_function(s: *mut c_char);
}

let c_string = CString::new("Hello!").unwrap();
let raw = c_string.into_raw();
unsafe {
    some_extern_function(raw);
    let c_string = CString::from_raw(raw);
}
source

pub fn into_raw(self) -> *mut i8

Transfers ownership of the string to a C caller.

The pointer must be returned to Rust and reconstituted using from_raw to be properly deallocated. Specifically, one should not use the standard C free function to deallocate this string.

Failure to call from_raw will lead to a memory leak.

§Examples
use cstr_core::CString;

let c_string = CString::new("foo").unwrap();

let ptr = c_string.into_raw();

unsafe {
    assert_eq!(b'f', *ptr as u8);
    assert_eq!(b'o', *ptr.offset(1) as u8);
    assert_eq!(b'o', *ptr.offset(2) as u8);
    assert_eq!(b'\0', *ptr.offset(3) as u8);

    // retake pointer to free memory
    let _ = CString::from_raw(ptr);
}
source

pub fn into_string(self) -> Result<String, IntoStringError>

Converts the CString into a String if it contains valid Unicode data.

On failure, ownership of the original CString is returned.

source

pub fn into_bytes(self) -> Vec<u8>

Returns the underlying byte buffer.

The returned buffer does not contain the trailing nul separator and it is guaranteed to not have any interior nul bytes.

§Examples
use cstr_core::CString;

let c_string = CString::new("foo").unwrap();
let bytes = c_string.into_bytes();
assert_eq!(bytes, vec![b'f', b'o', b'o']);
source

pub fn into_bytes_with_nul(self) -> Vec<u8>

Equivalent to the into_bytes function except that the returned vector includes the trailing nul byte.

§Examples
use cstr_core::CString;

let c_string = CString::new("foo").unwrap();
let bytes = c_string.into_bytes_with_nul();
assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
source

pub fn as_bytes(&self) -> &[u8]

Returns the contents of this CString as a slice of bytes.

The returned slice does not contain the trailing nul separator and it is guaranteed to not have any interior nul bytes.

§Examples
use cstr_core::CString;

let c_string = CString::new("foo").unwrap();
let bytes = c_string.as_bytes();
assert_eq!(bytes, &[b'f', b'o', b'o']);
source

pub fn as_bytes_with_nul(&self) -> &[u8]

Equivalent to the as_bytes function except that the returned slice includes the trailing nul byte.

§Examples
use cstr_core::CString;

let c_string = CString::new("foo").unwrap();
let bytes = c_string.as_bytes_with_nul();
assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
source

pub fn as_c_str(&self) -> &CStr

Extracts a CStr slice containing the entire string.

§Examples
use cstr_core::{CString, CStr};

let c_string = CString::new(b"foo".to_vec()).unwrap();
let c_str = c_string.as_c_str();
assert_eq!(c_str, CStr::from_bytes_with_nul(b"foo\0").unwrap());
source

pub fn into_boxed_c_str(self) -> Box<CStr>

Converts this CString into a boxed CStr.

§Examples
use cstr_core::{CString, CStr};

let c_string = CString::new(b"foo".to_vec()).unwrap();
let boxed = c_string.into_boxed_c_str();
assert_eq!(&*boxed, CStr::from_bytes_with_nul(b"foo\0").unwrap());

Methods from Deref<Target = CStr>§

source

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

Returns the inner pointer to this C string.

The returned pointer will be valid for as long as self is and points to a contiguous region of memory terminated with a 0 byte to represent the end of the string.

WARNING

It is your responsibility to make sure that the underlying memory is not freed too early. For example, the following code will cause undefined behavior when ptr is used inside the unsafe block:

use cstr_core::{CString};

let ptr = CString::new("Hello").unwrap().as_ptr();
unsafe {
    // `ptr` is dangling
    *ptr;
}

This happens because the pointer returned by as_ptr does not carry any lifetime information and the string is deallocated immediately after the CString::new("Hello").unwrap().as_ptr() expression is evaluated. To fix the problem, bind the string to a local variable:

use cstr_core::{CString};

let hello = CString::new("Hello").unwrap();
let ptr = hello.as_ptr();
unsafe {
    // `ptr` is valid because `hello` is in scope
    *ptr;
}
source

pub fn to_bytes(&self) -> &[u8]

Converts this C string to a byte slice.

This function will calculate the length of this string (which normally requires a linear amount of work to be done) and then return the resulting slice of u8 elements.

The returned slice will not contain the trailing nul that this C string has.

Note: This method is currently implemented as a constant-time cast, but it is planned to alter its definition in the future to perform the length calculation whenever this method is called.

§Examples
use cstr_core::CStr;

let c_str = CStr::from_bytes_with_nul(b"foo\0").unwrap();
assert_eq!(c_str.to_bytes(), b"foo");
source

pub fn to_bytes_with_nul(&self) -> &[u8]

Converts this C string to a byte slice containing the trailing 0 byte.

This function is the equivalent of to_bytes except that it will retain the trailing nul instead of chopping it off.

Note: This method is currently implemented as a 0-cost cast, but it is planned to alter its definition in the future to perform the length calculation whenever this method is called.

§Examples
use cstr_core::CStr;

let c_str = CStr::from_bytes_with_nul(b"foo\0").unwrap();
assert_eq!(c_str.to_bytes_with_nul(), b"foo\0");
source

pub fn to_str(&self) -> Result<&str, Utf8Error>

Yields a &str slice if the CStr contains valid UTF-8.

This function will calculate the length of this string and check for UTF-8 validity, and then return the &str if it’s valid.

Note: This method is currently implemented to check for validity after a constant-time cast, but it is planned to alter its definition in the future to perform the length calculation in addition to the UTF-8 check whenever this method is called.

§Examples
use cstr_core::CStr;

let c_str = CStr::from_bytes_with_nul(b"foo\0").unwrap();
assert_eq!(c_str.to_str(), Ok("foo"));
source

pub fn to_string_lossy(&self) -> Cow<'_, str>

Converts a CStr into a Cow<str>.

This function will calculate the length of this string (which normally requires a linear amount of work to be done) and then return the resulting slice as a Cow<str>, replacing any invalid UTF-8 sequences with U+FFFD REPLACEMENT CHARACTER.

Note: This method is currently implemented to check for validity after a constant-time cast, but it is planned to alter its definition in the future to perform the length calculation in addition to the UTF-8 check whenever this method is called.

§Examples

Calling to_string_lossy on a CStr containing valid UTF-8:

use std::borrow::Cow;
use cstr_core::CStr;

let c_str = CStr::from_bytes_with_nul(b"Hello World\0").unwrap();
assert_eq!(c_str.to_string_lossy(), Cow::Borrowed("Hello World"));

Calling to_string_lossy on a CStr containing invalid UTF-8:

use std::borrow::Cow;
use cstr_core::CStr;

let c_str = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0").unwrap();
assert_eq!(
    c_str.to_string_lossy(),
    Cow::Owned(String::from("Hello �World")) as Cow<str>
);

Trait Implementations§

source§

impl AsRef<CStr> for CString

source§

fn as_ref(&self) -> &CStr

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

impl Borrow<CStr> for CString

source§

fn borrow(&self) -> &CStr

Immutably borrows from an owned value. Read more
source§

impl Clone for CString

source§

fn clone(&self) -> CString

Returns a copy 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 CString

source§

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

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

impl Default for CString

source§

fn default() -> CString

Creates an empty CString.

source§

impl Deref for CString

§

type Target = CStr

The resulting type after dereferencing.
source§

fn deref(&self) -> &CStr

Dereferences the value.
source§

impl Drop for CString

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a> From<&'a CStr> for CString

source§

fn from(s: &'a CStr) -> CString

Converts to this type from the input type.
source§

impl From<Box<CStr>> for CString

source§

fn from(s: Box<CStr>) -> CString

Converts to this type from the input type.
source§

impl From<CString> for Box<CStr>

source§

fn from(s: CString) -> Box<CStr>

Converts to this type from the input type.
source§

impl From<CString> for Vec<u8>

source§

fn from(s: CString) -> Vec<u8>

Converts to this type from the input type.
source§

impl Hash for CString

source§

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

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<RangeFull> for CString

§

type Output = CStr

The returned type after indexing.
source§

fn index(&self, _index: RangeFull) -> &CStr

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

impl Ord for CString

source§

fn cmp(&self, other: &CString) -> 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 + PartialOrd,

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

impl PartialEq for CString

source§

fn eq(&self, other: &CString) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for CString

source§

fn partial_cmp(&self, other: &CString) -> 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

This method 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

This method 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

This method 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

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Eq for CString

source§

impl StructuralPartialEq for CString

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> 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,

§

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>,

§

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>,

§

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.