pub struct CString { /* fields omitted */ }
A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
middle.
This type serves the 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 ("nul characters") and that the final byte is 0 ("nul terminator").
CString
is to &CStr
as String
is to &str
: the former
in each pair are owned strings; the latter are borrowed
references.
A CString
is created from either a byte slice or a byte vector,
or anything that implements Into
<
Vec
<
u8
>>
(for
example, you can build a CString
straight out of a String
or
a &str
, since both implement that trait).
The new
method will actually check that the provided &[u8]
does not have 0 bytes in the middle, and return an error if it
finds one.
CString
implements a as_ptr
method through the Deref
trait. This method will give you a *const c_char
which you can
feed directly to extern functions that expect a nul-terminated
string, like C's strdup()
.
Alternatively, you can obtain a &[
u8
]
slice from a
CString
with the as_bytes
method. Slices produced in this
way do not contain the trailing nul terminator. This is useful
when you will be calling an extern function that takes a *const u8
argument which is not necessarily nul-terminated, plus another
argument with the length of the string — like C's strndup()
.
You can of course get the slice's length with its
len
method.
If you need a &[
u8
]
slice with the nul terminator, you
can use as_bytes_with_nul
instead.
Once you have the kind of slice you need (with or without a nul
terminator), you can call the slice's own
as_ptr
method to get a raw pointer to pass to
extern functions. See the documentation for that function for a
discussion on ensuring the lifetime of the raw pointer.
use std::ffi::CString;
use std::os::raw::c_char;
extern {
fn my_printer(s: *const c_char);
}
let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
unsafe {
my_printer(c_to_print.as_ptr());
}Run
CString
is intended for working with traditional C-style strings
(a sequence of non-nul bytes terminated by a single nul 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.
Creates a new C-compatible string from a container of bytes.
This function will consume the provided data and use the
underlying bytes to construct a new string, ensuring that
there is a trailing 0 byte. This trailing 0 byte will be
appended by this function; the provided data should not
contain any 0 bytes in it.
use std::ffi::CString;
use std::os::raw::c_char;
extern { fn puts(s: *const c_char); }
let to_print = CString::new("Hello!").expect("CString::new failed");
unsafe {
puts(to_print.as_ptr());
}Run
This function will return an error if the supplied bytes contain an
internal 0 byte. The NulError
returned will contain the bytes as well as
the position of the nul byte.
Creates a C-compatible string by consuming 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.
use std::ffi::CString;
let raw = b"foo".to_vec();
unsafe {
let c_string = CString::from_vec_unchecked(raw);
}Run
Retakes ownership of a CString
that was transferred to C via into_raw
.
Additionally, the length of the string will be recalculated from the pointer.
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.
Note: If you need to borrow a string that was allocated by
foreign code, use CStr
. If you need to take ownership of
a string that was allocated by foreign code, you will need to
make your own provisions for freeing it appropriately, likely
with the foreign code's API to do that.
Create a CString
, pass ownership to an extern
function (via raw pointer), then retake
ownership with from_raw
:
use std::ffi::CString;
use std::os::raw::c_char;
extern {
fn some_extern_function(s: *mut c_char);
}
let c_string = CString::new("Hello!").expect("CString::new failed");
let raw = c_string.into_raw();
unsafe {
some_extern_function(raw);
let c_string = CString::from_raw(raw);
}Run
Consumes the CString
and transfers ownership of the string to a C caller.
The pointer which this function returns 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.
use std::ffi::CString;
let c_string = CString::new("foo").expect("CString::new failed");
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);
let _ = CString::from_raw(ptr);
}Run
Converts the CString
into a String
if it contains valid UTF-8 data.
On failure, ownership of the original CString
is returned.
use std::ffi::CString;
let valid_utf8 = vec![b'f', b'o', b'o'];
let cstring = CString::new(valid_utf8).expect("CString::new failed");
assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
let cstring = CString::new(invalid_utf8).expect("CString::new failed");
let err = cstring.into_string().err().expect("into_string().err() failed");
assert_eq!(err.utf8_error().valid_up_to(), 1);Run
Consumes the CString
and returns the underlying byte buffer.
The returned buffer does not contain the trailing nul
terminator, and it is guaranteed to not have any interior nul
bytes.
use std::ffi::CString;
let c_string = CString::new("foo").expect("CString::new failed");
let bytes = c_string.into_bytes();
assert_eq!(bytes, vec![b'f', b'o', b'o']);Run
Equivalent to the into_bytes
function except that the returned vector
includes the trailing nul terminator.
use std::ffi::CString;
let c_string = CString::new("foo").expect("CString::new failed");
let bytes = c_string.into_bytes_with_nul();
assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);Run
Returns the contents of this CString
as a slice of bytes.
The returned slice does not contain the trailing nul
terminator, and it is guaranteed to not have any interior nul
bytes. If you need the nul terminator, use
as_bytes_with_nul
instead.
use std::ffi::CString;
let c_string = CString::new("foo").expect("CString::new failed");
let bytes = c_string.as_bytes();
assert_eq!(bytes, &[b'f', b'o', b'o']);Run
Equivalent to the as_bytes
function except that the returned slice
includes the trailing nul terminator.
use std::ffi::CString;
let c_string = CString::new("foo").expect("CString::new failed");
let bytes = c_string.as_bytes_with_nul();
assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);Run
Extracts a CStr
slice containing the entire string.
use std::ffi::{CString, CStr};
let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
let c_str = c_string.as_c_str();
assert_eq!(c_str,
CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));Run
Converts this CString
into a boxed CStr
.
use std::ffi::{CString, CStr};
let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
let boxed = c_string.into_boxed_c_str();
assert_eq!(&*boxed,
CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));Run
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 std::ffi::{CString};
let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
unsafe {
*ptr;
}Run
This happens because the pointer returned by as_ptr
does not carry any
lifetime information and the CString
is deallocated immediately after
the CString::new("Hello").expect("CString::new failed").as_ptr()
expression is evaluated.
To fix the problem, bind the CString
to a local variable:
use std::ffi::{CString};
let hello = CString::new("Hello").expect("CString::new failed");
let ptr = hello.as_ptr();
unsafe {
*ptr;
}Run
This way, the lifetime of the CString
in hello
encompasses
the lifetime of ptr
and the unsafe
block.
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.
use std::ffi::CStr;
let c_str = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
assert_eq!(c_str.to_bytes(), b"foo");Run
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 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.
use std::ffi::CStr;
let c_str = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
assert_eq!(c_str.to_bytes_with_nul(), b"foo\0");Run
Yields a &str
slice if the CStr
contains valid UTF-8.
If the contents of the CStr
are valid UTF-8 data, this
function will return the corresponding &str
slice. Otherwise,
it will return an error with details of where UTF-8 validation failed.
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.
use std::ffi::CStr;
let c_str = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
assert_eq!(c_str.to_str(), Ok("foo"));Run
Converts a CStr
into a Cow
<
str
>
.
If the contents of the CStr
are valid UTF-8 data, this
function will return a Cow
::
Borrowed
(
[&str
])
with the corresponding [&str
] slice. Otherwise, it will
replace any invalid UTF-8 sequences with
U+FFFD REPLACEMENT CHARACTER
and return a
Cow
::
Owned
(
String
)
with the result.
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.
Calling to_string_lossy
on a CStr
containing valid UTF-8:
use std::borrow::Cow;
use std::ffi::CStr;
let c_str = CStr::from_bytes_with_nul(b"Hello World\0")
.expect("CStr::from_bytes_with_nul failed");
assert_eq!(c_str.to_string_lossy(), Cow::Borrowed("Hello World"));Run
Calling to_string_lossy
on a CStr
containing invalid UTF-8:
use std::borrow::Cow;
use std::ffi::CStr;
let c_str = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
.expect("CStr::from_bytes_with_nul failed");
assert_eq!(
c_str.to_string_lossy(),
Cow::Owned(String::from("Hello �World")) as Cow<str>
);Run
Formats the value using the given formatter. Read more
This method tests for self
and other
values to be equal, and is used by ==
. Read more
This method tests for !=
.
This method returns an Ordering
between self
and other
. Read more
fn max(self, other: Self) -> Self | 1.21.0 [src] |
Compares and returns the maximum of two values. Read more
fn min(self, other: Self) -> Self | 1.21.0 [src] |
Compares and returns the minimum of two values. Read more
This method returns an ordering between self
and other
values if one exists. Read more
This method tests less than (for self
and other
) and is used by the <
operator. Read more
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
This method tests greater than (for self
and other
) and is used by the >
operator. Read more
This method tests greater than or equal to (for self
and other
) and is used by the >=
operator. Read more
Converts a CString
into a Vec
<u8>
.
The conversion consumes the CString
, and removes the terminating NUL byte.
Converts a Box
<CStr>
into a CString
without copying or allocating.
Converts a CString
into a Box
<CStr>
without copying or allocating.
Converts a CString
into a Arc
<CStr>
without copying or allocating.
Converts a CString
into a Rc
<CStr>
without copying or allocating.
Feeds this value into the given [Hasher
]. Read more
Feeds a slice of this type into the given [Hasher
]. Read more
type Target = CStr
The resulting type after dereferencing.
Executes the destructor for this type. Read more
type Output = CStr
The returned type after indexing.
Performs the indexing (container[index]
) operation.
Performs copy-assignment from source
. Read more
Creates an empty CString
.
Immutably borrows from an owned value. Read more
type Error = !
🔬 This is a nightly-only experimental API. (
try_from
#33417)
The type returned in the event of a conversion error.
🔬 This is a nightly-only experimental API. (
try_from
#33417)
type Error = <U as TryFrom<T>>::Error
🔬 This is a nightly-only experimental API. (
try_from
#33417)
The type returned in the event of a conversion error.
🔬 This is a nightly-only experimental API. (
try_from
#33417)
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
🔬 This is a nightly-only experimental API. (get_type_id
#27745)
this method will likely be replaced by an associated static
type Owned = T
Creates owned data from borrowed data, usually by cloning. Read more
🔬 This is a nightly-only experimental API. (toowned_clone_into
#41263)
recently added
Uses borrowed data to replace owned data, usually by cloning. Read more