[−][src]Struct ndless::ffi::CString
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.
Methods
impl CString
[src]
pub fn new<T>(t: T) -> Result<CString, NulError> where
T: Into<Vec<u8>>,
[src]
T: Into<Vec<u8>>,
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.
pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> CString
[src]
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); }
pub unsafe fn from_raw(ptr: *mut i8) -> CString
[src]
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); }
pub fn into_raw(self) -> *mut i8
[src]
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); }
pub fn into_string(self) -> Result<String, IntoStringError>
[src]
Converts the CString
into a String
if it contains valid Unicode data.
On failure, ownership of the original CString
is returned.
pub fn into_bytes(self) -> Vec<u8>
[src]
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']);
pub fn into_bytes_with_nul(self) -> Vec<u8>
[src]
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']);
pub fn as_bytes(&self) -> &[u8]
[src]
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']);
pub fn as_bytes_with_nul(&self) -> &[u8]
[src]
Equivalent to the as_bytes
function except that the returned slice
includes the trailing nul byte.
Examples
use cstr_core::CString; let c_string = CString::new("foo").unwrap(); let bytes = c_string.as_bytes_with_nul(); assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
pub fn as_c_str(&self) -> &CStr
[src]
Extracts a CStr
slice containing the entire string.
Examples
use cstr_core::{CString, CStr}; let c_string = CString::new(b"foo".to_vec()).unwrap(); let c_str = c_string.as_c_str(); assert_eq!(c_str, CStr::from_bytes_with_nul(b"foo\0").unwrap());
ⓘImportant traits for Box<F>pub fn into_boxed_c_str(self) -> Box<CStr>
[src]
Methods from Deref<Target = CStr>
pub fn as_ptr(&self) -> *const i8
[src]
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; }
pub fn to_bytes(&self) -> &[u8]
[src]
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");
pub fn to_bytes_with_nul(&self) -> &[u8]
[src]
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");
pub fn to_str(&self) -> Result<&str, Utf8Error>
[src]
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"));
pub fn to_string_lossy(&self) -> Cow<str>
[src]
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
impl AsRef<CStr> for CString
[src]
impl Ord for CString
[src]
fn cmp(&self, other: &CString) -> Ordering
[src]
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
fn clamp(self, min: Self, max: Self) -> Self
[src]
clamp
)Restrict a value to a certain interval. Read more
impl Clone for CString
[src]
fn clone(&self) -> CString
[src]
fn clone_from(&mut self, source: &Self)
1.0.0[src]
Performs copy-assignment from source
. Read more
impl Default for CString
[src]
impl Eq for CString
[src]
impl Drop for CString
[src]
impl Debug for CString
[src]
impl PartialOrd<CString> for CString
[src]
fn partial_cmp(&self, other: &CString) -> Option<Ordering>
[src]
fn lt(&self, other: &CString) -> bool
[src]
fn le(&self, other: &CString) -> bool
[src]
fn gt(&self, other: &CString) -> bool
[src]
fn ge(&self, other: &CString) -> bool
[src]
impl Hash for CString
[src]
fn hash<__H>(&self, state: &mut __H) where
__H: Hasher,
[src]
__H: Hasher,
fn hash_slice<H>(data: &[Self], state: &mut H) where
H: Hasher,
1.3.0[src]
H: Hasher,
Feeds a slice of this type into the given [Hasher
]. Read more
impl Index<RangeFull> for CString
[src]
type Output = CStr
The returned type after indexing.
fn index(&self, _index: RangeFull) -> &CStr
[src]
impl PartialEq<CString> for CString
[src]
impl From<Box<CStr>> for CString
[src]
impl From<CString> for Box<CStr>
[src]
impl<'a> From<&'a CStr> for CString
[src]
impl From<CString> for Vec<u8>
[src]
impl Borrow<CStr> for CString
[src]
impl Deref for CString
[src]
Auto Trait Implementations
Blanket Implementations
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T> From<T> for T
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> ToOwned for T where
T: Clone,
[src]
T: Clone,
type Owned = T
The resulting type after obtaining ownership.