Struct std::ffi::CString [] [src]

pub struct CString {
    // some fields omitted
}

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. After being created, a CString predominately inherits all of its methods from the Deref implementation to [libc::c_char]. Note that the underlying array is represented as an array of libc::c_char as opposed to u8. 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

#![feature(libc)] extern crate libc; fn main() { use std::ffi::CString; use libc; extern { fn my_printer(s: *const libc::c_char); } let c_to_print = CString::new("Hello, world!").unwrap(); unsafe { my_printer(c_to_print.as_ptr()); } }
use std::ffi::CString;
use libc;

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

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

Methods

impl CString

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

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

#![feature(libc)] extern crate libc; use std::ffi::CString; extern { fn puts(s: *const libc::c_char); } fn main() { let to_print = CString::new("Hello!").unwrap(); unsafe { puts(to_print.as_ptr()); } }
extern crate libc;
use std::ffi::CString;

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

fn main() {
    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.

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.

unsafe fn from_ptr(ptr: *const c_char) -> CString

Unstable

: recently added

Retakes ownership of a CString that was transferred to C.

The only appropriate argument is a pointer obtained by calling into_ptr. The length of the string will be recalculated using the pointer.

fn into_ptr(self) -> *const c_char

Unstable

: recently added

Transfers ownership of the string to a C caller.

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

Failure to call from_ptr will lead to a memory leak.

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.

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

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

Methods from Deref<Target=CStr>

fn as_ptr(&self) -> *const c_char

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.

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 0-cost cast, but it is planned to alter its definition in the future to perform the length calculation whenever this method is called.

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.

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

Unstable

: recently added

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 0-cost 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.

fn to_string_lossy(&self) -> Cow<str>

Unstable

: recently added

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 0-cost 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.

Trait Implementations

impl Deref for CString

type Target = CStr

fn deref(&self) -> &CStr

impl Debug for CString

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

impl Borrow<CStr> for CString

fn borrow(&self) -> &CStr

Derived Implementations

impl Clone for CString

fn clone(&self) -> CString

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

impl Hash for CString

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

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

impl Ord for CString

fn cmp(&self, __arg_0: &CString) -> Ordering

impl Eq for CString

impl PartialOrd for CString

fn partial_cmp(&self, __arg_0: &CString) -> Option<Ordering>

fn lt(&self, __arg_0: &CString) -> bool

fn le(&self, __arg_0: &CString) -> bool

fn gt(&self, __arg_0: &CString) -> bool

fn ge(&self, __arg_0: &CString) -> bool

impl PartialEq for CString

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

fn ne(&self, __arg_0: &CString) -> bool