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("we provided a string without NUL bytes, so CString::new should not fail");
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::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: &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::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: &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::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: &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::marker::StructuralPartialEq for FromBytesWithNulErrorKind { }
#[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::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: &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::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: &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("we provided a string without NUL bytes, so CString::new should not fail");
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)),
267// SAFETY: We ensured there's no null bytes.
268None => Ok(unsafe { CString::_from_vec_unchecked(bytes) }),
269 }
270 }
271 }
272273// Specialization for avoiding reallocation
274#[inline(always)] // Without that it is not inlined into specializations
275fn spec_new_impl_bytes(bytes: &[u8]) -> Result<CString, NulError> {
276// We cannot have such large slice that we would overflow here
277 // but using `checked_add` allows LLVM to assume that capacity never overflows
278 // and generate twice shorter code.
279 // `saturating_add` doesn't help for some reason.
280let capacity = bytes.len().checked_add(1).unwrap();
281282// Allocate before validation to avoid duplication of allocation code.
283 // We still need to allocate and copy memory even if we get an error.
284let mut buffer = Vec::with_capacity(capacity);
285buffer.extend(bytes);
286287// Check memory of self instead of new buffer.
288 // This allows better optimizations if lto enabled.
289match memchr::memchr(0, bytes) {
290Some(i) => Err(NulError(i, buffer)),
291// SAFETY: We ensured there's no null bytes.
292None => Ok(unsafe { CString::_from_vec_unchecked(buffer) }),
293 }
294 }
295296impl SpecNewImplfor &'_ [u8] {
297fn spec_new_impl(self) -> Result<CString, NulError> {
298spec_new_impl_bytes(self)
299 }
300 }
301302impl SpecNewImplfor &'_ str {
303fn spec_new_impl(self) -> Result<CString, NulError> {
304spec_new_impl_bytes(self.as_bytes())
305 }
306 }
307308impl SpecNewImplfor &'_ mut [u8] {
309fn spec_new_impl(self) -> Result<CString, NulError> {
310spec_new_impl_bytes(self)
311 }
312 }
313314t.spec_new_impl()
315 }
316317/// Creates a C-compatible string by consuming a byte vector,
318 /// without checking for interior 0 bytes.
319 ///
320 /// Trailing 0 byte will be appended by this function.
321 ///
322 /// This method is equivalent to [`CString::new`] except that no runtime
323 /// assertion is made that `v` contains no 0 bytes, and it requires an
324 /// actual byte vector, not anything that can be converted to one with Into.
325 ///
326 /// # Safety
327 ///
328 /// The caller must ensure `v` contains no nul bytes in its contents.
329 ///
330 /// # Examples
331 ///
332 /// ```
333 /// use std::ffi::CString;
334 ///
335 /// let raw = b"foo".to_vec();
336 /// unsafe {
337 /// let c_string = CString::from_vec_unchecked(raw);
338 /// }
339 /// ```
340#[must_use]
341 #[stable(feature = "rust1", since = "1.0.0")]
342pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> Self {
343if 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());
344// SAFETY: Upheld by caller.
345unsafe { Self::_from_vec_unchecked(v) }
346 }
347348unsafe fn _from_vec_unchecked(mut v: Vec<u8>) -> Self {
349v.reserve_exact(1);
350v.push(0);
351Self { inner: v.into_boxed_slice() }
352 }
353354/// Retakes ownership of a `CString` that was transferred to C via
355 /// [`CString::into_raw`].
356 ///
357 /// Additionally, the length of the string will be recalculated from the pointer.
358 ///
359 /// # Safety
360 ///
361 /// This should only ever be called with a pointer that was earlier
362 /// obtained by calling [`CString::into_raw`], and the memory it points to must not be accessed
363 /// through any other pointer during the lifetime of reconstructed `CString`.
364 /// Other usage (e.g., trying to take ownership of a string that was allocated by foreign code)
365 /// is likely to lead to undefined behavior or allocator corruption.
366 ///
367 /// This function does not validate ownership of the raw pointer's memory.
368 /// A double-free may occur if the function is called twice on the same raw pointer.
369 /// Additionally, the caller must ensure the pointer is not dangling.
370 ///
371 /// It should be noted that the length isn't just "recomputed," but that
372 /// the recomputed length must match the original length from the
373 /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
374 /// methods should not be used when passing the string to C functions that can
375 /// modify the string's length.
376 ///
377 /// > **Note:** If you need to borrow a string that was allocated by
378 /// > foreign code, use [`CStr`]. If you need to take ownership of
379 /// > a string that was allocated by foreign code, you will need to
380 /// > make your own provisions for freeing it appropriately, likely
381 /// > with the foreign code's API to do that.
382 ///
383 /// # Examples
384 ///
385 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
386 /// ownership with `from_raw`:
387 ///
388 /// ```ignore (extern-declaration)
389 /// use std::ffi::CString;
390 /// use std::os::raw::c_char;
391 ///
392 /// extern "C" {
393 /// fn some_extern_function(s: *mut c_char);
394 /// }
395 ///
396 /// let c_string = CString::from(c"Hello!");
397 /// let raw = c_string.into_raw();
398 /// unsafe {
399 /// some_extern_function(raw);
400 /// let c_string = CString::from_raw(raw);
401 /// }
402 /// ```
403#[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
404 #[stable(feature = "cstr_memory", since = "1.4.0")]
405pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
406// SAFETY: This is called with a pointer that was obtained from a call
407 // to `CString::into_raw` and the length has not been modified. As such,
408 // we know there is a NUL byte (and only one) at the end and that the
409 // information about the size of the allocation is correct on Rust's
410 // side.
411unsafe {
412unsafe extern "C" {
413/// Provided by libc or compiler_builtins.
414fn strlen(s: *const c_char) -> usize;
415 }
416let len = strlen(ptr) + 1; // Including the NUL byte
417let slice = slice::from_raw_parts_mut(ptr, len);
418CString { inner: Box::from_raw(sliceas *mut [c_char] as *mut [u8]) }
419 }
420 }
421422/// Consumes the `CString` and transfers ownership of the string to a C caller.
423 ///
424 /// The pointer which this function returns must be returned to Rust and reconstituted using
425 /// [`CString::from_raw`] to be properly deallocated. Specifically, one
426 /// should *not* use the standard C `free()` function to deallocate
427 /// this string.
428 ///
429 /// Failure to call [`CString::from_raw`] will lead to a memory leak.
430 ///
431 /// The C side must **not** modify the length of the string (by writing a
432 /// nul byte somewhere inside the string or removing the final one) before
433 /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
434 /// in [`CString::from_raw`].
435 ///
436 /// # Examples
437 ///
438 /// ```
439 /// use std::ffi::CString;
440 ///
441 /// let c_string = CString::from(c"foo");
442 ///
443 /// let ptr = c_string.into_raw();
444 ///
445 /// unsafe {
446 /// assert_eq!(b'f', *ptr as u8);
447 /// assert_eq!(b'o', *ptr.add(1) as u8);
448 /// assert_eq!(b'o', *ptr.add(2) as u8);
449 /// assert_eq!(b'\0', *ptr.add(3) as u8);
450 ///
451 /// // retake pointer to free memory
452 /// let _ = CString::from_raw(ptr);
453 /// }
454 /// ```
455#[inline]
456 #[must_use = "`self` will be dropped if the result is not used"]
457 #[stable(feature = "cstr_memory", since = "1.4.0")]
458pub fn into_raw(self) -> *mut c_char {
459Box::into_raw(self.into_inner()) as *mut c_char460 }
461462/// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
463 ///
464 /// On failure, ownership of the original `CString` is returned.
465 ///
466 /// # Examples
467 ///
468 /// ```
469 /// use std::ffi::CString;
470 ///
471 /// let valid_utf8 = vec![b'f', b'o', b'o'];
472 /// let cstring = CString::new(valid_utf8).expect("we provided bytes that do not have a NUL byte, so CString::new should not fail");
473 /// assert_eq!(cstring.into_string().expect("we provided bytes that are valid UTF-8, so `into_string` should not fail"), "foo");
474 ///
475 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
476 /// let cstring = CString::new(invalid_utf8).expect("we provided bytes that do not have a NUL byte, so CString::new should not fail");
477 /// let err = cstring.into_string().expect_err("we provided bytes that are invalid UTF-8, so `into_string` should fail");
478 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
479 /// ```
480#[stable(feature = "cstring_into", since = "1.7.0")]
481pub fn into_string(self) -> Result<String, IntoStringError> {
482String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
483 error: e.utf8_error(),
484// SAFETY: `CString`s never contain null bytes.
485inner: unsafe { Self::_from_vec_unchecked(e.into_bytes()) },
486 })
487 }
488489/// Consumes the `CString` and returns the underlying byte buffer.
490 ///
491 /// The returned buffer does **not** contain the trailing nul
492 /// terminator, and it is guaranteed to not have any interior nul
493 /// bytes.
494 ///
495 /// # Examples
496 ///
497 /// ```
498 /// use std::ffi::CString;
499 ///
500 /// let c_string = CString::from(c"foo");
501 /// let bytes = c_string.into_bytes();
502 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
503 /// ```
504#[must_use = "`self` will be dropped if the result is not used"]
505 #[stable(feature = "cstring_into", since = "1.7.0")]
506pub fn into_bytes(self) -> Vec<u8> {
507let mut vec = self.into_inner().into_vec();
508let _nul = vec.pop();
509if 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));
510vec511 }
512513/// Equivalent to [`CString::into_bytes()`] except that the
514 /// returned vector includes the trailing nul terminator.
515 ///
516 /// # Examples
517 ///
518 /// ```
519 /// use std::ffi::CString;
520 ///
521 /// let c_string = CString::from(c"foo");
522 /// let bytes = c_string.into_bytes_with_nul();
523 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
524 /// ```
525#[must_use = "`self` will be dropped if the result is not used"]
526 #[stable(feature = "cstring_into", since = "1.7.0")]
527pub fn into_bytes_with_nul(self) -> Vec<u8> {
528self.into_inner().into_vec()
529 }
530531/// Returns the contents of this `CString` as a slice of bytes.
532 ///
533 /// The returned slice does **not** contain the trailing nul
534 /// terminator, and it is guaranteed to not have any interior nul
535 /// bytes. If you need the nul terminator, use
536 /// [`CString::as_bytes_with_nul`] instead.
537 ///
538 /// # Examples
539 ///
540 /// ```
541 /// use std::ffi::CString;
542 ///
543 /// let c_string = CString::from(c"foo");
544 /// let bytes = c_string.as_bytes();
545 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
546 /// ```
547#[inline]
548 #[must_use]
549 #[stable(feature = "rust1", since = "1.0.0")]
550pub fn as_bytes(&self) -> &[u8] {
551// SAFETY: CString has a length at least 1
552unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
553 }
554555/// Equivalent to [`CString::as_bytes()`] except that the
556 /// returned slice includes the trailing nul terminator.
557 ///
558 /// # Examples
559 ///
560 /// ```
561 /// use std::ffi::CString;
562 ///
563 /// let c_string = CString::from(c"foo");
564 /// let bytes = c_string.as_bytes_with_nul();
565 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
566 /// ```
567#[inline]
568 #[must_use]
569 #[stable(feature = "rust1", since = "1.0.0")]
570pub fn as_bytes_with_nul(&self) -> &[u8] {
571&self.inner
572 }
573574/// Extracts a [`CStr`] slice containing the entire string.
575 ///
576 /// # Examples
577 ///
578 /// ```
579 /// use std::ffi::{CString, CStr};
580 ///
581 /// let c_string = CString::from(c"foo");
582 /// let cstr = c_string.as_c_str();
583 /// assert_eq!(cstr,
584 /// 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"));
585 /// ```
586#[inline]
587 #[must_use]
588 #[stable(feature = "as_c_str", since = "1.20.0")]
589 #[rustc_diagnostic_item = "cstring_as_c_str"]
590pub fn as_c_str(&self) -> &CStr {
591// SAFETY: Ensured by `as_bytes_with_nul`.
592unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
593 }
594595/// Converts this `CString` into a boxed [`CStr`].
596 ///
597 /// # Examples
598 ///
599 /// ```
600 /// let c_string = c"foo".to_owned();
601 /// let boxed = c_string.into_boxed_c_str();
602 /// assert_eq!(boxed.to_bytes_with_nul(), b"foo\0");
603 /// ```
604#[must_use = "`self` will be dropped if the result is not used"]
605 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
606pub fn into_boxed_c_str(self) -> Box<CStr> {
607// SAFETY: Typecast of [u8] to CStr is valid and we know contents have
608 // no nulls except for the terminating byte.
609unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
610 }
611612/// Bypass "move out of struct which implements [`Drop`] trait" restriction.
613#[inline]
614fn into_inner(self) -> Box<[u8]> {
615let this = mem::ManuallyDrop::new(self);
616// SAFETY: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
617 // so we use `ManuallyDrop` to ensure `self` is not dropped.
618 // Then we can return the box directly without invalidating it.
619 // See https://github.com/rust-lang/rust/issues/62553.
620unsafe { ptr::read(&this.inner) }
621 }
622623/// Converts a <code>[Vec]<[u8]></code> to a [`CString`] without checking the
624 /// invariants on the given [`Vec`].
625 ///
626 /// # Safety
627 ///
628 /// The given [`Vec`] **must** have one nul byte as its last element.
629 /// This means it cannot be empty nor have any other nul byte anywhere else.
630 ///
631 /// # Example
632 ///
633 /// ```
634 /// use std::ffi::CString;
635 /// assert_eq!(
636 /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
637 /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
638 /// );
639 /// ```
640#[must_use]
641 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
642pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
643if 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());
644// SAFETY: Upheld by caller.
645unsafe { Self::_from_vec_with_nul_unchecked(v) }
646 }
647648unsafe fn _from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
649Self { inner: v.into_boxed_slice() }
650 }
651652/// Attempts to convert a <code>[Vec]<[u8]></code> to a [`CString`].
653 ///
654 /// Runtime checks are present to ensure there is only one nul byte in the
655 /// [`Vec`], its last element.
656 ///
657 /// # Errors
658 ///
659 /// If a nul byte is present and not the last element or no nul bytes
660 /// is present, an error will be returned.
661 ///
662 /// # Examples
663 ///
664 /// A successful conversion will produce the same result as [`CString::new`]
665 /// when called without the ending nul byte.
666 ///
667 /// ```
668 /// use std::ffi::CString;
669 /// assert_eq!(
670 /// CString::from_vec_with_nul(b"abc\0".to_vec())
671 /// .expect("we provided bytes that has one NUL byte exactly at the end, so CString::from_vec_with_nul should not fail"),
672 /// c"abc".to_owned()
673 /// );
674 /// ```
675 ///
676 /// An incorrectly formatted [`Vec`] will produce an error.
677 ///
678 /// ```
679 /// use std::ffi::{CString, FromVecWithNulError};
680 /// // Interior nul byte
681 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
682 /// // No nul byte
683 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
684 /// ```
685#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
686pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
687let nul_pos = memchr::memchr(0, &v);
688match nul_pos {
689Some(nul_pos) if nul_pos + 1 == v.len() => {
690// SAFETY: We know there is only one nul byte, at the end
691 // of the vec.
692Ok(unsafe { Self::_from_vec_with_nul_unchecked(v) })
693 }
694Some(nul_pos) => Err(FromVecWithNulError {
695 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
696 bytes: v,
697 }),
698None => Err(FromVecWithNulError {
699 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
700 bytes: v,
701 }),
702 }
703 }
704}
705706// Turns this `CString` into an empty string to prevent
707// memory-unsafe code from working by accident. Inline
708// to prevent LLVM from optimizing it away in debug builds.
709#[stable(feature = "cstring_drop", since = "1.13.0")]
710impl Dropfor CString {
711#[inline]
712fn drop(&mut self) {
713// SAFETY: Length is always at least one.
714unsafe {
715*self.inner.get_unchecked_mut(0) = 0;
716 }
717 }
718}
719720#[stable(feature = "rust1", since = "1.0.0")]
721impl ops::Dereffor CString {
722type Target = CStr;
723724#[inline]
725fn deref(&self) -> &CStr {
726self.as_c_str()
727 }
728}
729730/// Delegates to the [`CStr`] implementation of [`fmt::Debug`],
731/// showing invalid UTF-8 as hex escapes.
732#[stable(feature = "rust1", since = "1.0.0")]
733impl fmt::Debugfor CString {
734fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735 fmt::Debug::fmt(self.as_c_str(), f)
736 }
737}
738739#[stable(feature = "cstring_into", since = "1.7.0")]
740impl From<CString> for Vec<u8> {
741/// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
742 ///
743 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
744#[inline]
745fn from(s: CString) -> Vec<u8> {
746s.into_bytes()
747 }
748}
749750#[stable(feature = "cstr_default", since = "1.10.0")]
751impl Defaultfor CString {
752/// Creates an empty `CString`.
753fn default() -> CString {
754let a: &CStr = Default::default();
755a.to_owned()
756 }
757}
758759#[stable(feature = "cstr_borrow", since = "1.3.0")]
760impl Borrow<CStr> for CString {
761#[inline]
762fn borrow(&self) -> &CStr {
763self764 }
765}
766767#[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
768impl<'a> From<Cow<'a, CStr>> for CString {
769/// Converts a `Cow<'a, CStr>` into a `CString`, by copying the contents if they are
770 /// borrowed.
771#[inline]
772fn from(s: Cow<'a, CStr>) -> Self {
773s.into_owned()
774 }
775}
776777#[stable(feature = "box_from_c_str", since = "1.17.0")]
778impl From<&CStr> for Box<CStr> {
779/// Converts a `&CStr` into a `Box<CStr>`,
780 /// by copying the contents into a newly allocated [`Box`].
781fn from(s: &CStr) -> Box<CStr> {
782Box::clone_from_ref(s)
783 }
784}
785786#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
787impl From<&mut CStr> for Box<CStr> {
788/// Converts a `&mut CStr` into a `Box<CStr>`,
789 /// by copying the contents into a newly allocated [`Box`].
790fn from(s: &mut CStr) -> Box<CStr> {
791Self::from(&*s)
792 }
793}
794795#[stable(feature = "box_from_cow", since = "1.45.0")]
796impl From<Cow<'_, CStr>> for Box<CStr> {
797/// Converts a `Cow<'a, CStr>` into a `Box<CStr>`,
798 /// by copying the contents if they are borrowed.
799#[inline]
800fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
801match cow {
802 Cow::Borrowed(s) => Box::from(s),
803 Cow::Owned(s) => Box::from(s),
804 }
805 }
806}
807808#[stable(feature = "c_string_from_box", since = "1.18.0")]
809impl From<Box<CStr>> for CString {
810/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
811#[inline]
812fn from(s: Box<CStr>) -> CString {
813let raw = Box::into_raw(s) as *mut [u8];
814// SAFETY: Converting a *mut CStr -> *mut [u8] -> CString is valid.
815CString { inner: unsafe { Box::from_raw(raw) } }
816 }
817}
818819#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
820impl From<Vec<NonZero<u8>>> for CString {
821/// Converts a <code>[Vec]<[NonZero]<[u8]>></code> into a [`CString`] without
822 /// copying nor checking for inner nul bytes.
823#[inline]
824fn from(v: Vec<NonZero<u8>>) -> CString {
825// Transmute `Vec<NonZero<u8>>` to `Vec<u8>`.
826let v: Vec<u8> = {
827let (ptr, len, cap): (*mut NonZero<u8>, _, _) = Vec::into_raw_parts(v);
828// SAFETY:
829 // - transmuting between `NonZero<u8>` and `u8` is sound;
830 // - `alloc::Layout<NonZero<u8>> == alloc::Layout<u8>`.
831unsafe { Vec::from_raw_parts(ptr.cast::<u8>(), len, cap) }
832 };
833// SAFETY: `v` cannot contain nul bytes, given the type-level
834 // invariant of `NonZero<u8>`.
835unsafe { Self::_from_vec_unchecked(v) }
836 }
837}
838839#[stable(feature = "c_string_from_str", since = "1.85.0")]
840impl FromStrfor CString {
841type Err = NulError;
842843/// Converts a string `s` into a [`CString`].
844 ///
845 /// This method is equivalent to [`CString::new`].
846#[inline]
847fn from_str(s: &str) -> Result<Self, Self::Err> {
848Self::new(s)
849 }
850}
851852#[stable(feature = "c_string_from_str", since = "1.85.0")]
853impl TryFrom<CString> for String {
854type Error = IntoStringError;
855856/// Converts a [`CString`] into a [`String`] if it contains valid UTF-8 data.
857 ///
858 /// This method is equivalent to [`CString::into_string`].
859#[inline]
860fn try_from(value: CString) -> Result<Self, Self::Error> {
861value.into_string()
862 }
863}
864865#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
866impl Clonefor Box<CStr> {
867#[inline]
868fn clone(&self) -> Self {
869 (**self).into()
870 }
871}
872873#[stable(feature = "box_from_c_string", since = "1.20.0")]
874impl From<CString> for Box<CStr> {
875/// Converts a [`CString`] into a <code>[Box]<[CStr]></code> without copying or allocating.
876#[inline]
877fn from(s: CString) -> Box<CStr> {
878s.into_boxed_c_str()
879 }
880}
881882#[stable(feature = "cow_from_cstr", since = "1.28.0")]
883impl<'a> From<CString> for Cow<'a, CStr> {
884/// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
885#[inline]
886fn from(s: CString) -> Cow<'a, CStr> {
887 Cow::Owned(s)
888 }
889}
890891#[stable(feature = "cow_from_cstr", since = "1.28.0")]
892impl<'a> From<&'a CStr> for Cow<'a, CStr> {
893/// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
894#[inline]
895fn from(s: &'a CStr) -> Cow<'a, CStr> {
896 Cow::Borrowed(s)
897 }
898}
899900#[stable(feature = "cow_from_cstr", since = "1.28.0")]
901impl<'a> From<&'a CString> for Cow<'a, CStr> {
902/// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
903#[inline]
904fn from(s: &'a CString) -> Cow<'a, CStr> {
905 Cow::Borrowed(s.as_c_str())
906 }
907}
908909#[cfg(target_has_atomic = "ptr")]
910#[stable(feature = "shared_from_slice2", since = "1.24.0")]
911impl From<CString> for Arc<CStr> {
912/// Converts a [`CString`] into an <code>[Arc]<[CStr]></code> by moving the [`CString`]
913 /// data into a new [`Arc`] buffer.
914#[inline]
915fn from(s: CString) -> Arc<CStr> {
916let arc: Arc<[u8]> = Arc::from(s.into_inner());
917// SAFETY: Type conversion is valid.
918unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
919 }
920}
921922#[cfg(target_has_atomic = "ptr")]
923#[stable(feature = "shared_from_slice2", since = "1.24.0")]
924impl From<&CStr> for Arc<CStr> {
925/// Converts a `&CStr` into a `Arc<CStr>`,
926 /// by copying the contents into a newly allocated [`Arc`].
927#[inline]
928fn from(s: &CStr) -> Arc<CStr> {
929let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
930// SAFETY: Type conversion is valid.
931unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
932 }
933}
934935#[cfg(target_has_atomic = "ptr")]
936#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
937impl From<&mut CStr> for Arc<CStr> {
938/// Converts a `&mut CStr` into a `Arc<CStr>`,
939 /// by copying the contents into a newly allocated [`Arc`].
940#[inline]
941fn from(s: &mut CStr) -> Arc<CStr> {
942Arc::from(&*s)
943 }
944}
945946#[stable(feature = "shared_from_slice2", since = "1.24.0")]
947impl From<CString> for Rc<CStr> {
948/// Converts a [`CString`] into an <code>[Rc]<[CStr]></code> by moving the [`CString`]
949 /// data into a new [`Rc`] buffer.
950#[inline]
951fn from(s: CString) -> Rc<CStr> {
952let rc: Rc<[u8]> = Rc::from(s.into_inner());
953// SAFETY: Type conversion is valid.
954unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
955 }
956}
957958#[stable(feature = "shared_from_slice2", since = "1.24.0")]
959impl From<&CStr> for Rc<CStr> {
960/// Converts a `&CStr` into a `Rc<CStr>`,
961 /// by copying the contents into a newly allocated [`Rc`].
962#[inline]
963fn from(s: &CStr) -> Rc<CStr> {
964let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
965// SAFETY: Type conversion is valid.
966unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
967 }
968}
969970#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
971impl From<&mut CStr> for Rc<CStr> {
972/// Converts a `&mut CStr` into a `Rc<CStr>`,
973 /// by copying the contents into a newly allocated [`Rc`].
974#[inline]
975fn from(s: &mut CStr) -> Rc<CStr> {
976Rc::from(&*s)
977 }
978}
979980#[cfg(not(no_global_oom_handling))]
981#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
982impl Defaultfor Rc<CStr> {
983/// Creates an empty CStr inside an Rc
984 ///
985 /// This may or may not share an allocation with other Rcs on the same thread.
986#[inline]
987fn default() -> Self {
988Rc::from(c"")
989 }
990}
991992#[stable(feature = "default_box_extra", since = "1.17.0")]
993impl Defaultfor Box<CStr> {
994fn default() -> Box<CStr> {
995Box::from(c"")
996 }
997}
998999impl NulError {
1000/// Returns the position of the nul byte in the slice that caused
1001 /// [`CString::new`] to fail.
1002 ///
1003 /// # Examples
1004 ///
1005 /// ```
1006 /// use std::ffi::CString;
1007 ///
1008 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1009 /// assert_eq!(nul_error.nul_position(), 3);
1010 ///
1011 /// let nul_error = CString::new("foo bar\0").unwrap_err();
1012 /// assert_eq!(nul_error.nul_position(), 7);
1013 /// ```
1014#[must_use]
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016pub fn nul_position(&self) -> usize {
1017self.0
1018}
10191020/// Consumes this error, returning the underlying vector of bytes which
1021 /// generated the error in the first place.
1022 ///
1023 /// # Examples
1024 ///
1025 /// ```
1026 /// use std::ffi::CString;
1027 ///
1028 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1029 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1030 /// ```
1031#[must_use = "`self` will be dropped if the result is not used"]
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033pub fn into_vec(self) -> Vec<u8> {
1034self.1
1035}
1036}
10371038#[stable(feature = "rust1", since = "1.0.0")]
1039impl fmt::Displayfor NulError {
1040fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041f.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)1042 }
1043}
10441045#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1046impl fmt::Displayfor FromVecWithNulError {
1047fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048match self.error_kind {
1049 FromBytesWithNulErrorKind::InteriorNul(pos) => {
1050f.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}")1051 }
1052 FromBytesWithNulErrorKind::NotNulTerminated => {
1053f.write_fmt(format_args!("data provided is not nul terminated"))write!(f, "data provided is not nul terminated")1054 }
1055 }
1056 }
1057}
10581059impl IntoStringError {
1060/// Consumes this error, returning original [`CString`] which generated the
1061 /// error.
1062#[must_use = "`self` will be dropped if the result is not used"]
1063 #[stable(feature = "cstring_into", since = "1.7.0")]
1064pub fn into_cstring(self) -> CString {
1065self.inner
1066 }
10671068/// Access the underlying UTF-8 error that was the cause of this error.
1069#[must_use]
1070 #[stable(feature = "cstring_into", since = "1.7.0")]
1071pub fn utf8_error(&self) -> Utf8Error {
1072self.error
1073 }
1074}
10751076#[stable(feature = "cstring_into", since = "1.7.0")]
1077impl fmt::Displayfor IntoStringError {
1078fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1079"C string contained non-utf8 bytes".fmt(f)
1080 }
1081}
10821083#[stable(feature = "cstr_borrow", since = "1.3.0")]
1084impl ToOwnedfor CStr {
1085type Owned = CString;
10861087fn to_owned(&self) -> CString {
1088CString { inner: self.to_bytes_with_nul().into() }
1089 }
10901091fn clone_into(&self, target: &mut CString) {
1092let src = self.to_bytes_with_nul();
1093// If the lengths match, we can reuse the existing allocation without any overhead.
1094if target.inner.len() == src.len() {
1095target.inner.copy_from_slice(src);
1096 } else {
1097// Reuse the existing allocation's capacity by converting to a Vec.
1098 // We temporarily replace `target` with a valid dummy to remain panic-safe.
1099let mut b = mem::replace(&mut target.inner, Box::new([0])).into_vec();
1100self.to_bytes_with_nul().clone_into(&mut b);
1101target.inner = b.into_boxed_slice();
1102 }
1103 }
1104}
11051106#[stable(feature = "cstring_asref", since = "1.7.0")]
1107impl From<&CStr> for CString {
1108/// Converts a <code>&[CStr]</code> into a [`CString`]
1109 /// by copying the contents into a new allocation.
1110fn from(s: &CStr) -> CString {
1111s.to_owned()
1112 }
1113}
11141115#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1116impl PartialEq<CStr> for CString {
1117#[inline]
1118fn eq(&self, other: &CStr) -> bool {
1119**self == *other1120 }
11211122#[inline]
1123fn ne(&self, other: &CStr) -> bool {
1124**self != *other1125 }
1126}
11271128#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1129impl PartialEq<&CStr> for CString {
1130#[inline]
1131fn eq(&self, other: &&CStr) -> bool {
1132**self == **other1133 }
11341135#[inline]
1136fn ne(&self, other: &&CStr) -> bool {
1137**self != **other1138 }
1139}
11401141#[cfg(not(no_global_oom_handling))]
1142#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1143impl PartialEq<Cow<'_, CStr>> for CString {
1144#[inline]
1145fn eq(&self, other: &Cow<'_, CStr>) -> bool {
1146**self == **other1147 }
11481149#[inline]
1150fn ne(&self, other: &Cow<'_, CStr>) -> bool {
1151**self != **other1152 }
1153}
11541155#[stable(feature = "cstring_asref", since = "1.7.0")]
1156impl ops::Index<ops::RangeFull> for CString {
1157type Output = CStr;
11581159#[inline]
1160fn index(&self, _index: ops::RangeFull) -> &CStr {
1161self1162 }
1163}
11641165#[stable(feature = "cstring_asref", since = "1.7.0")]
1166impl AsRef<CStr> for CString {
1167#[inline]
1168fn as_ref(&self) -> &CStr {
1169self1170 }
1171}
11721173impl CStr {
1174/// Converts a `CStr` into a <code>[Cow]<[str]></code>.
1175 ///
1176 /// If the contents of the `CStr` are valid UTF-8 data, this
1177 /// function will return a <code>[Cow]::[Borrowed]\(&[str])</code>
1178 /// with the corresponding <code>&[str]</code> slice. Otherwise, it will
1179 /// replace any invalid UTF-8 sequences with
1180 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1181 /// <code>[Cow]::[Owned]\([String])</code> with the result.
1182 ///
1183 /// [str]: prim@str "str"
1184 /// [Borrowed]: Cow::Borrowed
1185 /// [Owned]: Cow::Owned
1186 /// [U+FFFD]: char::REPLACEMENT_CHARACTER
1187 ///
1188 /// # Examples
1189 ///
1190 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8. The leading
1191 /// `c` on the string literal denotes a `CStr`.
1192 ///
1193 /// ```
1194 /// use std::borrow::Cow;
1195 ///
1196 /// assert_eq!(c"Hello World".to_string_lossy(), Cow::Borrowed("Hello World"));
1197 /// ```
1198 ///
1199 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1200 ///
1201 /// ```
1202 /// use std::borrow::Cow;
1203 ///
1204 /// assert_eq!(
1205 /// c"Hello \xF0\x90\x80World".to_string_lossy(),
1206 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
1207 /// );
1208 /// ```
1209#[rustc_allow_incoherent_impl]
1210 #[must_use = "this returns the result of the operation, \
1211 without modifying the original"]
1212 #[stable(feature = "cstr_to_str", since = "1.4.0")]
1213pub fn to_string_lossy(&self) -> Cow<'_, str> {
1214String::from_utf8_lossy(self.to_bytes())
1215 }
12161217/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
1218 ///
1219 /// # Examples
1220 ///
1221 /// ```
1222 /// use std::ffi::{CStr, CString};
1223 ///
1224 /// let boxed: Box<CStr> = Box::from(c"foo");
1225 /// let c_string: CString = c"foo".to_owned();
1226 ///
1227 /// assert_eq!(boxed.into_c_string(), c_string);
1228 /// ```
1229#[rustc_allow_incoherent_impl]
1230 #[must_use = "`self` will be dropped if the result is not used"]
1231 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
1232pub fn into_c_string(self: Box<Self>) -> CString {
1233CString::from(self)
1234 }
1235}
12361237#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1238impl PartialEq<CString> for CStr {
1239#[inline]
1240fn eq(&self, other: &CString) -> bool {
1241*self == **other1242 }
12431244#[inline]
1245fn ne(&self, other: &CString) -> bool {
1246*self != **other1247 }
1248}
12491250#[cfg(not(no_global_oom_handling))]
1251#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1252impl PartialEq<Cow<'_, Self>> for CStr {
1253#[inline]
1254fn eq(&self, other: &Cow<'_, Self>) -> bool {
1255*self == **other1256 }
12571258#[inline]
1259fn ne(&self, other: &Cow<'_, Self>) -> bool {
1260*self != **other1261 }
1262}
12631264#[cfg(not(no_global_oom_handling))]
1265#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1266impl PartialEq<CStr> for Cow<'_, CStr> {
1267#[inline]
1268fn eq(&self, other: &CStr) -> bool {
1269**self == *other1270 }
12711272#[inline]
1273fn ne(&self, other: &CStr) -> bool {
1274**self != *other1275 }
1276}
12771278#[cfg(not(no_global_oom_handling))]
1279#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1280impl PartialEq<&CStr> for Cow<'_, CStr> {
1281#[inline]
1282fn eq(&self, other: &&CStr) -> bool {
1283**self == **other1284 }
12851286#[inline]
1287fn ne(&self, other: &&CStr) -> bool {
1288**self != **other1289 }
1290}
12911292#[cfg(not(no_global_oom_handling))]
1293#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
1294impl PartialEq<CString> for Cow<'_, CStr> {
1295#[inline]
1296fn eq(&self, other: &CString) -> bool {
1297**self == **other1298 }
12991300#[inline]
1301fn ne(&self, other: &CString) -> bool {
1302**self != **other1303 }
1304}
13051306#[stable(feature = "rust1", since = "1.0.0")]
1307impl core::error::Errorfor NulError {}
13081309#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
1310impl core::error::Errorfor FromVecWithNulError {}
13111312#[stable(feature = "cstring_into", since = "1.7.0")]
1313impl core::error::Errorfor IntoStringError {
1314fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
1315Some(&self.error)
1316 }
1317}