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
impl CString
sourcepub fn new<T>(t: T) -> Result<CString, NulError>
pub fn new<T>(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
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.
sourcepub unsafe fn from_vec_unchecked(v: Vec<u8>) -> CString
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);
}
sourcepub unsafe fn from_raw(ptr: *mut i8) -> CString
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);
}
sourcepub fn into_raw(self) -> *mut i8
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);
}
sourcepub fn into_string(self) -> Result<String, IntoStringError>
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.
sourcepub fn into_bytes(self) -> Vec<u8>
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']);
sourcepub fn into_bytes_with_nul(self) -> Vec<u8>
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']);
sourcepub fn as_bytes(&self) -> &[u8]
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']);
sourcepub fn as_bytes_with_nul(&self) -> &[u8]
pub fn as_bytes_with_nul(&self) -> &[u8]
Methods from Deref<Target = CStr>§
sourcepub fn as_ptr(&self) -> *const i8
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;
}
sourcepub fn to_bytes(&self) -> &[u8]
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");
sourcepub fn to_bytes_with_nul(&self) -> &[u8]
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");
sourcepub fn to_str(&self) -> Result<&str, Utf8Error>
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"));
sourcepub fn to_string_lossy(&self) -> Cow<'_, str>
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 Ord for CString
impl Ord for CString
source§impl PartialEq for CString
impl PartialEq for CString
source§impl PartialOrd for CString
impl PartialOrd for CString
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read more