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::alloc::Allocator;
11use crate::borrow::{Cow, ToOwned};
12use crate::boxed::Box;
13use crate::rc::Rc;
14use crate::string::String;
15#[cfg(target_has_atomic = "ptr")]
16use crate::sync::Arc;
17use crate::vec::Vec;
1819/// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
20/// middle.
21///
22/// This type serves the purpose of being able to safely generate a
23/// C-compatible string from a Rust byte slice or vector. An instance of this
24/// type is a static guarantee that the underlying bytes contain no interior 0
25/// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
26///
27/// `CString` is to <code>&[CStr]</code> as [`String`] is to <code>&[str]</code>: the former
28/// in each pair are owned strings; the latter are borrowed
29/// references.
30///
31/// # Creating a `CString`
32///
33/// A `CString` is created from either a byte slice or a byte vector,
34/// or anything that implements <code>[Into]<[Vec]<[u8]>></code> (for
35/// example, you can build a `CString` straight out of a [`String`] or
36/// a <code>&[str]</code>, since both implement that trait).
37/// You can create a `CString` from a literal with `CString::from(c"Text")`.
38///
39/// The [`CString::new`] method will actually check that the provided <code>&[[u8]]</code>
40/// does not have 0 bytes in the middle, and return an error if it
41/// finds one.
42///
43/// # Extracting a raw pointer to the whole C string
44///
45/// `CString` implements an [`as_ptr`][`CStr::as_ptr`] method through the [`Deref`]
46/// trait. This method will give you a `*const c_char` which you can
47/// feed directly to extern functions that expect a nul-terminated
48/// string, like C's `strdup()`. Notice that [`as_ptr`][`CStr::as_ptr`] returns a
49/// read-only pointer; if the C code writes to it, that causes
50/// undefined behavior.
51///
52/// # Extracting a slice of the whole C string
53///
54/// Alternatively, you can obtain a <code>&[[u8]]</code> slice from a
55/// `CString` with the [`CString::as_bytes`] method. Slices produced in this
56/// way do *not* contain the trailing nul terminator. This is useful
57/// when you will be calling an extern function that takes a `*const
58/// u8` argument which is not necessarily nul-terminated, plus another
59/// argument with the length of the string — like C's `strndup()`.
60/// You can of course get the slice's length with its
61/// [`len`][slice::len] method.
62///
63/// If you need a <code>&[[u8]]</code> slice *with* the nul terminator, you
64/// can use [`CString::as_bytes_with_nul`] instead.
65///
66/// Once you have the kind of slice you need (with or without a nul
67/// terminator), you can call the slice's own
68/// [`as_ptr`][slice::as_ptr] method to get a read-only raw pointer to pass to
69/// extern functions. See the documentation for that function for a
70/// discussion on ensuring the lifetime of the raw pointer.
71///
72/// [str]: prim@str "str"
73/// [`Deref`]: ops::Deref
74///
75/// # Examples
76///
77/// ```ignore (extern-declaration)
78/// # fn main() {
79/// use std::ffi::CString;
80/// use std::os::raw::c_char;
81///
82/// extern "C" {
83/// fn my_printer(s: *const c_char);
84/// }
85///
86/// // We are certain that our string doesn't have 0 bytes in the middle,
87/// // so we can .expect()
88/// let c_to_print = CString::new("Hello, world!").expect("we provided a string without NUL bytes, so CString::new should not fail");
89/// unsafe {
90/// my_printer(c_to_print.as_ptr());
91/// }
92/// # }
93/// ```
94///
95/// # Safety
96///
97/// `CString` is intended for working with traditional C-style strings
98/// (a sequence of non-nul bytes terminated by a single nul byte); the
99/// primary use case for these kinds of strings is interoperating with C-like
100/// code. Often you will need to transfer ownership to/from that external
101/// code. It is strongly recommended that you thoroughly read through the
102/// documentation of `CString` before use, as improper ownership management
103/// of `CString` instances can lead to invalid memory accesses, memory leaks,
104/// and other memory errors.
105#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::marker::StructuralPartialEq for CString { }
#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for CString {
#[inline]
fn eq(&self, other: &Self) -> 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: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}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: &Self) -> ::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) -> Self {
CString { inner: ::core::clone::Clone::clone(&self.inner) }
}
}Clone)]
106#[rustc_diagnostic_item = "cstring_type"]
107#[rustc_insignificant_dtor]
108#[stable(feature = "alloc_c_string", since = "1.64.0")]
109pub struct CString {
110// Invariant 1: the slice ends with a zero byte and has a length of at least one.
111 // Invariant 2: the slice contains only one zero byte.
112 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
113inner: Box<[u8]>,
114}
115116/// An error indicating that an interior nul byte was found.
117///
118/// While Rust strings may contain nul bytes in the middle, C strings
119/// can't, as that byte would effectively truncate the string.
120///
121/// This error is created by the [`new`][`CString::new`] method on
122/// [`CString`]. See its documentation for more.
123///
124/// # Examples
125///
126/// ```
127/// use std::ffi::{CString, NulError};
128///
129/// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
130/// ```
131#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::clone::Clone for NulError {
#[inline]
fn clone(&self) -> Self {
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::marker::StructuralPartialEq for NulError { }
#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for NulError {
#[inline]
fn eq(&self, other: &Self) -> 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)]
132#[stable(feature = "alloc_c_string", since = "1.64.0")]
133pub struct NulError(usize, Vec<u8>);
134135#[derive(#[automatically_derived]
impl ::core::clone::Clone for FromBytesWithNulErrorKind {
#[inline]
fn clone(&self) -> Self {
match self {
Self::InteriorNul(__self_0) =>
FromBytesWithNulErrorKind::InteriorNul(::core::clone::Clone::clone(__self_0)),
Self::NotNulTerminated =>
FromBytesWithNulErrorKind::NotNulTerminated,
}
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for FromBytesWithNulErrorKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for FromBytesWithNulErrorKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::InteriorNul(__self_0), Self::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 {
Self::InteriorNul(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InteriorNul", &__self_0),
Self::NotNulTerminated =>
::core::fmt::Formatter::write_str(f, "NotNulTerminated"),
}
}
}Debug)]
136enum FromBytesWithNulErrorKind {
137 InteriorNul(usize),
138 NotNulTerminated,
139}
140141/// An error indicating that a nul byte was not in the expected position.
142///
143/// The vector used to create a [`CString`] must have one and only one nul byte,
144/// positioned at the end.
145///
146/// This error is created by the [`CString::from_vec_with_nul`] method.
147/// See its documentation for more.
148///
149/// # Examples
150///
151/// ```
152/// use std::ffi::{CString, FromVecWithNulError};
153///
154/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
155/// ```
156#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::clone::Clone for FromVecWithNulError {
#[inline]
fn clone(&self) -> Self {
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::marker::StructuralPartialEq for FromVecWithNulError { }
#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for FromVecWithNulError {
#[inline]
fn eq(&self, other: &Self) -> 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)]
157#[stable(feature = "alloc_c_string", since = "1.64.0")]
158pub struct FromVecWithNulError {
159 error_kind: FromBytesWithNulErrorKind,
160 bytes: Vec<u8>,
161}
162163#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
164impl FromVecWithNulError {
165/// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
166 ///
167 /// # Examples
168 ///
169 /// Basic usage:
170 ///
171 /// ```
172 /// use std::ffi::CString;
173 ///
174 /// // Some invalid bytes in a vector
175 /// let bytes = b"f\0oo".to_vec();
176 ///
177 /// let value = CString::from_vec_with_nul(bytes.clone());
178 ///
179 /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
180 /// ```
181#[must_use]
182 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
183pub fn as_bytes(&self) -> &[u8] {
184&self.bytes[..]
185 }
186187/// Returns the bytes that were attempted to convert to a [`CString`].
188 ///
189 /// This method is carefully constructed to avoid allocation. It will
190 /// consume the error, moving out the bytes, so that a copy of the bytes
191 /// does not need to be made.
192 ///
193 /// # Examples
194 ///
195 /// Basic usage:
196 ///
197 /// ```
198 /// use std::ffi::CString;
199 ///
200 /// // Some invalid bytes in a vector
201 /// let bytes = b"f\0oo".to_vec();
202 ///
203 /// let value = CString::from_vec_with_nul(bytes.clone());
204 ///
205 /// assert_eq!(bytes, value.unwrap_err().into_bytes());
206 /// ```
207#[must_use = "`self` will be dropped if the result is not used"]
208 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
209pub fn into_bytes(self) -> Vec<u8> {
210self.bytes
211 }
212}
213214/// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
215///
216/// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
217/// [`CString::into_string`] performs UTF-8 validation on those bytes and may
218/// return this error.
219///
220/// This `struct` is created by [`CString::into_string()`]. See
221/// its documentation for more.
222#[derive(#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::clone::Clone for IntoStringError {
#[inline]
fn clone(&self) -> Self {
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::marker::StructuralPartialEq for IntoStringError { }
#[automatically_derived]
#[stable(feature = "alloc_c_string", since = "1.64.0")]
impl ::core::cmp::PartialEq for IntoStringError {
#[inline]
fn eq(&self, other: &Self) -> 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)]
223#[stable(feature = "alloc_c_string", since = "1.64.0")]
224pub struct IntoStringError {
225 inner: CString,
226 error: Utf8Error,
227}
228229impl CString {
230/// Creates a new C-compatible string from a container of bytes.
231 ///
232 /// This function will consume the provided data and use the
233 /// underlying bytes to construct a new string, ensuring that
234 /// there is a trailing 0 byte. This trailing 0 byte will be
235 /// appended by this function; the provided data should *not*
236 /// contain any 0 bytes in it.
237 ///
238 /// # Examples
239 ///
240 /// ```ignore (extern-declaration)
241 /// use std::ffi::CString;
242 /// use std::os::raw::c_char;
243 ///
244 /// extern "C" { fn puts(s: *const c_char); }
245 ///
246 /// let to_print = CString::new("Hello!").expect("we provided a string without NUL bytes, so CString::new should not fail");
247 /// unsafe {
248 /// puts(to_print.as_ptr());
249 /// }
250 /// ```
251 ///
252 /// # Errors
253 ///
254 /// This function will return an error if the supplied bytes contain an
255 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
256 /// the position of the nul byte.
257#[stable(feature = "rust1", since = "1.0.0")]
258pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
259trait SpecNewImpl {
260fn spec_new_impl(self) -> Result<CString, NulError>;
261 }
262263impl<T: Into<Vec<u8>>> SpecNewImplfor T {
264 default fn spec_new_impl(self) -> Result<CString, NulError> {
265let bytes: Vec<u8> = self.into();
266match memchr::memchr(0, &bytes) {
267Some(i) => Err(NulError(i, bytes)),
268// SAFETY: We ensured there's no null bytes.
269None => Ok(unsafe { CString::_from_vec_unchecked(bytes) }),
270 }
271 }
272 }
273274// Specialization for avoiding reallocation
275#[inline(always)] // Without that it is not inlined into specializations
276fn spec_new_impl_bytes(bytes: &[u8]) -> Result<CString, NulError> {
277// We cannot have such large slice that we would overflow here
278 // but using `checked_add` allows LLVM to assume that capacity never overflows
279 // and generate twice shorter code.
280 // `saturating_add` doesn't help for some reason.
281let capacity = bytes.len().checked_add(1).unwrap();
282283// Allocate before validation to avoid duplication of allocation code.
284 // We still need to allocate and copy memory even if we get an error.
285let mut buffer = Vec::with_capacity(capacity);
286buffer.extend(bytes);
287288// Check memory of self instead of new buffer.
289 // This allows better optimizations if lto enabled.
290match memchr::memchr(0, bytes) {
291Some(i) => Err(NulError(i, buffer)),
292// SAFETY: We ensured there's no null bytes.
293None => Ok(unsafe { CString::_from_vec_unchecked(buffer) }),
294 }
295 }
296297impl SpecNewImplfor &'_ [u8] {
298fn spec_new_impl(self) -> Result<CString, NulError> {
299spec_new_impl_bytes(self)
300 }
301 }
302303impl SpecNewImplfor &'_ str {
304fn spec_new_impl(self) -> Result<CString, NulError> {
305spec_new_impl_bytes(self.as_bytes())
306 }
307 }
308309impl SpecNewImplfor &'_ mut [u8] {
310fn spec_new_impl(self) -> Result<CString, NulError> {
311spec_new_impl_bytes(self)
312 }
313 }
314315t.spec_new_impl()
316 }
317318/// Creates a C-compatible string by consuming a byte vector,
319 /// without checking for interior 0 bytes.
320 ///
321 /// Trailing 0 byte will be appended by this function.
322 ///
323 /// This method is equivalent to [`CString::new`] except that no runtime
324 /// assertion is made that `v` contains no 0 bytes, and it requires an
325 /// actual byte vector, not anything that can be converted to one with Into.
326 ///
327 /// # Safety
328 ///
329 /// The caller must ensure `v` contains no nul bytes in its contents.
330 ///
331 /// # Examples
332 ///
333 /// ```
334 /// use std::ffi::CString;
335 ///
336 /// let raw = b"foo".to_vec();
337 /// unsafe {
338 /// let c_string = CString::from_vec_unchecked(raw);
339 /// }
340 /// ```
341#[must_use]
342 #[stable(feature = "rust1", since = "1.0.0")]
343pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> Self {
344if 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());
345// SAFETY: Upheld by caller.
346unsafe { Self::_from_vec_unchecked(v) }
347 }
348349unsafe fn _from_vec_unchecked(mut v: Vec<u8>) -> Self {
350v.reserve_exact(1);
351v.push(0);
352Self { inner: v.into_boxed_slice() }
353 }
354355/// Retakes ownership of a `CString` that was transferred to C via
356 /// [`CString::into_raw`].
357 ///
358 /// Additionally, the length of the string will be recalculated from the pointer.
359 ///
360 /// # Safety
361 ///
362 /// This should only ever be called with a pointer that was earlier
363 /// obtained by calling [`CString::into_raw`], and the memory it points to must not be accessed
364 /// through any other pointer during the lifetime of reconstructed `CString`.
365 /// Other usage (e.g., trying to take ownership of a string that was allocated by foreign code)
366 /// is likely to lead to undefined behavior or allocator corruption.
367 ///
368 /// This function does not validate ownership of the raw pointer's memory.
369 /// A double-free may occur if the function is called twice on the same raw pointer.
370 /// Additionally, the caller must ensure the pointer is not dangling.
371 ///
372 /// It should be noted that the length isn't just "recomputed," but that
373 /// the recomputed length must match the original length from the
374 /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
375 /// methods should not be used when passing the string to C functions that can
376 /// modify the string's length.
377 ///
378 /// > **Note:** If you need to borrow a string that was allocated by
379 /// > foreign code, use [`CStr`]. If you need to take ownership of
380 /// > a string that was allocated by foreign code, you will need to
381 /// > make your own provisions for freeing it appropriately, likely
382 /// > with the foreign code's API to do that.
383 ///
384 /// # Examples
385 ///
386 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
387 /// ownership with `from_raw`:
388 ///
389 /// ```ignore (extern-declaration)
390 /// use std::ffi::CString;
391 /// use std::os::raw::c_char;
392 ///
393 /// extern "C" {
394 /// fn some_extern_function(s: *mut c_char);
395 /// }
396 ///
397 /// let c_string = CString::from(c"Hello!");
398 /// let raw = c_string.into_raw();
399 /// unsafe {
400 /// some_extern_function(raw);
401 /// let c_string = CString::from_raw(raw);
402 /// }
403 /// ```
404#[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
405 #[stable(feature = "cstr_memory", since = "1.4.0")]
406pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
407// SAFETY: This is called with a pointer that was obtained from a call
408 // to `CString::into_raw` and the length has not been modified. As such,
409 // we know there is a NUL byte (and only one) at the end and that the
410 // information about the size of the allocation is correct on Rust's
411 // side.
412unsafe {
413unsafe extern "C" {
414/// Provided by libc or compiler_builtins.
415fn strlen(s: *const c_char) -> usize;
416 }
417let len = strlen(ptr) + 1; // Including the NUL byte
418let slice = slice::from_raw_parts_mut(ptr, len);
419CString { inner: Box::from_raw(sliceas *mut [c_char] as *mut [u8]) }
420 }
421 }
422423/// Consumes the `CString` and transfers ownership of the string to a C caller.
424 ///
425 /// The pointer which this function returns must be returned to Rust and reconstituted using
426 /// [`CString::from_raw`] to be properly deallocated. Specifically, one
427 /// should *not* use the standard C `free()` function to deallocate
428 /// this string.
429 ///
430 /// Failure to call [`CString::from_raw`] will lead to a memory leak.
431 ///
432 /// The C side must **not** modify the length of the string (by writing a
433 /// nul byte somewhere inside the string or removing the final one) before
434 /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
435 /// in [`CString::from_raw`].
436 ///
437 /// # Examples
438 ///
439 /// ```
440 /// use std::ffi::CString;
441 ///
442 /// let c_string = CString::from(c"foo");
443 ///
444 /// let ptr = c_string.into_raw();
445 ///
446 /// unsafe {
447 /// assert_eq!(b'f', *ptr as u8);
448 /// assert_eq!(b'o', *ptr.add(1) as u8);
449 /// assert_eq!(b'o', *ptr.add(2) as u8);
450 /// assert_eq!(b'\0', *ptr.add(3) as u8);
451 ///
452 /// // retake pointer to free memory
453 /// let _ = CString::from_raw(ptr);
454 /// }
455 /// ```
456#[inline]
457 #[must_use = "`self` will be dropped if the result is not used"]
458 #[stable(feature = "cstr_memory", since = "1.4.0")]
459pub fn into_raw(self) -> *mut c_char {
460Box::into_raw(self.into_inner()) as *mut c_char461 }
462463/// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
464 ///
465 /// On failure, ownership of the original `CString` is returned.
466 ///
467 /// # Examples
468 ///
469 /// ```
470 /// use std::ffi::CString;
471 ///
472 /// let valid_utf8 = vec![b'f', b'o', b'o'];
473 /// let cstring = CString::new(valid_utf8).expect("we provided bytes that do not have a NUL byte, so CString::new should not fail");
474 /// assert_eq!(cstring.into_string().expect("we provided bytes that are valid UTF-8, so `into_string` should not fail"), "foo");
475 ///
476 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
477 /// let cstring = CString::new(invalid_utf8).expect("we provided bytes that do not have a NUL byte, so CString::new should not fail");
478 /// let err = cstring.into_string().expect_err("we provided bytes that are invalid UTF-8, so `into_string` should fail");
479 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
480 /// ```
481#[stable(feature = "cstring_into", since = "1.7.0")]
482pub fn into_string(self) -> Result<String, IntoStringError> {
483String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
484 error: e.utf8_error(),
485// SAFETY: `CString`s never contain null bytes.
486inner: unsafe { Self::_from_vec_unchecked(e.into_bytes()) },
487 })
488 }
489490/// Consumes the `CString` and returns the underlying byte buffer.
491 ///
492 /// The returned buffer does **not** contain the trailing nul
493 /// terminator, and it is guaranteed to not have any interior nul
494 /// bytes.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// use std::ffi::CString;
500 ///
501 /// let c_string = CString::from(c"foo");
502 /// let bytes = c_string.into_bytes();
503 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
504 /// ```
505#[must_use = "`self` will be dropped if the result is not used"]
506 #[stable(feature = "cstring_into", since = "1.7.0")]
507pub fn into_bytes(self) -> Vec<u8> {
508let mut vec = self.into_inner().into_vec();
509let _nul = vec.pop();
510if 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));
511vec512 }
513514/// Equivalent to [`CString::into_bytes()`] except that the
515 /// returned vector includes the trailing nul terminator.
516 ///
517 /// # Examples
518 ///
519 /// ```
520 /// use std::ffi::CString;
521 ///
522 /// let c_string = CString::from(c"foo");
523 /// let bytes = c_string.into_bytes_with_nul();
524 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
525 /// ```
526#[must_use = "`self` will be dropped if the result is not used"]
527 #[stable(feature = "cstring_into", since = "1.7.0")]
528pub fn into_bytes_with_nul(self) -> Vec<u8> {
529self.into_inner().into_vec()
530 }
531532/// Returns the contents of this `CString` as a slice of bytes.
533 ///
534 /// The returned slice does **not** contain the trailing nul
535 /// terminator, and it is guaranteed to not have any interior nul
536 /// bytes. If you need the nul terminator, use
537 /// [`CString::as_bytes_with_nul`] instead.
538 ///
539 /// # Examples
540 ///
541 /// ```
542 /// use std::ffi::CString;
543 ///
544 /// let c_string = CString::from(c"foo");
545 /// let bytes = c_string.as_bytes();
546 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
547 /// ```
548#[inline]
549 #[must_use]
550 #[stable(feature = "rust1", since = "1.0.0")]
551pub fn as_bytes(&self) -> &[u8] {
552// SAFETY: CString has a length at least 1
553unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
554 }
555556/// Equivalent to [`CString::as_bytes()`] except that the
557 /// returned slice includes the trailing nul terminator.
558 ///
559 /// # Examples
560 ///
561 /// ```
562 /// use std::ffi::CString;
563 ///
564 /// let c_string = CString::from(c"foo");
565 /// let bytes = c_string.as_bytes_with_nul();
566 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
567 /// ```
568#[inline]
569 #[must_use]
570 #[stable(feature = "rust1", since = "1.0.0")]
571pub fn as_bytes_with_nul(&self) -> &[u8] {
572&self.inner
573 }
574575/// Extracts a [`CStr`] slice containing the entire string.
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use std::ffi::{CString, CStr};
581 ///
582 /// let c_string = CString::from(c"foo");
583 /// let cstr = c_string.as_c_str();
584 /// assert_eq!(cstr,
585 /// CStr::from_bytes_with_nul(b"foo\0").expect("we provided bytes that has one NUL byte exactly at the end, so CStr::from_bytes_with_nul should not fail"));
586 /// ```
587#[inline]
588 #[must_use]
589 #[stable(feature = "as_c_str", since = "1.20.0")]
590 #[rustc_diagnostic_item = "cstring_as_c_str"]
591pub fn as_c_str(&self) -> &CStr {
592// SAFETY: Ensured by `as_bytes_with_nul`.
593unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
594 }
595596/// Converts this `CString` into a boxed [`CStr`].
597 ///
598 /// # Examples
599 ///
600 /// ```
601 /// let c_string = c"foo".to_owned();
602 /// let boxed = c_string.into_boxed_c_str();
603 /// assert_eq!(boxed.to_bytes_with_nul(), b"foo\0");
604 /// ```
605#[must_use = "`self` will be dropped if the result is not used"]
606 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
607pub fn into_boxed_c_str(self) -> Box<CStr> {
608// SAFETY: Typecast of [u8] to CStr is valid and we know contents have
609 // no nulls except for the terminating byte.
610unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
611 }
612613/// Bypass "move out of struct which implements [`Drop`] trait" restriction.
614#[inline]
615fn into_inner(self) -> Box<[u8]> {
616let this = mem::ManuallyDrop::new(self);
617// SAFETY: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
618 // so we use `ManuallyDrop` to ensure `self` is not dropped.
619 // Then we can return the box directly without invalidating it.
620 // See https://github.com/rust-lang/rust/issues/62553.
621unsafe { ptr::read(&this.inner) }
622 }
623624/// Converts a <code>[Vec]<[u8]></code> to a [`CString`] without checking the
625 /// invariants on the given [`Vec`].
626 ///
627 /// # Safety
628 ///
629 /// The given [`Vec`] **must** have one nul byte as its last element.
630 /// This means it cannot be empty nor have any other nul byte anywhere else.
631 ///
632 /// # Example
633 ///
634 /// ```
635 /// use std::ffi::CString;
636 /// assert_eq!(
637 /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
638 /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
639 /// );
640 /// ```
641#[must_use]
642 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
643pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
644if 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());
645// SAFETY: Upheld by caller.
646unsafe { Self::_from_vec_with_nul_unchecked(v) }
647 }
648649unsafe fn _from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
650Self { inner: v.into_boxed_slice() }
651 }
652653/// Attempts to convert a <code>[Vec]<[u8]></code> to a [`CString`].
654 ///
655 /// Runtime checks are present to ensure there is only one nul byte in the
656 /// [`Vec`], its last element.
657 ///
658 /// # Errors
659 ///
660 /// If a nul byte is present and not the last element or no nul bytes
661 /// is present, an error will be returned.
662 ///
663 /// # Examples
664 ///
665 /// A successful conversion will produce the same result as [`CString::new`]
666 /// when called without the ending nul byte.
667 ///
668 /// ```
669 /// use std::ffi::CString;
670 /// assert_eq!(
671 /// CString::from_vec_with_nul(b"abc\0".to_vec())
672 /// .expect("we provided bytes that has one NUL byte exactly at the end, so CString::from_vec_with_nul should not fail"),
673 /// c"abc".to_owned()
674 /// );
675 /// ```
676 ///
677 /// An incorrectly formatted [`Vec`] will produce an error.
678 ///
679 /// ```
680 /// use std::ffi::{CString, FromVecWithNulError};
681 /// // Interior nul byte
682 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
683 /// // No nul byte
684 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
685 /// ```
686#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
687pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
688let nul_pos = memchr::memchr(0, &v);
689match nul_pos {
690Some(nul_pos) if nul_pos + 1 == v.len() => {
691// SAFETY: We know there is only one nul byte, at the end
692 // of the vec.
693Ok(unsafe { Self::_from_vec_with_nul_unchecked(v) })
694 }
695Some(nul_pos) => Err(FromVecWithNulError {
696 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
697 bytes: v,
698 }),
699None => Err(FromVecWithNulError {
700 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
701 bytes: v,
702 }),
703 }
704 }
705}
706707// Turns this `CString` into an empty string to prevent
708// memory-unsafe code from working by accident. Inline
709// to prevent LLVM from optimizing it away in debug builds.
710#[stable(feature = "cstring_drop", since = "1.13.0")]
711impl Dropfor CString {
712#[inline]
713fn drop(&mut self) {
714// SAFETY: Length is always at least one.
715unsafe {
716*self.inner.get_unchecked_mut(0) = 0;
717 }
718 }
719}
720721#[stable(feature = "rust1", since = "1.0.0")]
722impl ops::Dereffor CString {
723type Target = CStr;
724725#[inline]
726fn deref(&self) -> &CStr {
727self.as_c_str()
728 }
729}
730731/// Delegates to the [`CStr`] implementation of [`fmt::Debug`],
732/// showing invalid UTF-8 as hex escapes.
733#[stable(feature = "rust1", since = "1.0.0")]
734impl fmt::Debugfor CString {
735fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736 fmt::Debug::fmt(self.as_c_str(), f)
737 }
738}
739740#[stable(feature = "cstring_into", since = "1.7.0")]
741impl From<CString> for Vec<u8> {
742/// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
743 ///
744 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
745#[inline]
746fn from(s: CString) -> Vec<u8> {
747s.into_bytes()
748 }
749}
750751#[stable(feature = "cstr_default", since = "1.10.0")]
752impl Defaultfor CString {
753/// Creates an empty `CString`.
754fn default() -> CString {
755let a: &CStr = Default::default();
756a.to_owned()
757 }
758}
759760#[stable(feature = "cstr_borrow", since = "1.3.0")]
761impl Borrow<CStr> for CString {
762#[inline]
763fn borrow(&self) -> &CStr {
764self765 }
766}
767768#[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
769impl<'a> From<Cow<'a, CStr>> for CString {
770/// Converts a `Cow<'a, CStr>` into a `CString`, by copying the contents if they are
771 /// borrowed.
772#[inline]
773fn from(s: Cow<'a, CStr>) -> Self {
774s.into_owned()
775 }
776}
777778#[stable(feature = "box_from_c_str", since = "1.17.0")]
779impl From<&CStr> for Box<CStr> {
780/// Converts a `&CStr` into a `Box<CStr>`,
781 /// by copying the contents into a newly allocated [`Box`].
782fn from(s: &CStr) -> Box<CStr> {
783Box::clone_from_ref(s)
784 }
785}
786787#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
788impl From<&mut CStr> for Box<CStr> {
789/// Converts a `&mut CStr` into a `Box<CStr>`,
790 /// by copying the contents into a newly allocated [`Box`].
791fn from(s: &mut CStr) -> Box<CStr> {
792Self::from(&*s)
793 }
794}
795796#[stable(feature = "box_from_cow", since = "1.45.0")]
797impl From<Cow<'_, CStr>> for Box<CStr> {
798/// Converts a `Cow<'a, CStr>` into a `Box<CStr>`,
799 /// by copying the contents if they are borrowed.
800#[inline]
801fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
802match cow {
803 Cow::Borrowed(s) => Box::from(s),
804 Cow::Owned(s) => Box::from(s),
805 }
806 }
807}
808809#[stable(feature = "c_string_from_box", since = "1.18.0")]
810impl From<Box<CStr>> for CString {
811/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
812#[inline]
813fn from(s: Box<CStr>) -> CString {
814let raw = Box::into_raw(s) as *mut [u8];
815// SAFETY: Converting a *mut CStr -> *mut [u8] -> CString is valid.
816CString { inner: unsafe { Box::from_raw(raw) } }
817 }
818}
819820#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
821impl From<Vec<NonZero<u8>>> for CString {
822/// Converts a <code>[Vec]<[NonZero]<[u8]>></code> into a [`CString`] without
823 /// copying nor checking for inner nul bytes.
824#[inline]
825fn from(v: Vec<NonZero<u8>>) -> CString {
826// Transmute `Vec<NonZero<u8>>` to `Vec<u8>`.
827let v: Vec<u8> = {
828let (ptr, len, cap): (*mut NonZero<u8>, _, _) = Vec::into_raw_parts(v);
829// SAFETY:
830 // - transmuting between `NonZero<u8>` and `u8` is sound;
831 // - `alloc::Layout<NonZero<u8>> == alloc::Layout<u8>`.
832unsafe { Vec::from_raw_parts(ptr.cast::<u8>(), len, cap) }
833 };
834// SAFETY: `v` cannot contain nul bytes, given the type-level
835 // invariant of `NonZero<u8>`.
836unsafe { Self::_from_vec_unchecked(v) }
837 }
838}
839840#[stable(feature = "c_string_from_str", since = "1.85.0")]
841impl FromStrfor CString {
842type Err = NulError;
843844/// Converts a string `s` into a [`CString`].
845 ///
846 /// This method is equivalent to [`CString::new`].
847#[inline]
848fn from_str(s: &str) -> Result<Self, Self::Err> {
849Self::new(s)
850 }
851}
852853#[stable(feature = "c_string_from_str", since = "1.85.0")]
854impl TryFrom<CString> for String {
855type Error = IntoStringError;
856857/// Converts a [`CString`] into a [`String`] if it contains valid UTF-8 data.
858 ///
859 /// This method is equivalent to [`CString::into_string`].
860#[inline]
861fn try_from(value: CString) -> Result<Self, Self::Error> {
862value.into_string()
863 }
864}
865866#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
867impl<A: Allocator + Clone> Clonefor Box<CStr, A> {
868#[inline]
869fn clone(&self) -> Self {
870Box::clone_from_ref_in(&**self, Self::allocator(self).clone())
871 }
872}
873874#[stable(feature = "box_from_c_string", since = "1.20.0")]
875impl From<CString> for Box<CStr> {
876/// Converts a [`CString`] into a <code>[Box]<[CStr]></code> without copying or allocating.
877#[inline]
878fn from(s: CString) -> Box<CStr> {
879s.into_boxed_c_str()
880 }
881}
882883#[stable(feature = "cow_from_cstr", since = "1.28.0")]
884impl<'a> From<CString> for Cow<'a, CStr> {
885/// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
886#[inline]
887fn from(s: CString) -> Cow<'a, CStr> {
888 Cow::Owned(s)
889 }
890}
891892#[stable(feature = "cow_from_cstr", since = "1.28.0")]
893impl<'a> From<&'a CStr> for Cow<'a, CStr> {
894/// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
895#[inline]
896fn from(s: &'a CStr) -> Cow<'a, CStr> {
897 Cow::Borrowed(s)
898 }
899}
900901#[stable(feature = "cow_from_cstr", since = "1.28.0")]
902impl<'a> From<&'a CString> for Cow<'a, CStr> {
903/// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
904#[inline]
905fn from(s: &'a CString) -> Cow<'a, CStr> {
906 Cow::Borrowed(s.as_c_str())
907 }
908}
909910#[cfg(target_has_atomic = "ptr")]
911#[stable(feature = "shared_from_slice2", since = "1.24.0")]
912impl From<CString> for Arc<CStr> {
913/// Converts a [`CString`] into an <code>[Arc]<[CStr]></code> by moving the [`CString`]
914 /// data into a new [`Arc`] buffer.
915#[inline]
916fn from(s: CString) -> Arc<CStr> {
917let arc: Arc<[u8]> = Arc::from(s.into_inner());
918// SAFETY: Type conversion is valid.
919unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
920 }
921}
922923#[cfg(target_has_atomic = "ptr")]
924#[stable(feature = "shared_from_slice2", since = "1.24.0")]
925impl From<&CStr> for Arc<CStr> {
926/// Converts a `&CStr` into a `Arc<CStr>`,
927 /// by copying the contents into a newly allocated [`Arc`].
928#[inline]
929fn from(s: &CStr) -> Arc<CStr> {
930let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
931// SAFETY: Type conversion is valid.
932unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
933 }
934}
935936#[cfg(target_has_atomic = "ptr")]
937#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
938impl From<&mut CStr> for Arc<CStr> {
939/// Converts a `&mut CStr` into a `Arc<CStr>`,
940 /// by copying the contents into a newly allocated [`Arc`].
941#[inline]
942fn from(s: &mut CStr) -> Arc<CStr> {
943Arc::from(&*s)
944 }
945}
946947#[stable(feature = "shared_from_slice2", since = "1.24.0")]
948impl From<CString> for Rc<CStr> {
949/// Converts a [`CString`] into an <code>[Rc]<[CStr]></code> by moving the [`CString`]
950 /// data into a new [`Rc`] buffer.
951#[inline]
952fn from(s: CString) -> Rc<CStr> {
953let rc: Rc<[u8]> = Rc::from(s.into_inner());
954// SAFETY: Type conversion is valid.
955unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
956 }
957}
958959#[stable(feature = "shared_from_slice2", since = "1.24.0")]
960impl From<&CStr> for Rc<CStr> {
961/// Converts a `&CStr` into a `Rc<CStr>`,
962 /// by copying the contents into a newly allocated [`Rc`].
963#[inline]
964fn from(s: &CStr) -> Rc<CStr> {
965let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
966// SAFETY: Type conversion is valid.
967unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
968 }
969}
970971#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
972impl From<&mut CStr> for Rc<CStr> {
973/// Converts a `&mut CStr` into a `Rc<CStr>`,
974 /// by copying the contents into a newly allocated [`Rc`].
975#[inline]
976fn from(s: &mut CStr) -> Rc<CStr> {
977Rc::from(&*s)
978 }
979}
980981#[cfg(not(no_global_oom_handling))]
982#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
983impl Defaultfor Rc<CStr> {
984/// Creates an empty CStr inside an Rc
985 ///
986 /// This may or may not share an allocation with other Rcs on the same thread.
987#[inline]
988fn default() -> Self {
989Rc::from(c"")
990 }
991}
992993#[stable(feature = "default_box_extra", since = "1.17.0")]
994impl Defaultfor Box<CStr> {
995fn default() -> Box<CStr> {
996Box::from(c"")
997 }
998}
9991000impl NulError {
1001/// Returns the position of the nul byte in the slice that caused
1002 /// [`CString::new`] to fail.
1003 ///
1004 /// # Examples
1005 ///
1006 /// ```
1007 /// use std::ffi::CString;
1008 ///
1009 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1010 /// assert_eq!(nul_error.nul_position(), 3);
1011 ///
1012 /// let nul_error = CString::new("foo bar\0").unwrap_err();
1013 /// assert_eq!(nul_error.nul_position(), 7);
1014 /// ```
1015#[must_use]
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017pub fn nul_position(&self) -> usize {
1018self.0
1019}
10201021/// Consumes this error, returning the underlying vector of bytes which
1022 /// generated the error in the first place.
1023 ///
1024 /// # Examples
1025 ///
1026 /// ```
1027 /// use std::ffi::CString;
1028 ///
1029 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1030 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1031 /// ```
1032#[must_use = "`self` will be dropped if the result is not used"]
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034pub fn into_vec(self) -> Vec<u8> {
1035self.1
1036}
1037}
10381039#[stable(feature = "rust1", since = "1.0.0")]
1040impl fmt::Displayfor NulError {
1041fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1042f.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)1043 }
1044}
10451046#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1047impl fmt::Displayfor FromVecWithNulError {
1048fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1049match self.error_kind {
1050 FromBytesWithNulErrorKind::InteriorNul(pos) => {
1051f.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}")1052 }
1053 FromBytesWithNulErrorKind::NotNulTerminated => {
1054f.write_fmt(format_args!("data provided is not nul terminated"))write!(f, "data provided is not nul terminated")1055 }
1056 }
1057 }
1058}
10591060impl IntoStringError {
1061/// Consumes this error, returning original [`CString`] which generated the
1062 /// error.
1063#[must_use = "`self` will be dropped if the result is not used"]
1064 #[stable(feature = "cstring_into", since = "1.7.0")]
1065pub fn into_cstring(self) -> CString {
1066self.inner
1067 }
10681069/// Access the underlying UTF-8 error that was the cause of this error.
1070#[must_use]
1071 #[stable(feature = "cstring_into", since = "1.7.0")]
1072pub fn utf8_error(&self) -> Utf8Error {
1073self.error
1074 }
1075}
10761077#[stable(feature = "cstring_into", since = "1.7.0")]
1078impl fmt::Displayfor IntoStringError {
1079fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080"C string contained non-utf8 bytes".fmt(f)
1081 }
1082}
10831084#[stable(feature = "cstr_borrow", since = "1.3.0")]
1085impl ToOwnedfor CStr {
1086type Owned = CString;
10871088fn to_owned(&self) -> CString {
1089CString { inner: self.to_bytes_with_nul().into() }
1090 }
10911092fn clone_into(&self, target: &mut CString) {
1093let src = self.to_bytes_with_nul();
1094// If the lengths match, we can reuse the existing allocation without any overhead.
1095if target.inner.len() == src.len() {
1096target.inner.copy_from_slice(src);
1097 } else {
1098// Reuse the existing allocation's capacity by converting to a Vec.
1099 // We temporarily replace `target` with a valid dummy to remain panic-safe.
1100let mut b = mem::replace(&mut target.inner, Box::new([0])).into_vec();
1101self.to_bytes_with_nul().clone_into(&mut b);
1102target.inner = b.into_boxed_slice();
1103 }
1104 }
1105}
11061107#[stable(feature = "cstring_asref", since = "1.7.0")]
1108impl From<&CStr> for CString {
1109/// Converts a <code>&[CStr]</code> into a [`CString`]
1110 /// by copying the contents into a new allocation.
1111fn from(s: &CStr) -> CString {
1112s.to_owned()
1113 }
1114}
11151116#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1117impl PartialEq<CStr> for CString {
1118#[inline]
1119fn eq(&self, other: &CStr) -> bool {
1120**self == *other1121 }
11221123#[inline]
1124fn ne(&self, other: &CStr) -> bool {
1125**self != *other1126 }
1127}
11281129#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1130impl PartialEq<&CStr> for CString {
1131#[inline]
1132fn eq(&self, other: &&CStr) -> bool {
1133**self == **other1134 }
11351136#[inline]
1137fn ne(&self, other: &&CStr) -> bool {
1138**self != **other1139 }
1140}
11411142#[cfg(not(no_global_oom_handling))]
1143#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1144impl PartialEq<Cow<'_, CStr>> for CString {
1145#[inline]
1146fn eq(&self, other: &Cow<'_, CStr>) -> bool {
1147**self == **other1148 }
11491150#[inline]
1151fn ne(&self, other: &Cow<'_, CStr>) -> bool {
1152**self != **other1153 }
1154}
11551156#[stable(feature = "cstring_asref", since = "1.7.0")]
1157impl ops::Index<ops::RangeFull> for CString {
1158type Output = CStr;
11591160#[inline]
1161fn index(&self, _index: ops::RangeFull) -> &CStr {
1162self1163 }
1164}
11651166#[stable(feature = "cstring_asref", since = "1.7.0")]
1167impl AsRef<CStr> for CString {
1168#[inline]
1169fn as_ref(&self) -> &CStr {
1170self1171 }
1172}
11731174impl CStr {
1175/// Converts a `CStr` into a <code>[Cow]<[str]></code>.
1176 ///
1177 /// If the contents of the `CStr` are valid UTF-8 data, this
1178 /// function will return a <code>[Cow]::[Borrowed]\(&[str])</code>
1179 /// with the corresponding <code>&[str]</code> slice. Otherwise, it will
1180 /// replace any invalid UTF-8 sequences with
1181 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1182 /// <code>[Cow]::[Owned]\([String])</code> with the result.
1183 ///
1184 /// [str]: prim@str "str"
1185 /// [Borrowed]: Cow::Borrowed
1186 /// [Owned]: Cow::Owned
1187 /// [U+FFFD]: char::REPLACEMENT_CHARACTER
1188 ///
1189 /// # Examples
1190 ///
1191 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8. The leading
1192 /// `c` on the string literal denotes a `CStr`.
1193 ///
1194 /// ```
1195 /// use std::borrow::Cow;
1196 ///
1197 /// assert_eq!(c"Hello World".to_string_lossy(), Cow::Borrowed("Hello World"));
1198 /// ```
1199 ///
1200 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1201 ///
1202 /// ```
1203 /// use std::borrow::Cow;
1204 ///
1205 /// assert_eq!(
1206 /// c"Hello \xF0\x90\x80World".to_string_lossy(),
1207 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1208 /// );
1209 /// ```
1210#[rustc_allow_incoherent_impl]
1211 #[must_use = "this returns the result of the operation, \
1212 without modifying the original"]
1213 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1214pub fn to_string_lossy(&self) -> Cow<'_, str> {
1215String::from_utf8_lossy(self.to_bytes())
1216 }
12171218/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
1219 ///
1220 /// # Examples
1221 ///
1222 /// ```
1223 /// use std::ffi::{CStr, CString};
1224 ///
1225 /// let boxed: Box<CStr> = Box::from(c"foo");
1226 /// let c_string: CString = c"foo".to_owned();
1227 ///
1228 /// assert_eq!(boxed.into_c_string(), c_string);
1229 /// ```
1230#[rustc_allow_incoherent_impl]
1231 #[must_use = "`self` will be dropped if the result is not used"]
1232 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1233pub fn into_c_string(self: Box<Self>) -> CString {
1234CString::from(self)
1235 }
1236}
12371238#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1239impl PartialEq<CString> for CStr {
1240#[inline]
1241fn eq(&self, other: &CString) -> bool {
1242*self == **other1243 }
12441245#[inline]
1246fn ne(&self, other: &CString) -> bool {
1247*self != **other1248 }
1249}
12501251#[cfg(not(no_global_oom_handling))]
1252#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1253impl PartialEq<Cow<'_, Self>> for CStr {
1254#[inline]
1255fn eq(&self, other: &Cow<'_, Self>) -> bool {
1256*self == **other1257 }
12581259#[inline]
1260fn ne(&self, other: &Cow<'_, Self>) -> bool {
1261*self != **other1262 }
1263}
12641265#[cfg(not(no_global_oom_handling))]
1266#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1267impl PartialEq<CStr> for Cow<'_, CStr> {
1268#[inline]
1269fn eq(&self, other: &CStr) -> bool {
1270**self == *other1271 }
12721273#[inline]
1274fn ne(&self, other: &CStr) -> bool {
1275**self != *other1276 }
1277}
12781279#[cfg(not(no_global_oom_handling))]
1280#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1281impl PartialEq<&CStr> for Cow<'_, CStr> {
1282#[inline]
1283fn eq(&self, other: &&CStr) -> bool {
1284**self == **other1285 }
12861287#[inline]
1288fn ne(&self, other: &&CStr) -> bool {
1289**self != **other1290 }
1291}
12921293#[cfg(not(no_global_oom_handling))]
1294#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1295impl PartialEq<CString> for Cow<'_, CStr> {
1296#[inline]
1297fn eq(&self, other: &CString) -> bool {
1298**self == **other1299 }
13001301#[inline]
1302fn ne(&self, other: &CString) -> bool {
1303**self != **other1304 }
1305}
13061307#[stable(feature = "rust1", since = "1.0.0")]
1308impl core::error::Errorfor NulError {}
13091310#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1311impl core::error::Errorfor FromVecWithNulError {}
13121313#[stable(feature = "cstring_into", since = "1.7.0")]
1314impl core::error::Errorfor IntoStringError {
1315fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1316Some(&self.error)
1317 }
1318}