c_string 0.7.0

C string helpers for Rust

Crate c_string [] [src]

This library provides helpers for creating and managing null-terminated strings for use with FFI calls. Most C APIs require that the string being passed to them is null-terminated and many of them allocate and return null-terminated strings, but Rust's built-in string types are not null terminated.

The other problem with translating Rust strings to C strings is that Rust strings can validly contain a NUL byte in the middle of the string (0 is a valid Unicode codepoint). This means that not all Rust strings can actually be translated to C strings.

Managing foreign-allocated C strings

An allocated C string is managed through the type OwnedCString. Values of this type "own" an internal buffer of characters and will call a destructor when the value is dropped.

Creation of a C string

The type CStrBuf is used to adapt string data from Rust for calling C functions that expect a null-terminated string. The conversion constructors of CStrBuf provide various ways to produce C strings, but the conversions can fail due to some of the limitations explained above.

Borrowed C strings

Both OwnedCString and CStrBuf dereference to std::ffi::CStr, an unsized type that asserts the C string requirements when passed or returned by reference. &CStr can be used to encapsulate FFI functions under a safe facade.

An example of creating and using a C string would be:

#![feature(libc)]

extern crate c_string;
extern crate libc;

use c_string::CStrBuf;
use std::ffi::CStr;

fn safe_puts(s: &CStr) {
    unsafe { libc::puts(s.as_ptr()) };
}

fn main() {
    let my_string = "Hello, world!";

    // Allocate the C string with an explicit local that owns the string.
    // The string will be deallocated when `my_c_string` goes out of scope.
    let my_c_string = match CStrBuf::from_str(my_string) {
            Ok(s) => s,
            Err(e) => panic!(e)
        };

    safe_puts(&my_c_string);
}

Macros

c_str!

Produce a CStr reference out of a static string literal.

Structs

CChars

External iterator for C string's bytes.

CStrBuf

An adaptor type to pass C string data to foreign functions.

NulError

Error information about a failed string conversion due to an interior NUL in the source data.

OwnedCString

Representation of an allocated C String.

Functions

libc_free

The deallocation function that delegates to libc::free.

parse_c_multistring

Parses a C "multistring".

Type Definitions

DestroyFn

Signature for deallocation functions used with OwnedCString::new.

c_char