Struct CStr
struct CStr { ... }
A dynamically-sized view of a C string.
The type &CStr represents a reference to a borrowed nul-terminated
array of bytes. It can be constructed safely from a &[[u8]]
slice, or unsafely from a raw *const c_char. It can be expressed as a
literal in the form c"Hello world".
The &CStr can then be converted to a Rust &str by performing
UTF-8 validation, or into an owned CString.
&CStr is to CString as &str is to String: the former
in each pair are borrowing references; the latter are owned
strings.
Note that this structure does not have a guaranteed layout (the repr(transparent)
notwithstanding) and should not be placed in the signatures of FFI functions.
Instead, safe wrappers of FFI functions may leverage CStr::as_ptr and the unsafe
CStr::from_ptr constructor to provide a safe interface to other consumers.
Examples
Inspecting a foreign C string:
use CStr;
use c_char;
# /* Extern functions are awkward in doc comments - fake it instead
extern "C" { fn my_string() -> *const c_char; }
# */ unsafe extern "C" *const c_char
unsafe
Passing a Rust-originating C string:
use CStr;
use c_char;
let s = c"Hello world!";
work;
Converting a foreign C string into a Rust String:
use CStr;
use c_char;
# /* Extern functions are awkward in doc comments - fake it instead
extern "C" { fn my_string() -> *const c_char; }
# */ unsafe extern "C" *const c_char
println!;
Implementations
impl CStr
unsafe const fn from_ptr<'a>(ptr: *const c_char) -> &'a CStrWraps a raw C string with a safe C string wrapper.
This function will wrap the provided
ptrwith aCStrwrapper, which allows inspection and interoperation of non-owned C strings. The total size of the terminated buffer must be smaller thanisize::MAXbytes in memory (a restriction fromslice::from_raw_parts).Safety
-
The memory pointed to by
ptrmust contain a valid nul terminator at the end of the string. -
ptrmust be valid for reads of bytes up to and including the nul terminator. This means in particular:- The entire memory range of this
CStrmust be contained within a single allocation! ptrmust be non-null even for a zero-length cstr.
- The entire memory range of this
-
The memory referenced by the returned
CStrmust not be mutated for the duration of lifetime'a. -
The nul terminator must be within
isize::MAXfromptr
Note: This operation is intended to be a 0-cost cast but it is currently implemented with an up-front calculation of the length of the string. This is not guaranteed to always be the case.
Caveat
The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse, it's suggested to tie the lifetime to whichever source lifetime is safe in the context, such as by providing a helper function taking the lifetime of a host value for the slice, or by explicit annotation.
Examples
use ; *const c_char unsafeuse ; const HELLO_PTR: *const c_char = ; const HELLO: &CStr = unsafe ; assert_eq!;-
const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError>Creates a C string wrapper from a byte slice with any number of nuls.
This method will create a
CStrfrom any byte slice that contains at least one nul byte. Unlike withCStr::from_bytes_with_nul, the caller does not need to know where the nul byte is located.If the first byte is a nul character, this method will return an empty
CStr. If multiple nul characters are present, theCStrwill end at the first one.If the slice only has a single nul byte at the end, this method is equivalent to
CStr::from_bytes_with_nul.Examples
use CStr; let mut buffer = ; unsafe // Attempt to extract a C nul-terminated string from the buffer. let c_str = from_bytes_until_nul.unwrap; assert_eq!;const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError>Creates a C string wrapper from a byte slice with exactly one nul terminator.
This function will cast the provided
bytesto aCStrwrapper after ensuring that the byte slice is nul-terminated and does not contain any interior nul bytes.If the nul byte may not be at the end,
CStr::from_bytes_until_nulcan be used instead.Examples
use CStr; let cstr = from_bytes_with_nul; assert_eq!;Creating a
CStrwithout a trailing nul terminator is an error:use ; let cstr = from_bytes_with_nul; assert_eq!;Creating a
CStrwith an interior nul byte is an error:use ; let cstr = from_bytes_with_nul; assert_eq!;unsafe const fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStrUnsafely creates a C string wrapper from a byte slice.
This function will cast the provided
bytesto aCStrwrapper without performing any sanity checks.Safety
The provided slice must be nul-terminated and not contain any interior nul bytes.
Examples
use CStr; let bytes = b"Hello world!\0"; let cstr = unsafe ; assert_eq!;const fn as_ptr(self: &Self) -> *const c_charReturns the inner pointer to this C string.
The returned pointer will be valid for as long as
selfis, and points to a contiguous region of memory terminated with a 0 byte to represent the end of the string.The type of the returned pointer is [
*const c_char][crate::ffi::c_char], and whether it's an alias for*const i8or*const u8is platform-specific.WARNING
The returned pointer is read-only; writing to it (including passing it to C code that writes to it) causes undefined behavior.
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
ptris used inside theunsafeblock:# #![expect(dangling_pointers_from_temporaries)] use std::ffi::{CStr, CString}; // 💀 The meaning of this entire program is undefined, // 💀 and nothing about its behavior is guaranteed, // 💀 not even that its behavior resembles the code as written, // 💀 just because it contains a single instance of undefined behavior! // 🚨 creates a dangling pointer to a temporary `CString` // 🚨 that is deallocated at the end of the statement let ptr = CString::new("Hi!".to_uppercase()).unwrap().as_ptr(); // without undefined behavior, you would expect that `ptr` equals: dbg!(CStr::from_bytes_with_nul(b"HI!\0").unwrap()); // 🙏 Possibly the program behaved as expected so far, // 🙏 and this just shows `ptr` is now garbage..., but // 💀 this violates `CStr::from_ptr`'s safety contract // 💀 leading to a dereference of a dangling pointer, // 💀 which is immediate undefined behavior. // 💀 *BOOM*, you're dead, your entire program has no meaning. dbg!(unsafe { CStr::from_ptr(ptr) });This happens because, the pointer returned by
as_ptrdoes not carry any lifetime information, and theCStringis deallocated immediately after the expression that it is part of has been evaluated. To fix the problem, bind theCStringto a local variable:use ; let c_str = new.unwrap; let ptr = c_str.as_ptr; assert_eq!;const fn count_bytes(self: &Self) -> usizeReturns the length of
self. Like C'sstrlen, this does not include the nul terminator.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
assert_eq!; assert_eq!;const fn is_empty(self: &Self) -> boolReturns
trueifself.to_bytes()has a length of 0.Examples
assert!; assert!;const fn to_bytes(self: &Self) -> &[u8]Converts this C string to a byte slice.
The returned slice will not contain the trailing nul terminator 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
assert_eq!;const fn to_bytes_with_nul(self: &Self) -> &[u8]Converts this C string to a byte slice containing the trailing 0 byte.
This function is the equivalent of
CStr::to_bytesexcept that it will retain the trailing nul terminator 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
assert_eq!;fn bytes(self: &Self) -> Bytes<'_>Iterates over the bytes in this C string.
The returned iterator will not contain the trailing nul terminator that this C string has.
Examples
assert!;const fn to_str(self: &Self) -> Result<&str, str::Utf8Error>Yields a
&strslice if theCStrcontains valid UTF-8.If the contents of the
CStrare valid UTF-8 data, this function will return the corresponding&strslice. Otherwise, it will return an error with details of where UTF-8 validation failed.Examples
assert_eq!;fn display(self: &Self) -> impl fmt::DisplayReturns an object that implements
Displayfor safely printing aCStrthat may contain non-Unicode data.Behaves as if
selfwere first lossily converted to astr, with invalid UTF-8 presented as the Unicode replacement character: �.Examples
let cstr = c"Hello, world!"; println!;const fn as_c_str(self: &Self) -> &CStrReturns the same string as a string slice
&CStr.This method is redundant when used directly on
&CStr, but it helps dereferencing other string-like types to string slices, for example references toBox<CStr>orArc<CStr>.
impl AsRef for CStr
fn as_ref(self: &Self) -> &CStr
impl CloneToUninit for crate::ffi::CStr
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl Debug for CStr
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl Eq for CStr
impl Freeze for CStr
impl Hash for CStr
fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H)
impl Index for CStr
fn index(self: &Self, index: ops::RangeFrom<usize>) -> &CStr
impl Ord for CStr
fn cmp(self: &Self, other: &CStr) -> Ordering
impl PartialEq for CStr
fn eq(self: &Self, other: &&Self) -> boolfn ne(self: &Self, other: &&Self) -> bool
impl PartialEq for CStr
fn eq(self: &Self, other: &CStr) -> bool
impl PartialOrd for CStr
fn partial_cmp(self: &Self, other: &CStr) -> Option<Ordering>
impl RefUnwindSafe for CStr
impl Send for CStr
impl Sized for CStr
impl StructuralPartialEq for CStr
impl Sync for CStr
impl Unpin for CStr
impl UnwindSafe for CStr
impl<T> Any for CStr
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for CStr
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for CStr
fn borrow_mut(self: &mut Self) -> &mut T