1//! [`CString`] and its related types.
23use core::borrow::Borrow;
4use core::ffi::{CStr, c_char};
5use core::num::NonZero;
6use core::slice::memchr;
7use core::str::{self, FromStr, Utf8Error};
8use core::{fmt, mem, ops, ptr, slice};
910use crate::borrow::{Cow, ToOwned};
11use crate::boxed::Box;
12use crate::rc::Rc;
13use crate::string::String;
14#[cfg(target_has_atomic = "ptr")]
15use crate::sync::Arc;
16use crate::vec::Vec;
1718/// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
19/// middle.
20///
21/// This type serves the purpose of being able to safely generate a
22/// C-compatible string from a Rust byte slice or vector. An instance of this
23/// type is a static guarantee that the underlying bytes contain no interior 0
24/// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
25///
26/// `CString` is to <code>&[CStr]</code> as [`String`] is to <code>&[str]</code>: the former
27/// in each pair are owned strings; the latter are borrowed
28/// references.
29///
30/// # Creating a `CString`
31///
32/// A `CString` is created from either a byte slice or a byte vector,
33/// or anything that implements <code>[Into]<[Vec]<[u8]>></code> (for
34/// example, you can build a `CString` straight out of a [`String`] or
35/// a <code>&[str]</code>, since both implement that trait).
36/// You can create a `CString` from a literal with `CString::from(c"Text")`.
37///
38/// The [`CString::new`] method will actually check that the provided <code>&[[u8]]</code>
39/// does not have 0 bytes in the middle, and return an error if it
40/// finds one.
41///
42/// # Extracting a raw pointer to the whole C string
43///
44/// `CString` implements an [`as_ptr`][`CStr::as_ptr`] method through the [`Deref`]
45/// trait. This method will give you a `*const c_char` which you can
46/// feed directly to extern functions that expect a nul-terminated
47/// string, like C's `strdup()`. Notice that [`as_ptr`][`CStr::as_ptr`] returns a
48/// read-only pointer; if the C code writes to it, that causes
49/// undefined behavior.
50///
51/// # Extracting a slice of the whole C string
52///
53/// Alternatively, you can obtain a <code>&[[u8]]</code> slice from a
54/// `CString` with the [`CString::as_bytes`] method. Slices produced in this
55/// way do *not* contain the trailing nul terminator. This is useful
56/// when you will be calling an extern function that takes a `*const
57/// u8` argument which is not necessarily nul-terminated, plus another
58/// argument with the length of the string — like C's `strndup()`.
59/// You can of course get the slice's length with its
60/// [`len`][slice::len] method.
61///
62/// If you need a <code>&[[u8]]</code> slice *with* the nul terminator, you
63/// can use [`CString::as_bytes_with_nul`] instead.
64///
65/// Once you have the kind of slice you need (with or without a nul
66/// terminator), you can call the slice's own
67/// [`as_ptr`][slice::as_ptr] method to get a read-only raw pointer to pass to
68/// extern functions. See the documentation for that function for a
69/// discussion on ensuring the lifetime of the raw pointer.
70///
71/// [str]: prim@str "str"
72/// [`Deref`]: ops::Deref
73///
74/// # Examples
75///
76/// ```ignore (extern-declaration)
77/// # fn main() {
78/// use std::ffi::CString;
79/// use std::os::raw::c_char;
80///
81/// extern "C" {
82/// fn my_printer(s: *const c_char);
83/// }
84///
85/// // We are certain that our string doesn't have 0 bytes in the middle,
86/// // so we can .expect()
87/// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
88/// unsafe {
89/// my_printer(c_to_print.as_ptr());
90/// }
91/// # }
92/// ```
93///
94/// # Safety
95///
96/// `CString` is intended for working with traditional C-style strings
97/// (a sequence of non-nul bytes terminated by a single nul byte); the
98/// primary use case for these kinds of strings is interoperating with C-like
99/// code. Often you will need to transfer ownership to/from that external
100/// code. It is strongly recommended that you thoroughly read through the
101/// documentation of `CString` before use, as improper ownership management
102/// of `CString` instances can lead to invalid memory accesses, memory leaks,
103/// and other memory errors.
104#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for CString {
#[inline]
fn eq(&self, other: &CString) -> bool { self.inner == other.inner }
}PartialEq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialOrd for CString {
#[inline]
fn partial_cmp(&self, other: &CString)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::cmp::PartialOrd::partial_cmp(&self.inner, &other.inner)
}
}PartialOrd, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::Eq for CString {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Box<[u8]>>;
}
}Eq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::Ord for CString {
#[inline]
fn cmp(&self, other: &CString) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.inner, &other.inner)
}
}Ord, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::hash::Hash for CString {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.inner, state)
}
}Hash, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::clone::Clone for CString {
#[inline]
fn clone(&self) -> CString {
CString { inner: ::core::clone::Clone::clone(&self.inner) }
}
}Clone)]
105#[rustc_diagnostic_item = "cstring_type"]
106#[rustc_insignificant_dtor]
107#[stable(feature = "alloc_c_string", since = "1.64.0")]
108pub struct CString {
109// Invariant 1: the slice ends with a zero byte and has a length of at least one.
110 // Invariant 2: the slice contains only one zero byte.
111 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
112inner: Box<[u8]>,
113}
114115/// An error indicating that an interior nul byte was found.
116///
117/// While Rust strings may contain nul bytes in the middle, C strings
118/// can't, as that byte would effectively truncate the string.
119///
120/// This error is created by the [`new`][`CString::new`] method on
121/// [`CString`]. See its documentation for more.
122///
123/// # Examples
124///
125/// ```
126/// use std::ffi::{CString, NulError};
127///
128/// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
129/// ```
130#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::clone::Clone for NulError {
#[inline]
fn clone(&self) -> NulError {
NulError(::core::clone::Clone::clone(&self.0),
::core::clone::Clone::clone(&self.1))
}
}Clone, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for NulError {
#[inline]
fn eq(&self, other: &NulError) -> bool {
self.0 == other.0 && self.1 == other.1
}
}PartialEq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::Eq for NulError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<Vec<u8>>;
}
}Eq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::fmt::Debug for NulError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field2_finish(f, "NulError",
&self.0, &&self.1)
}
}Debug)]
131#[stable(feature = "alloc_c_string", since = "1.64.0")]
132pub struct NulError(usize, Vec<u8>);
133134#[derive(#[automatically_derived]
impl ::core::clone::Clone for FromBytesWithNulErrorKind {
#[inline]
fn clone(&self) -> FromBytesWithNulErrorKind {
match self {
FromBytesWithNulErrorKind::InteriorNul(__self_0) =>
FromBytesWithNulErrorKind::InteriorNul(::core::clone::Clone::clone(__self_0)),
FromBytesWithNulErrorKind::NotNulTerminated =>
FromBytesWithNulErrorKind::NotNulTerminated,
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for FromBytesWithNulErrorKind {
#[inline]
fn eq(&self, other: &FromBytesWithNulErrorKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(FromBytesWithNulErrorKind::InteriorNul(__self_0),
FromBytesWithNulErrorKind::InteriorNul(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for FromBytesWithNulErrorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for FromBytesWithNulErrorKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FromBytesWithNulErrorKind::InteriorNul(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InteriorNul", &__self_0),
FromBytesWithNulErrorKind::NotNulTerminated =>
::core::fmt::Formatter::write_str(f, "NotNulTerminated"),
}
}
}Debug)]
135enum FromBytesWithNulErrorKind {
136 InteriorNul(usize),
137 NotNulTerminated,
138}
139140/// An error indicating that a nul byte was not in the expected position.
141///
142/// The vector used to create a [`CString`] must have one and only one nul byte,
143/// positioned at the end.
144///
145/// This error is created by the [`CString::from_vec_with_nul`] method.
146/// See its documentation for more.
147///
148/// # Examples
149///
150/// ```
151/// use std::ffi::{CString, FromVecWithNulError};
152///
153/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
154/// ```
155#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::clone::Clone for FromVecWithNulError {
#[inline]
fn clone(&self) -> FromVecWithNulError {
FromVecWithNulError {
error_kind: ::core::clone::Clone::clone(&self.error_kind),
bytes: ::core::clone::Clone::clone(&self.bytes),
}
}
}Clone, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for FromVecWithNulError {
#[inline]
fn eq(&self, other: &FromVecWithNulError) -> bool {
self.error_kind == other.error_kind && self.bytes == other.bytes
}
}PartialEq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::Eq for FromVecWithNulError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<FromBytesWithNulErrorKind>;
let _: ::core::cmp::AssertParamIsEq<Vec<u8>>;
}
}Eq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::fmt::Debug for FromVecWithNulError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"FromVecWithNulError", "error_kind", &self.error_kind, "bytes",
&&self.bytes)
}
}Debug)]
156#[stable(feature = "alloc_c_string", since = "1.64.0")]
157pub struct FromVecWithNulError {
158 error_kind: FromBytesWithNulErrorKind,
159 bytes: Vec<u8>,
160}
161162#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
163impl FromVecWithNulError {
164/// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
165 ///
166 /// # Examples
167 ///
168 /// Basic usage:
169 ///
170 /// ```
171 /// use std::ffi::CString;
172 ///
173 /// // Some invalid bytes in a vector
174 /// let bytes = b"f\0oo".to_vec();
175 ///
176 /// let value = CString::from_vec_with_nul(bytes.clone());
177 ///
178 /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
179 /// ```
180#[must_use]
181 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
182pub fn as_bytes(&self) -> &[u8] {
183&self.bytes[..]
184 }
185186/// Returns the bytes that were attempted to convert to a [`CString`].
187 ///
188 /// This method is carefully constructed to avoid allocation. It will
189 /// consume the error, moving out the bytes, so that a copy of the bytes
190 /// does not need to be made.
191 ///
192 /// # Examples
193 ///
194 /// Basic usage:
195 ///
196 /// ```
197 /// use std::ffi::CString;
198 ///
199 /// // Some invalid bytes in a vector
200 /// let bytes = b"f\0oo".to_vec();
201 ///
202 /// let value = CString::from_vec_with_nul(bytes.clone());
203 ///
204 /// assert_eq!(bytes, value.unwrap_err().into_bytes());
205 /// ```
206#[must_use = "`self` will be dropped if the result is not used"]
207 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
208pub fn into_bytes(self) -> Vec<u8> {
209self.bytes
210 }
211}
212213/// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
214///
215/// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
216/// [`CString::into_string`] performs UTF-8 validation on those bytes and may
217/// return this error.
218///
219/// This `struct` is created by [`CString::into_string()`]. See
220/// its documentation for more.
221#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::clone::Clone for IntoStringError {
#[inline]
fn clone(&self) -> IntoStringError {
IntoStringError {
inner: ::core::clone::Clone::clone(&self.inner),
error: ::core::clone::Clone::clone(&self.error),
}
}
}Clone, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for IntoStringError {
#[inline]
fn eq(&self, other: &IntoStringError) -> bool {
self.inner == other.inner && self.error == other.error
}
}PartialEq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::Eq for IntoStringError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<CString>;
let _: ::core::cmp::AssertParamIsEq<Utf8Error>;
}
}Eq, #[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::fmt::Debug for IntoStringError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"IntoStringError", "inner", &self.inner, "error", &&self.error)
}
}Debug)]
222#[stable(feature = "alloc_c_string", since = "1.64.0")]
223pub struct IntoStringError {
224 inner: CString,
225 error: Utf8Error,
226}
227228impl CString {
229/// Creates a new C-compatible string from a container of bytes.
230 ///
231 /// This function will consume the provided data and use the
232 /// underlying bytes to construct a new string, ensuring that
233 /// there is a trailing 0 byte. This trailing 0 byte will be
234 /// appended by this function; the provided data should *not*
235 /// contain any 0 bytes in it.
236 ///
237 /// # Examples
238 ///
239 /// ```ignore (extern-declaration)
240 /// use std::ffi::CString;
241 /// use std::os::raw::c_char;
242 ///
243 /// extern "C" { fn puts(s: *const c_char); }
244 ///
245 /// let to_print = CString::new("Hello!").expect("CString::new failed");
246 /// unsafe {
247 /// puts(to_print.as_ptr());
248 /// }
249 /// ```
250 ///
251 /// # Errors
252 ///
253 /// This function will return an error if the supplied bytes contain an
254 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
255 /// the position of the nul byte.
256#[stable(feature = "rust1", since = "1.0.0")]
257pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
258trait SpecNewImpl {
259fn spec_new_impl(self) -> Result<CString, NulError>;
260 }
261262impl<T: Into<Vec<u8>>> SpecNewImplfor T {
263 default fn spec_new_impl(self) -> Result<CString, NulError> {
264let bytes: Vec<u8> = self.into();
265match memchr::memchr(0, &bytes) {
266Some(i) => Err(NulError(i, bytes)),
267None => Ok(unsafe { CString::_from_vec_unchecked(bytes) }),
268 }
269 }
270 }
271272// Specialization for avoiding reallocation
273#[inline(always)] // Without that it is not inlined into specializations
274fn spec_new_impl_bytes(bytes: &[u8]) -> Result<CString, NulError> {
275// We cannot have such large slice that we would overflow here
276 // but using `checked_add` allows LLVM to assume that capacity never overflows
277 // and generate twice shorter code.
278 // `saturating_add` doesn't help for some reason.
279let capacity = bytes.len().checked_add(1).unwrap();
280281// Allocate before validation to avoid duplication of allocation code.
282 // We still need to allocate and copy memory even if we get an error.
283let mut buffer = Vec::with_capacity(capacity);
284buffer.extend(bytes);
285286// Check memory of self instead of new buffer.
287 // This allows better optimizations if lto enabled.
288match memchr::memchr(0, bytes) {
289Some(i) => Err(NulError(i, buffer)),
290None => Ok(unsafe { CString::_from_vec_unchecked(buffer) }),
291 }
292 }
293294impl SpecNewImplfor &'_ [u8] {
295fn spec_new_impl(self) -> Result<CString, NulError> {
296spec_new_impl_bytes(self)
297 }
298 }
299300impl SpecNewImplfor &'_ str {
301fn spec_new_impl(self) -> Result<CString, NulError> {
302spec_new_impl_bytes(self.as_bytes())
303 }
304 }
305306impl SpecNewImplfor &'_ mut [u8] {
307fn spec_new_impl(self) -> Result<CString, NulError> {
308spec_new_impl_bytes(self)
309 }
310 }
311312t.spec_new_impl()
313 }
314315/// Creates a C-compatible string by consuming a byte vector,
316 /// without checking for interior 0 bytes.
317 ///
318 /// Trailing 0 byte will be appended by this function.
319 ///
320 /// This method is equivalent to [`CString::new`] except that no runtime
321 /// assertion is made that `v` contains no 0 bytes, and it requires an
322 /// actual byte vector, not anything that can be converted to one with Into.
323 ///
324 /// # Safety
325 ///
326 /// The caller must ensure `v` contains no nul bytes in its contents.
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// use std::ffi::CString;
332 ///
333 /// let raw = b"foo".to_vec();
334 /// unsafe {
335 /// let c_string = CString::from_vec_unchecked(raw);
336 /// }
337 /// ```
338#[must_use]
339 #[stable(feature = "rust1", since = "1.0.0")]
340pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> Self {
341if true {
if !memchr::memchr(0, &v).is_none() {
::core::panicking::panic("assertion failed: memchr::memchr(0, &v).is_none()")
};
};debug_assert!(memchr::memchr(0, &v).is_none());
342unsafe { Self::_from_vec_unchecked(v) }
343 }
344345unsafe fn _from_vec_unchecked(mut v: Vec<u8>) -> Self {
346v.reserve_exact(1);
347v.push(0);
348Self { inner: v.into_boxed_slice() }
349 }
350351/// Retakes ownership of a `CString` that was transferred to C via
352 /// [`CString::into_raw`].
353 ///
354 /// Additionally, the length of the string will be recalculated from the pointer.
355 ///
356 /// # Safety
357 ///
358 /// This should only ever be called with a pointer that was earlier
359 /// obtained by calling [`CString::into_raw`], and the memory it points to must not be accessed
360 /// through any other pointer during the lifetime of reconstructed `CString`.
361 /// Other usage (e.g., trying to take ownership of a string that was allocated by foreign code)
362 /// is likely to lead to undefined behavior or allocator corruption.
363 ///
364 /// This function does not validate ownership of the raw pointer's memory.
365 /// A double-free may occur if the function is called twice on the same raw pointer.
366 /// Additionally, the caller must ensure the pointer is not dangling.
367 ///
368 /// It should be noted that the length isn't just "recomputed," but that
369 /// the recomputed length must match the original length from the
370 /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
371 /// methods should not be used when passing the string to C functions that can
372 /// modify the string's length.
373 ///
374 /// > **Note:** If you need to borrow a string that was allocated by
375 /// > foreign code, use [`CStr`]. If you need to take ownership of
376 /// > a string that was allocated by foreign code, you will need to
377 /// > make your own provisions for freeing it appropriately, likely
378 /// > with the foreign code's API to do that.
379 ///
380 /// # Examples
381 ///
382 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
383 /// ownership with `from_raw`:
384 ///
385 /// ```ignore (extern-declaration)
386 /// use std::ffi::CString;
387 /// use std::os::raw::c_char;
388 ///
389 /// extern "C" {
390 /// fn some_extern_function(s: *mut c_char);
391 /// }
392 ///
393 /// let c_string = CString::from(c"Hello!");
394 /// let raw = c_string.into_raw();
395 /// unsafe {
396 /// some_extern_function(raw);
397 /// let c_string = CString::from_raw(raw);
398 /// }
399 /// ```
400#[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
401 #[stable(feature = "cstr_memory", since = "1.4.0")]
402pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
403// SAFETY: This is called with a pointer that was obtained from a call
404 // to `CString::into_raw` and the length has not been modified. As such,
405 // we know there is a NUL byte (and only one) at the end and that the
406 // information about the size of the allocation is correct on Rust's
407 // side.
408unsafe {
409unsafe extern "C" {
410/// Provided by libc or compiler_builtins.
411fn strlen(s: *const c_char) -> usize;
412 }
413let len = strlen(ptr) + 1; // Including the NUL byte
414let slice = slice::from_raw_parts_mut(ptr, len);
415CString { inner: Box::from_raw(sliceas *mut [c_char] as *mut [u8]) }
416 }
417 }
418419/// Consumes the `CString` and transfers ownership of the string to a C caller.
420 ///
421 /// The pointer which this function returns must be returned to Rust and reconstituted using
422 /// [`CString::from_raw`] to be properly deallocated. Specifically, one
423 /// should *not* use the standard C `free()` function to deallocate
424 /// this string.
425 ///
426 /// Failure to call [`CString::from_raw`] will lead to a memory leak.
427 ///
428 /// The C side must **not** modify the length of the string (by writing a
429 /// nul byte somewhere inside the string or removing the final one) before
430 /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
431 /// in [`CString::from_raw`].
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// use std::ffi::CString;
437 ///
438 /// let c_string = CString::from(c"foo");
439 ///
440 /// let ptr = c_string.into_raw();
441 ///
442 /// unsafe {
443 /// assert_eq!(b'f', *ptr as u8);
444 /// assert_eq!(b'o', *ptr.add(1) as u8);
445 /// assert_eq!(b'o', *ptr.add(2) as u8);
446 /// assert_eq!(b'\0', *ptr.add(3) as u8);
447 ///
448 /// // retake pointer to free memory
449 /// let _ = CString::from_raw(ptr);
450 /// }
451 /// ```
452#[inline]
453 #[must_use = "`self` will be dropped if the result is not used"]
454 #[stable(feature = "cstr_memory", since = "1.4.0")]
455pub fn into_raw(self) -> *mut c_char {
456Box::into_raw(self.into_inner()) as *mut c_char457 }
458459/// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
460 ///
461 /// On failure, ownership of the original `CString` is returned.
462 ///
463 /// # Examples
464 ///
465 /// ```
466 /// use std::ffi::CString;
467 ///
468 /// let valid_utf8 = vec![b'f', b'o', b'o'];
469 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
470 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
471 ///
472 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
473 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
474 /// let err = cstring.into_string().err().expect("into_string().err() failed");
475 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
476 /// ```
477#[stable(feature = "cstring_into", since = "1.7.0")]
478pub fn into_string(self) -> Result<String, IntoStringError> {
479String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
480 error: e.utf8_error(),
481 inner: unsafe { Self::_from_vec_unchecked(e.into_bytes()) },
482 })
483 }
484485/// Consumes the `CString` and returns the underlying byte buffer.
486 ///
487 /// The returned buffer does **not** contain the trailing nul
488 /// terminator, and it is guaranteed to not have any interior nul
489 /// bytes.
490 ///
491 /// # Examples
492 ///
493 /// ```
494 /// use std::ffi::CString;
495 ///
496 /// let c_string = CString::from(c"foo");
497 /// let bytes = c_string.into_bytes();
498 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
499 /// ```
500#[must_use = "`self` will be dropped if the result is not used"]
501 #[stable(feature = "cstring_into", since = "1.7.0")]
502pub fn into_bytes(self) -> Vec<u8> {
503let mut vec = self.into_inner().into_vec();
504let _nul = vec.pop();
505if true {
match (&_nul, &Some(0u8)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(_nul, Some(0u8));
506vec507 }
508509/// Equivalent to [`CString::into_bytes()`] except that the
510 /// returned vector includes the trailing nul terminator.
511 ///
512 /// # Examples
513 ///
514 /// ```
515 /// use std::ffi::CString;
516 ///
517 /// let c_string = CString::from(c"foo");
518 /// let bytes = c_string.into_bytes_with_nul();
519 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
520 /// ```
521#[must_use = "`self` will be dropped if the result is not used"]
522 #[stable(feature = "cstring_into", since = "1.7.0")]
523pub fn into_bytes_with_nul(self) -> Vec<u8> {
524self.into_inner().into_vec()
525 }
526527/// Returns the contents of this `CString` as a slice of bytes.
528 ///
529 /// The returned slice does **not** contain the trailing nul
530 /// terminator, and it is guaranteed to not have any interior nul
531 /// bytes. If you need the nul terminator, use
532 /// [`CString::as_bytes_with_nul`] instead.
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// use std::ffi::CString;
538 ///
539 /// let c_string = CString::from(c"foo");
540 /// let bytes = c_string.as_bytes();
541 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
542 /// ```
543#[inline]
544 #[must_use]
545 #[stable(feature = "rust1", since = "1.0.0")]
546pub fn as_bytes(&self) -> &[u8] {
547// SAFETY: CString has a length at least 1
548unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
549 }
550551/// Equivalent to [`CString::as_bytes()`] except that the
552 /// returned slice includes the trailing nul terminator.
553 ///
554 /// # Examples
555 ///
556 /// ```
557 /// use std::ffi::CString;
558 ///
559 /// let c_string = CString::from(c"foo");
560 /// let bytes = c_string.as_bytes_with_nul();
561 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
562 /// ```
563#[inline]
564 #[must_use]
565 #[stable(feature = "rust1", since = "1.0.0")]
566pub fn as_bytes_with_nul(&self) -> &[u8] {
567&self.inner
568 }
569570/// Extracts a [`CStr`] slice containing the entire string.
571 ///
572 /// # Examples
573 ///
574 /// ```
575 /// use std::ffi::{CString, CStr};
576 ///
577 /// let c_string = CString::from(c"foo");
578 /// let cstr = c_string.as_c_str();
579 /// assert_eq!(cstr,
580 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
581 /// ```
582#[inline]
583 #[must_use]
584 #[stable(feature = "as_c_str", since = "1.20.0")]
585 #[rustc_diagnostic_item = "cstring_as_c_str"]
586pub fn as_c_str(&self) -> &CStr {
587unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
588 }
589590/// Converts this `CString` into a boxed [`CStr`].
591 ///
592 /// # Examples
593 ///
594 /// ```
595 /// let c_string = c"foo".to_owned();
596 /// let boxed = c_string.into_boxed_c_str();
597 /// assert_eq!(boxed.to_bytes_with_nul(), b"foo\0");
598 /// ```
599#[must_use = "`self` will be dropped if the result is not used"]
600 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
601pub fn into_boxed_c_str(self) -> Box<CStr> {
602unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
603 }
604605/// Bypass "move out of struct which implements [`Drop`] trait" restriction.
606#[inline]
607fn into_inner(self) -> Box<[u8]> {
608// Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
609 // so we use `ManuallyDrop` to ensure `self` is not dropped.
610 // Then we can return the box directly without invalidating it.
611 // See https://github.com/rust-lang/rust/issues/62553.
612let this = mem::ManuallyDrop::new(self);
613unsafe { ptr::read(&this.inner) }
614 }
615616/// Converts a <code>[Vec]<[u8]></code> to a [`CString`] without checking the
617 /// invariants on the given [`Vec`].
618 ///
619 /// # Safety
620 ///
621 /// The given [`Vec`] **must** have one nul byte as its last element.
622 /// This means it cannot be empty nor have any other nul byte anywhere else.
623 ///
624 /// # Example
625 ///
626 /// ```
627 /// use std::ffi::CString;
628 /// assert_eq!(
629 /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
630 /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
631 /// );
632 /// ```
633#[must_use]
634 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
635pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
636if true {
if !(memchr::memchr(0, &v).unwrap() + 1 == v.len()) {
::core::panicking::panic("assertion failed: memchr::memchr(0, &v).unwrap() + 1 == v.len()")
};
};debug_assert!(memchr::memchr(0, &v).unwrap() + 1 == v.len());
637unsafe { Self::_from_vec_with_nul_unchecked(v) }
638 }
639640unsafe fn _from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
641Self { inner: v.into_boxed_slice() }
642 }
643644/// Attempts to convert a <code>[Vec]<[u8]></code> to a [`CString`].
645 ///
646 /// Runtime checks are present to ensure there is only one nul byte in the
647 /// [`Vec`], its last element.
648 ///
649 /// # Errors
650 ///
651 /// If a nul byte is present and not the last element or no nul bytes
652 /// is present, an error will be returned.
653 ///
654 /// # Examples
655 ///
656 /// A successful conversion will produce the same result as [`CString::new`]
657 /// when called without the ending nul byte.
658 ///
659 /// ```
660 /// use std::ffi::CString;
661 /// assert_eq!(
662 /// CString::from_vec_with_nul(b"abc\0".to_vec())
663 /// .expect("CString::from_vec_with_nul failed"),
664 /// c"abc".to_owned()
665 /// );
666 /// ```
667 ///
668 /// An incorrectly formatted [`Vec`] will produce an error.
669 ///
670 /// ```
671 /// use std::ffi::{CString, FromVecWithNulError};
672 /// // Interior nul byte
673 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
674 /// // No nul byte
675 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
676 /// ```
677#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
678pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
679let nul_pos = memchr::memchr(0, &v);
680match nul_pos {
681Some(nul_pos) if nul_pos + 1 == v.len() => {
682// SAFETY: We know there is only one nul byte, at the end
683 // of the vec.
684Ok(unsafe { Self::_from_vec_with_nul_unchecked(v) })
685 }
686Some(nul_pos) => Err(FromVecWithNulError {
687 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
688 bytes: v,
689 }),
690None => Err(FromVecWithNulError {
691 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
692 bytes: v,
693 }),
694 }
695 }
696}
697698// Turns this `CString` into an empty string to prevent
699// memory-unsafe code from working by accident. Inline
700// to prevent LLVM from optimizing it away in debug builds.
701#[stable(feature = "cstring_drop", since = "1.13.0")]
702impl Dropfor CString {
703#[inline]
704fn drop(&mut self) {
705unsafe {
706*self.inner.get_unchecked_mut(0) = 0;
707 }
708 }
709}
710711#[stable(feature = "rust1", since = "1.0.0")]
712impl ops::Dereffor CString {
713type Target = CStr;
714715#[inline]
716fn deref(&self) -> &CStr {
717self.as_c_str()
718 }
719}
720721/// Delegates to the [`CStr`] implementation of [`fmt::Debug`],
722/// showing invalid UTF-8 as hex escapes.
723#[stable(feature = "rust1", since = "1.0.0")]
724impl fmt::Debugfor CString {
725fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726 fmt::Debug::fmt(self.as_c_str(), f)
727 }
728}
729730#[stable(feature = "cstring_into", since = "1.7.0")]
731impl From<CString> for Vec<u8> {
732/// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
733 ///
734 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
735#[inline]
736fn from(s: CString) -> Vec<u8> {
737s.into_bytes()
738 }
739}
740741#[stable(feature = "cstr_default", since = "1.10.0")]
742impl Defaultfor CString {
743/// Creates an empty `CString`.
744fn default() -> CString {
745let a: &CStr = Default::default();
746a.to_owned()
747 }
748}
749750#[stable(feature = "cstr_borrow", since = "1.3.0")]
751impl Borrow<CStr> for CString {
752#[inline]
753fn borrow(&self) -> &CStr {
754self755 }
756}
757758#[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
759impl<'a> From<Cow<'a, CStr>> for CString {
760/// Converts a `Cow<'a, CStr>` into a `CString`, by copying the contents if they are
761 /// borrowed.
762#[inline]
763fn from(s: Cow<'a, CStr>) -> Self {
764s.into_owned()
765 }
766}
767768#[stable(feature = "box_from_c_str", since = "1.17.0")]
769impl From<&CStr> for Box<CStr> {
770/// Converts a `&CStr` into a `Box<CStr>`,
771 /// by copying the contents into a newly allocated [`Box`].
772fn from(s: &CStr) -> Box<CStr> {
773Box::clone_from_ref(s)
774 }
775}
776777#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
778impl From<&mut CStr> for Box<CStr> {
779/// Converts a `&mut CStr` into a `Box<CStr>`,
780 /// by copying the contents into a newly allocated [`Box`].
781fn from(s: &mut CStr) -> Box<CStr> {
782Self::from(&*s)
783 }
784}
785786#[stable(feature = "box_from_cow", since = "1.45.0")]
787impl From<Cow<'_, CStr>> for Box<CStr> {
788/// Converts a `Cow<'a, CStr>` into a `Box<CStr>`,
789 /// by copying the contents if they are borrowed.
790#[inline]
791fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
792match cow {
793 Cow::Borrowed(s) => Box::from(s),
794 Cow::Owned(s) => Box::from(s),
795 }
796 }
797}
798799#[stable(feature = "c_string_from_box", since = "1.18.0")]
800impl From<Box<CStr>> for CString {
801/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
802#[inline]
803fn from(s: Box<CStr>) -> CString {
804let raw = Box::into_raw(s) as *mut [u8];
805CString { inner: unsafe { Box::from_raw(raw) } }
806 }
807}
808809#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
810impl From<Vec<NonZero<u8>>> for CString {
811/// Converts a <code>[Vec]<[NonZero]<[u8]>></code> into a [`CString`] without
812 /// copying nor checking for inner nul bytes.
813#[inline]
814fn from(v: Vec<NonZero<u8>>) -> CString {
815unsafe {
816// Transmute `Vec<NonZero<u8>>` to `Vec<u8>`.
817let v: Vec<u8> = {
818// SAFETY:
819 // - transmuting between `NonZero<u8>` and `u8` is sound;
820 // - `alloc::Layout<NonZero<u8>> == alloc::Layout<u8>`.
821let (ptr, len, cap): (*mut NonZero<u8>, _, _) = Vec::into_raw_parts(v);
822Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
823 };
824// SAFETY: `v` cannot contain nul bytes, given the type-level
825 // invariant of `NonZero<u8>`.
826Self::_from_vec_unchecked(v)
827 }
828 }
829}
830831#[stable(feature = "c_string_from_str", since = "1.85.0")]
832impl FromStrfor CString {
833type Err = NulError;
834835/// Converts a string `s` into a [`CString`].
836 ///
837 /// This method is equivalent to [`CString::new`].
838#[inline]
839fn from_str(s: &str) -> Result<Self, Self::Err> {
840Self::new(s)
841 }
842}
843844#[stable(feature = "c_string_from_str", since = "1.85.0")]
845impl TryFrom<CString> for String {
846type Error = IntoStringError;
847848/// Converts a [`CString`] into a [`String`] if it contains valid UTF-8 data.
849 ///
850 /// This method is equivalent to [`CString::into_string`].
851#[inline]
852fn try_from(value: CString) -> Result<Self, Self::Error> {
853value.into_string()
854 }
855}
856857#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
858impl Clonefor Box<CStr> {
859#[inline]
860fn clone(&self) -> Self {
861 (**self).into()
862 }
863}
864865#[stable(feature = "box_from_c_string", since = "1.20.0")]
866impl From<CString> for Box<CStr> {
867/// Converts a [`CString`] into a <code>[Box]<[CStr]></code> without copying or allocating.
868#[inline]
869fn from(s: CString) -> Box<CStr> {
870s.into_boxed_c_str()
871 }
872}
873874#[stable(feature = "cow_from_cstr", since = "1.28.0")]
875impl<'a> From<CString> for Cow<'a, CStr> {
876/// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
877#[inline]
878fn from(s: CString) -> Cow<'a, CStr> {
879 Cow::Owned(s)
880 }
881}
882883#[stable(feature = "cow_from_cstr", since = "1.28.0")]
884impl<'a> From<&'a CStr> for Cow<'a, CStr> {
885/// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
886#[inline]
887fn from(s: &'a CStr) -> Cow<'a, CStr> {
888 Cow::Borrowed(s)
889 }
890}
891892#[stable(feature = "cow_from_cstr", since = "1.28.0")]
893impl<'a> From<&'a CString> for Cow<'a, CStr> {
894/// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
895#[inline]
896fn from(s: &'a CString) -> Cow<'a, CStr> {
897 Cow::Borrowed(s.as_c_str())
898 }
899}
900901#[cfg(target_has_atomic = "ptr")]
902#[stable(feature = "shared_from_slice2", since = "1.24.0")]
903impl From<CString> for Arc<CStr> {
904/// Converts a [`CString`] into an <code>[Arc]<[CStr]></code> by moving the [`CString`]
905 /// data into a new [`Arc`] buffer.
906#[inline]
907fn from(s: CString) -> Arc<CStr> {
908let arc: Arc<[u8]> = Arc::from(s.into_inner());
909unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
910 }
911}
912913#[cfg(target_has_atomic = "ptr")]
914#[stable(feature = "shared_from_slice2", since = "1.24.0")]
915impl From<&CStr> for Arc<CStr> {
916/// Converts a `&CStr` into a `Arc<CStr>`,
917 /// by copying the contents into a newly allocated [`Arc`].
918#[inline]
919fn from(s: &CStr) -> Arc<CStr> {
920let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
921unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
922 }
923}
924925#[cfg(target_has_atomic = "ptr")]
926#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
927impl From<&mut CStr> for Arc<CStr> {
928/// Converts a `&mut CStr` into a `Arc<CStr>`,
929 /// by copying the contents into a newly allocated [`Arc`].
930#[inline]
931fn from(s: &mut CStr) -> Arc<CStr> {
932Arc::from(&*s)
933 }
934}
935936#[stable(feature = "shared_from_slice2", since = "1.24.0")]
937impl From<CString> for Rc<CStr> {
938/// Converts a [`CString`] into an <code>[Rc]<[CStr]></code> by moving the [`CString`]
939 /// data into a new [`Rc`] buffer.
940#[inline]
941fn from(s: CString) -> Rc<CStr> {
942let rc: Rc<[u8]> = Rc::from(s.into_inner());
943unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
944 }
945}
946947#[stable(feature = "shared_from_slice2", since = "1.24.0")]
948impl From<&CStr> for Rc<CStr> {
949/// Converts a `&CStr` into a `Rc<CStr>`,
950 /// by copying the contents into a newly allocated [`Rc`].
951#[inline]
952fn from(s: &CStr) -> Rc<CStr> {
953let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
954unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
955 }
956}
957958#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
959impl From<&mut CStr> for Rc<CStr> {
960/// Converts a `&mut CStr` into a `Rc<CStr>`,
961 /// by copying the contents into a newly allocated [`Rc`].
962#[inline]
963fn from(s: &mut CStr) -> Rc<CStr> {
964Rc::from(&*s)
965 }
966}
967968#[cfg(not(no_global_oom_handling))]
969#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
970impl Defaultfor Rc<CStr> {
971/// Creates an empty CStr inside an Rc
972 ///
973 /// This may or may not share an allocation with other Rcs on the same thread.
974#[inline]
975fn default() -> Self {
976Rc::from(c"")
977 }
978}
979980#[stable(feature = "default_box_extra", since = "1.17.0")]
981impl Defaultfor Box<CStr> {
982fn default() -> Box<CStr> {
983Box::from(c"")
984 }
985}
986987impl NulError {
988/// Returns the position of the nul byte in the slice that caused
989 /// [`CString::new`] to fail.
990 ///
991 /// # Examples
992 ///
993 /// ```
994 /// use std::ffi::CString;
995 ///
996 /// let nul_error = CString::new("foo\0bar").unwrap_err();
997 /// assert_eq!(nul_error.nul_position(), 3);
998 ///
999 /// let nul_error = CString::new("foo bar\0").unwrap_err();
1000 /// assert_eq!(nul_error.nul_position(), 7);
1001 /// ```
1002#[must_use]
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004pub fn nul_position(&self) -> usize {
1005self.0
1006}
10071008/// Consumes this error, returning the underlying vector of bytes which
1009 /// generated the error in the first place.
1010 ///
1011 /// # Examples
1012 ///
1013 /// ```
1014 /// use std::ffi::CString;
1015 ///
1016 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1017 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1018 /// ```
1019#[must_use = "`self` will be dropped if the result is not used"]
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021pub fn into_vec(self) -> Vec<u8> {
1022self.1
1023}
1024}
10251026#[stable(feature = "rust1", since = "1.0.0")]
1027impl fmt::Displayfor NulError {
1028fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1029f.write_fmt(format_args!("nul byte found in provided data at position: {0}",
self.0))write!(f, "nul byte found in provided data at position: {}", self.0)1030 }
1031}
10321033#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1034impl fmt::Displayfor FromVecWithNulError {
1035fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036match self.error_kind {
1037 FromBytesWithNulErrorKind::InteriorNul(pos) => {
1038f.write_fmt(format_args!("data provided contains an interior nul byte at pos {0}",
pos))write!(f, "data provided contains an interior nul byte at pos {pos}")1039 }
1040 FromBytesWithNulErrorKind::NotNulTerminated => {
1041f.write_fmt(format_args!("data provided is not nul terminated"))write!(f, "data provided is not nul terminated")1042 }
1043 }
1044 }
1045}
10461047impl IntoStringError {
1048/// Consumes this error, returning original [`CString`] which generated the
1049 /// error.
1050#[must_use = "`self` will be dropped if the result is not used"]
1051 #[stable(feature = "cstring_into", since = "1.7.0")]
1052pub fn into_cstring(self) -> CString {
1053self.inner
1054 }
10551056/// Access the underlying UTF-8 error that was the cause of this error.
1057#[must_use]
1058 #[stable(feature = "cstring_into", since = "1.7.0")]
1059pub fn utf8_error(&self) -> Utf8Error {
1060self.error
1061 }
1062}
10631064#[stable(feature = "cstring_into", since = "1.7.0")]
1065impl fmt::Displayfor IntoStringError {
1066fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1067"C string contained non-utf8 bytes".fmt(f)
1068 }
1069}
10701071#[stable(feature = "cstr_borrow", since = "1.3.0")]
1072impl ToOwnedfor CStr {
1073type Owned = CString;
10741075fn to_owned(&self) -> CString {
1076CString { inner: self.to_bytes_with_nul().into() }
1077 }
10781079fn clone_into(&self, target: &mut CString) {
1080let mut b = mem::take(&mut target.inner).into_vec();
1081self.to_bytes_with_nul().clone_into(&mut b);
1082target.inner = b.into_boxed_slice();
1083 }
1084}
10851086#[stable(feature = "cstring_asref", since = "1.7.0")]
1087impl From<&CStr> for CString {
1088/// Converts a <code>&[CStr]</code> into a [`CString`]
1089 /// by copying the contents into a new allocation.
1090fn from(s: &CStr) -> CString {
1091s.to_owned()
1092 }
1093}
10941095#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1096impl PartialEq<CStr> for CString {
1097#[inline]
1098fn eq(&self, other: &CStr) -> bool {
1099**self == *other1100 }
11011102#[inline]
1103fn ne(&self, other: &CStr) -> bool {
1104**self != *other1105 }
1106}
11071108#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1109impl PartialEq<&CStr> for CString {
1110#[inline]
1111fn eq(&self, other: &&CStr) -> bool {
1112**self == **other1113 }
11141115#[inline]
1116fn ne(&self, other: &&CStr) -> bool {
1117**self != **other1118 }
1119}
11201121#[cfg(not(no_global_oom_handling))]
1122#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1123impl PartialEq<Cow<'_, CStr>> for CString {
1124#[inline]
1125fn eq(&self, other: &Cow<'_, CStr>) -> bool {
1126**self == **other1127 }
11281129#[inline]
1130fn ne(&self, other: &Cow<'_, CStr>) -> bool {
1131**self != **other1132 }
1133}
11341135#[stable(feature = "cstring_asref", since = "1.7.0")]
1136impl ops::Index<ops::RangeFull> for CString {
1137type Output = CStr;
11381139#[inline]
1140fn index(&self, _index: ops::RangeFull) -> &CStr {
1141self1142 }
1143}
11441145#[stable(feature = "cstring_asref", since = "1.7.0")]
1146impl AsRef<CStr> for CString {
1147#[inline]
1148fn as_ref(&self) -> &CStr {
1149self1150 }
1151}
11521153impl CStr {
1154/// Converts a `CStr` into a <code>[Cow]<[str]></code>.
1155 ///
1156 /// If the contents of the `CStr` are valid UTF-8 data, this
1157 /// function will return a <code>[Cow]::[Borrowed]\(&[str])</code>
1158 /// with the corresponding <code>&[str]</code> slice. Otherwise, it will
1159 /// replace any invalid UTF-8 sequences with
1160 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1161 /// <code>[Cow]::[Owned]\([String])</code> with the result.
1162 ///
1163 /// [str]: prim@str "str"
1164 /// [Borrowed]: Cow::Borrowed
1165 /// [Owned]: Cow::Owned
1166 /// [U+FFFD]: core::char::REPLACEMENT_CHARACTER "std::char::REPLACEMENT_CHARACTER"
1167 ///
1168 /// # Examples
1169 ///
1170 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8. The leading
1171 /// `c` on the string literal denotes a `CStr`.
1172 ///
1173 /// ```
1174 /// use std::borrow::Cow;
1175 ///
1176 /// assert_eq!(c"Hello World".to_string_lossy(), Cow::Borrowed("Hello World"));
1177 /// ```
1178 ///
1179 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1180 ///
1181 /// ```
1182 /// use std::borrow::Cow;
1183 ///
1184 /// assert_eq!(
1185 /// c"Hello \xF0\x90\x80World".to_string_lossy(),
1186 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1187 /// );
1188 /// ```
1189#[rustc_allow_incoherent_impl]
1190 #[must_use = "this returns the result of the operation, \
1191 without modifying the original"]
1192 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1193pub fn to_string_lossy(&self) -> Cow<'_, str> {
1194String::from_utf8_lossy(self.to_bytes())
1195 }
11961197/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
1198 ///
1199 /// # Examples
1200 ///
1201 /// ```
1202 /// use std::ffi::{CStr, CString};
1203 ///
1204 /// let boxed: Box<CStr> = Box::from(c"foo");
1205 /// let c_string: CString = c"foo".to_owned();
1206 ///
1207 /// assert_eq!(boxed.into_c_string(), c_string);
1208 /// ```
1209#[rustc_allow_incoherent_impl]
1210 #[must_use = "`self` will be dropped if the result is not used"]
1211 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1212pub fn into_c_string(self: Box<Self>) -> CString {
1213CString::from(self)
1214 }
1215}
12161217#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1218impl PartialEq<CString> for CStr {
1219#[inline]
1220fn eq(&self, other: &CString) -> bool {
1221*self == **other1222 }
12231224#[inline]
1225fn ne(&self, other: &CString) -> bool {
1226*self != **other1227 }
1228}
12291230#[cfg(not(no_global_oom_handling))]
1231#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1232impl PartialEq<Cow<'_, Self>> for CStr {
1233#[inline]
1234fn eq(&self, other: &Cow<'_, Self>) -> bool {
1235*self == **other1236 }
12371238#[inline]
1239fn ne(&self, other: &Cow<'_, Self>) -> bool {
1240*self != **other1241 }
1242}
12431244#[cfg(not(no_global_oom_handling))]
1245#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1246impl PartialEq<CStr> for Cow<'_, CStr> {
1247#[inline]
1248fn eq(&self, other: &CStr) -> bool {
1249**self == *other1250 }
12511252#[inline]
1253fn ne(&self, other: &CStr) -> bool {
1254**self != *other1255 }
1256}
12571258#[cfg(not(no_global_oom_handling))]
1259#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1260impl PartialEq<&CStr> for Cow<'_, CStr> {
1261#[inline]
1262fn eq(&self, other: &&CStr) -> bool {
1263**self == **other1264 }
12651266#[inline]
1267fn ne(&self, other: &&CStr) -> bool {
1268**self != **other1269 }
1270}
12711272#[cfg(not(no_global_oom_handling))]
1273#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1274impl PartialEq<CString> for Cow<'_, CStr> {
1275#[inline]
1276fn eq(&self, other: &CString) -> bool {
1277**self == **other1278 }
12791280#[inline]
1281fn ne(&self, other: &CString) -> bool {
1282**self != **other1283 }
1284}
12851286#[stable(feature = "rust1", since = "1.0.0")]
1287impl core::error::Errorfor NulError {}
12881289#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1290impl core::error::Errorfor FromVecWithNulError {}
12911292#[stable(feature = "cstring_into", since = "1.7.0")]
1293impl core::error::Errorfor IntoStringError {
1294fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1295Some(&self.error)
1296 }
1297}