]> git.proxmox.com Git - rustc.git/blame - library/std/src/ffi/c_str.rs
New upstream version 1.54.0+dfsg1
[rustc.git] / library / std / src / ffi / c_str.rs
CommitLineData
3dfed10e 1#![deny(unsafe_op_in_unsafe_fn)]
1b1a35ee
XL
2
3#[cfg(test)]
4mod tests;
5
532ac7d7 6use crate::ascii;
dfeec247 7use crate::borrow::{Borrow, Cow};
532ac7d7
XL
8use crate::cmp::Ordering;
9use crate::error::Error;
10use crate::fmt::{self, Write};
11use crate::io;
12use crate::mem;
74b04a01 13use crate::num::NonZeroU8;
532ac7d7
XL
14use crate::ops;
15use crate::os::raw::c_char;
16use crate::ptr;
17use crate::rc::Rc;
18use crate::slice;
19use crate::str::{self, Utf8Error};
20use crate::sync::Arc;
21use crate::sys;
17df50a5 22use crate::sys_common::memchr;
1a4d82fc 23
abe05a73
XL
24/// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
25/// middle.
1a4d82fc 26///
abe05a73 27/// This type serves the purpose of being able to safely generate a
1a4d82fc
JJ
28/// C-compatible string from a Rust byte slice or vector. An instance of this
29/// type is a static guarantee that the underlying bytes contain no interior 0
abe05a73 30/// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
1a4d82fc 31///
b7449926 32/// `CString` is to [`&CStr`] as [`String`] is to [`&str`]: the former
abe05a73
XL
33/// in each pair are owned strings; the latter are borrowed
34/// references.
7cac9316 35///
abe05a73
XL
36/// # Creating a `CString`
37///
38/// A `CString` is created from either a byte slice or a byte vector,
39/// or anything that implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>` (for
40/// example, you can build a `CString` straight out of a [`String`] or
41/// a [`&str`], since both implement that trait).
42///
3dfed10e 43/// The [`CString::new`] method will actually check that the provided `&[u8]`
abe05a73
XL
44/// does not have 0 bytes in the middle, and return an error if it
45/// finds one.
46///
47/// # Extracting a raw pointer to the whole C string
48///
3dfed10e 49/// `CString` implements a [`as_ptr`][`CStr::as_ptr`] method through the [`Deref`]
abe05a73
XL
50/// trait. This method will give you a `*const c_char` which you can
51/// feed directly to extern functions that expect a nul-terminated
3dfed10e 52/// string, like C's `strdup()`. Notice that [`as_ptr`][`CStr::as_ptr`] returns a
48663c56
XL
53/// read-only pointer; if the C code writes to it, that causes
54/// undefined behavior.
abe05a73
XL
55///
56/// # Extracting a slice of the whole C string
57///
58/// Alternatively, you can obtain a `&[`[`u8`]`]` slice from a
3dfed10e 59/// `CString` with the [`CString::as_bytes`] method. Slices produced in this
abe05a73
XL
60/// way do *not* contain the trailing nul terminator. This is useful
61/// when you will be calling an extern function that takes a `*const
62/// u8` argument which is not necessarily nul-terminated, plus another
63/// argument with the length of the string — like C's `strndup()`.
64/// You can of course get the slice's length with its
6a06907d 65/// [`len`][slice::len] method.
abe05a73
XL
66///
67/// If you need a `&[`[`u8`]`]` slice *with* the nul terminator, you
3dfed10e 68/// can use [`CString::as_bytes_with_nul`] instead.
abe05a73
XL
69///
70/// Once you have the kind of slice you need (with or without a nul
71/// terminator), you can call the slice's own
6a06907d 72/// [`as_ptr`][slice::as_ptr] method to get a read-only raw pointer to pass to
abe05a73
XL
73/// extern functions. See the documentation for that function for a
74/// discussion on ensuring the lifetime of the raw pointer.
75///
3dfed10e 76/// [`&str`]: prim@str
3dfed10e
XL
77/// [`Deref`]: ops::Deref
78/// [`&CStr`]: CStr
1a4d82fc 79///
c34b1796 80/// # Examples
1a4d82fc 81///
0531ce1d 82/// ```ignore (extern-declaration)
1a4d82fc
JJ
83/// # fn main() {
84/// use std::ffi::CString;
92a42be0 85/// use std::os::raw::c_char;
1a4d82fc 86///
5869c6ff 87/// extern "C" {
92a42be0 88/// fn my_printer(s: *const c_char);
1a4d82fc
JJ
89/// }
90///
abe05a73 91/// // We are certain that our string doesn't have 0 bytes in the middle,
b7449926
XL
92/// // so we can .expect()
93/// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
1a4d82fc
JJ
94/// unsafe {
95/// my_printer(c_to_print.as_ptr());
96/// }
97/// # }
98/// ```
7453a54e
SL
99///
100/// # Safety
101///
102/// `CString` is intended for working with traditional C-style strings
abe05a73 103/// (a sequence of non-nul bytes terminated by a single nul byte); the
7453a54e
SL
104/// primary use case for these kinds of strings is interoperating with C-like
105/// code. Often you will need to transfer ownership to/from that external
106/// code. It is strongly recommended that you thoroughly read through the
107/// documentation of `CString` before use, as improper ownership management
108/// of `CString` instances can lead to invalid memory accesses, memory leaks,
109/// and other memory errors.
c1a9b12d 110#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
29967ef6 111#[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
c34b1796 112#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 113pub struct CString {
9e0c209e
SL
114 // Invariant 1: the slice ends with a zero byte and has a length of at least one.
115 // Invariant 2: the slice contains only one zero byte.
116 // Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
62682a34 117 inner: Box<[u8]>,
85aaf69f
SL
118}
119
120/// Representation of a borrowed C string.
121///
abe05a73
XL
122/// This type represents a borrowed reference to a nul-terminated
123/// array of bytes. It can be constructed safely from a `&[`[`u8`]`]`
124/// slice, or unsafely from a raw `*const c_char`. It can then be
125/// converted to a Rust [`&str`] by performing UTF-8 validation, or
126/// into an owned [`CString`].
127///
b7449926 128/// `&CStr` is to [`CString`] as [`&str`] is to [`String`]: the former
abe05a73
XL
129/// in each pair are borrowed references; the latter are owned
130/// strings.
85aaf69f
SL
131///
132/// Note that this structure is **not** `repr(C)` and is not recommended to be
abe05a73 133/// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
3dfed10e
XL
134/// functions may leverage the unsafe [`CStr::from_ptr`] constructor to provide
135/// a safe interface to other consumers.
85aaf69f
SL
136///
137/// # Examples
138///
7cac9316 139/// Inspecting a foreign C string:
85aaf69f 140///
0531ce1d 141/// ```ignore (extern-declaration)
85aaf69f 142/// use std::ffi::CStr;
92a42be0 143/// use std::os::raw::c_char;
85aaf69f 144///
5869c6ff 145/// extern "C" { fn my_string() -> *const c_char; }
85aaf69f 146///
5bcae85e
SL
147/// unsafe {
148/// let slice = CStr::from_ptr(my_string());
abe05a73 149/// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
85aaf69f
SL
150/// }
151/// ```
152///
7cac9316 153/// Passing a Rust-originating C string:
85aaf69f 154///
0531ce1d 155/// ```ignore (extern-declaration)
85aaf69f 156/// use std::ffi::{CString, CStr};
92a42be0 157/// use std::os::raw::c_char;
85aaf69f
SL
158///
159/// fn work(data: &CStr) {
5869c6ff 160/// extern "C" { fn work_with(data: *const c_char); }
85aaf69f
SL
161///
162/// unsafe { work_with(data.as_ptr()) }
163/// }
164///
b7449926 165/// let s = CString::new("data data data data").expect("CString::new failed");
5bcae85e 166/// work(&s);
85aaf69f 167/// ```
62682a34 168///
7cac9316
XL
169/// Converting a foreign C string into a Rust [`String`]:
170///
0531ce1d 171/// ```ignore (extern-declaration)
62682a34 172/// use std::ffi::CStr;
92a42be0 173/// use std::os::raw::c_char;
62682a34 174///
5869c6ff 175/// extern "C" { fn my_string() -> *const c_char; }
62682a34
SL
176///
177/// fn my_string_safe() -> String {
178/// unsafe {
179/// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
180/// }
181/// }
182///
5bcae85e 183/// println!("string: {}", my_string_safe());
62682a34 184/// ```
abe05a73 185///
3dfed10e 186/// [`&str`]: prim@str
85aaf69f 187#[derive(Hash)]
17df50a5 188#[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
c34b1796 189#[stable(feature = "rust1", since = "1.0.0")]
416331ca
XL
190// FIXME:
191// `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
192// on `CStr` being layout-compatible with `[u8]`.
193// When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
194// Anyway, `CStr` representation and layout are considered implementation detail, are
195// not documented and must not be relied upon.
85aaf69f 196pub struct CStr {
c34b1796 197 // FIXME: this should not be represented with a DST slice but rather with
92a42be0 198 // just a raw `c_char` along with some form of marker to make
c34b1796
AL
199 // this an unsized type. Essentially `sizeof(&CStr)` should be the
200 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
dfeec247 201 inner: [c_char],
85aaf69f
SL
202}
203
abe05a73
XL
204/// An error indicating that an interior nul byte was found.
205///
206/// While Rust strings may contain nul bytes in the middle, C strings
207/// can't, as that byte would effectively truncate the string.
7cac9316 208///
abe05a73
XL
209/// This error is created by the [`new`][`CString::new`] method on
210/// [`CString`]. See its documentation for more.
211///
041b39d2
XL
212/// # Examples
213///
214/// ```
215/// use std::ffi::{CString, NulError};
216///
217/// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
218/// ```
9e0c209e 219#[derive(Clone, PartialEq, Eq, Debug)]
c34b1796 220#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
221pub struct NulError(usize, Vec<u8>);
222
abe05a73
XL
223/// An error indicating that a nul byte was not in the expected position.
224///
f035d41b
XL
225/// The slice used to create a [`CStr`] must have one and only one nul byte,
226/// positioned at the end.
7cac9316 227///
3dfed10e 228/// This error is created by the [`CStr::from_bytes_with_nul`] method.
f035d41b 229/// See its documentation for more.
abe05a73 230///
041b39d2
XL
231/// # Examples
232///
233/// ```
234/// use std::ffi::{CStr, FromBytesWithNulError};
235///
236/// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
237/// ```
9e0c209e 238#[derive(Clone, PartialEq, Eq, Debug)]
a7813a04 239#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
8bb4bdeb
XL
240pub struct FromBytesWithNulError {
241 kind: FromBytesWithNulErrorKind,
242}
243
f035d41b
XL
244/// An error indicating that a nul byte was not in the expected position.
245///
246/// The vector used to create a [`CString`] must have one and only one nul byte,
247/// positioned at the end.
248///
3dfed10e 249/// This error is created by the [`CString::from_vec_with_nul`] method.
f035d41b
XL
250/// See its documentation for more.
251///
f035d41b
XL
252/// # Examples
253///
254/// ```
255/// #![feature(cstring_from_vec_with_nul)]
256/// use std::ffi::{CString, FromVecWithNulError};
257///
258/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
259/// ```
260#[derive(Clone, PartialEq, Eq, Debug)]
261#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
262pub struct FromVecWithNulError {
263 error_kind: FromBytesWithNulErrorKind,
264 bytes: Vec<u8>,
265}
266
8bb4bdeb
XL
267#[derive(Clone, PartialEq, Eq, Debug)]
268enum FromBytesWithNulErrorKind {
269 InteriorNul(usize),
270 NotNulTerminated,
271}
272
273impl FromBytesWithNulError {
274 fn interior_nul(pos: usize) -> FromBytesWithNulError {
dfeec247 275 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
8bb4bdeb
XL
276 }
277 fn not_nul_terminated() -> FromBytesWithNulError {
dfeec247 278 FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
8bb4bdeb
XL
279 }
280}
a7813a04 281
f035d41b
XL
282#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
283impl FromVecWithNulError {
284 /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
285 ///
286 /// # Examples
287 ///
288 /// Basic usage:
289 ///
290 /// ```
291 /// #![feature(cstring_from_vec_with_nul)]
292 /// use std::ffi::CString;
293 ///
294 /// // Some invalid bytes in a vector
295 /// let bytes = b"f\0oo".to_vec();
296 ///
297 /// let value = CString::from_vec_with_nul(bytes.clone());
298 ///
299 /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
300 /// ```
f035d41b
XL
301 pub fn as_bytes(&self) -> &[u8] {
302 &self.bytes[..]
303 }
304
305 /// Returns the bytes that were attempted to convert to a [`CString`].
306 ///
307 /// This method is carefully constructed to avoid allocation. It will
308 /// consume the error, moving out the bytes, so that a copy of the bytes
309 /// does not need to be made.
310 ///
311 /// # Examples
312 ///
313 /// Basic usage:
314 ///
315 /// ```
316 /// #![feature(cstring_from_vec_with_nul)]
317 /// use std::ffi::CString;
318 ///
319 /// // Some invalid bytes in a vector
320 /// let bytes = b"f\0oo".to_vec();
321 ///
322 /// let value = CString::from_vec_with_nul(bytes.clone());
323 ///
324 /// assert_eq!(bytes, value.unwrap_err().into_bytes());
325 /// ```
f035d41b
XL
326 pub fn into_bytes(self) -> Vec<u8> {
327 self.bytes
328 }
329}
330
abe05a73
XL
331/// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
332///
3dfed10e
XL
333/// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
334/// [`CString::into_string`] performs UTF-8 validation on those bytes and may
335/// return this error.
abe05a73 336///
3dfed10e 337/// This `struct` is created by [`CString::into_string()`]. See
abe05a73 338/// its documentation for more.
9e0c209e 339#[derive(Clone, PartialEq, Eq, Debug)]
9cc50fc6 340#[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf
SL
341pub struct IntoStringError {
342 inner: CString,
343 error: Utf8Error,
344}
345
1a4d82fc 346impl CString {
9346a6ac 347 /// Creates a new C-compatible string from a container of bytes.
85aaf69f 348 ///
abe05a73
XL
349 /// This function will consume the provided data and use the
350 /// underlying bytes to construct a new string, ensuring that
351 /// there is a trailing 0 byte. This trailing 0 byte will be
352 /// appended by this function; the provided data should *not*
353 /// contain any 0 bytes in it.
85aaf69f
SL
354 ///
355 /// # Examples
356 ///
0531ce1d 357 /// ```ignore (extern-declaration)
85aaf69f 358 /// use std::ffi::CString;
92a42be0 359 /// use std::os::raw::c_char;
85aaf69f 360 ///
5869c6ff 361 /// extern "C" { fn puts(s: *const c_char); }
85aaf69f 362 ///
b7449926 363 /// let to_print = CString::new("Hello!").expect("CString::new failed");
5bcae85e
SL
364 /// unsafe {
365 /// puts(to_print.as_ptr());
85aaf69f
SL
366 /// }
367 /// ```
368 ///
369 /// # Errors
370 ///
abe05a73
XL
371 /// This function will return an error if the supplied bytes contain an
372 /// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
85aaf69f 373 /// the position of the nul byte.
c34b1796
AL
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
e74abb32
XL
376 trait SpecIntoVec {
377 fn into_vec(self) -> Vec<u8>;
378 }
379 impl<T: Into<Vec<u8>>> SpecIntoVec for T {
380 default fn into_vec(self) -> Vec<u8> {
381 self.into()
382 }
383 }
384 // Specialization for avoiding reallocation.
385 impl SpecIntoVec for &'_ [u8] {
386 fn into_vec(self) -> Vec<u8> {
387 let mut v = Vec::with_capacity(self.len() + 1);
388 v.extend(self);
389 v
390 }
391 }
392 impl SpecIntoVec for &'_ str {
393 fn into_vec(self) -> Vec<u8> {
394 let mut v = Vec::with_capacity(self.len() + 1);
395 v.extend(self.as_bytes());
396 v
397 }
398 }
399
400 Self::_new(SpecIntoVec::into_vec(t))
e9174d1e
SL
401 }
402
403 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
9cc50fc6 404 match memchr::memchr(0, &bytes) {
85aaf69f
SL
405 Some(i) => Err(NulError(i, bytes)),
406 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
407 }
408 }
409
abe05a73
XL
410 /// Creates a C-compatible string by consuming a byte vector,
411 /// without checking for interior 0 bytes.
1a4d82fc 412 ///
3dfed10e
XL
413 /// This method is equivalent to [`CString::new`] except that no runtime
414 /// assertion is made that `v` contains no 0 bytes, and it requires an
415 /// actual byte vector, not anything that can be converted to one with Into.
7cac9316 416 ///
9e0c209e
SL
417 /// # Examples
418 ///
419 /// ```
420 /// use std::ffi::CString;
421 ///
422 /// let raw = b"foo".to_vec();
423 /// unsafe {
424 /// let c_string = CString::from_vec_unchecked(raw);
425 /// }
426 /// ```
c34b1796 427 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 428 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
9e0c209e 429 v.reserve_exact(1);
1a4d82fc 430 v.push(0);
62682a34
SL
431 CString { inner: v.into_boxed_slice() }
432 }
433
3dfed10e
XL
434 /// Retakes ownership of a `CString` that was transferred to C via
435 /// [`CString::into_raw`].
e9174d1e 436 ///
9e0c209e
SL
437 /// Additionally, the length of the string will be recalculated from the pointer.
438 ///
439 /// # Safety
440 ///
7453a54e 441 /// This should only ever be called with a pointer that was earlier
3dfed10e 442 /// obtained by calling [`CString::into_raw`]. Other usage (e.g., trying to take
9e0c209e
SL
443 /// ownership of a string that was allocated by foreign code) is likely to lead
444 /// to undefined behavior or allocator corruption.
7cac9316 445 ///
f035d41b
XL
446 /// It should be noted that the length isn't just "recomputed," but that
447 /// the recomputed length must match the original length from the
3dfed10e
XL
448 /// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
449 /// methods should not be used when passing the string to C functions that can
f035d41b
XL
450 /// modify the string's length.
451 ///
abe05a73
XL
452 /// > **Note:** If you need to borrow a string that was allocated by
453 /// > foreign code, use [`CStr`]. If you need to take ownership of
454 /// > a string that was allocated by foreign code, you will need to
455 /// > make your own provisions for freeing it appropriately, likely
456 /// > with the foreign code's API to do that.
457 ///
041b39d2
XL
458 /// # Examples
459 ///
9fa01778 460 /// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
041b39d2
XL
461 /// ownership with `from_raw`:
462 ///
0531ce1d 463 /// ```ignore (extern-declaration)
041b39d2
XL
464 /// use std::ffi::CString;
465 /// use std::os::raw::c_char;
466 ///
5869c6ff 467 /// extern "C" {
041b39d2
XL
468 /// fn some_extern_function(s: *mut c_char);
469 /// }
470 ///
b7449926 471 /// let c_string = CString::new("Hello!").expect("CString::new failed");
041b39d2
XL
472 /// let raw = c_string.into_raw();
473 /// unsafe {
474 /// some_extern_function(raw);
475 /// let c_string = CString::from_raw(raw);
476 /// }
477 /// ```
e9174d1e 478 #[stable(feature = "cstr_memory", since = "1.4.0")]
92a42be0 479 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
3dfed10e
XL
480 // SAFETY: This is called with a pointer that was obtained from a call
481 // to `CString::into_raw` and the length has not been modified. As such,
482 // we know there is a NUL byte (and only one) at the end and that the
483 // information about the size of the allocation is correct on Rust's
484 // side.
485 unsafe {
486 let len = sys::strlen(ptr) + 1; // Including the NUL byte
487 let slice = slice::from_raw_parts_mut(ptr, len as usize);
488 CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
489 }
62682a34
SL
490 }
491
abe05a73 492 /// Consumes the `CString` and transfers ownership of the string to a C caller.
62682a34 493 ///
abe05a73 494 /// The pointer which this function returns must be returned to Rust and reconstituted using
3dfed10e 495 /// [`CString::from_raw`] to be properly deallocated. Specifically, one
abe05a73 496 /// should *not* use the standard C `free()` function to deallocate
62682a34
SL
497 /// this string.
498 ///
3dfed10e 499 /// Failure to call [`CString::from_raw`] will lead to a memory leak.
7cac9316 500 ///
f035d41b 501 /// The C side must **not** modify the length of the string (by writing a
17df50a5 502 /// `null` somewhere inside the string or removing the final one) before
3dfed10e
XL
503 /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
504 /// in [`CString::from_raw`].
041b39d2
XL
505 ///
506 /// # Examples
507 ///
508 /// ```
509 /// use std::ffi::CString;
510 ///
b7449926 511 /// let c_string = CString::new("foo").expect("CString::new failed");
041b39d2
XL
512 ///
513 /// let ptr = c_string.into_raw();
514 ///
515 /// unsafe {
516 /// assert_eq!(b'f', *ptr as u8);
517 /// assert_eq!(b'o', *ptr.offset(1) as u8);
518 /// assert_eq!(b'o', *ptr.offset(2) as u8);
519 /// assert_eq!(b'\0', *ptr.offset(3) as u8);
520 ///
521 /// // retake pointer to free memory
522 /// let _ = CString::from_raw(ptr);
523 /// }
524 /// ```
525 #[inline]
e9174d1e 526 #[stable(feature = "cstr_memory", since = "1.4.0")]
92a42be0 527 pub fn into_raw(self) -> *mut c_char {
9e0c209e 528 Box::into_raw(self.into_inner()) as *mut c_char
1a4d82fc
JJ
529 }
530
abe05a73 531 /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
b039eaaf
SL
532 ///
533 /// On failure, ownership of the original `CString` is returned.
7cac9316 534 ///
abe05a73
XL
535 /// # Examples
536 ///
537 /// ```
538 /// use std::ffi::CString;
539 ///
540 /// let valid_utf8 = vec![b'f', b'o', b'o'];
b7449926
XL
541 /// let cstring = CString::new(valid_utf8).expect("CString::new failed");
542 /// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
abe05a73
XL
543 ///
544 /// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
b7449926
XL
545 /// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
546 /// let err = cstring.into_string().err().expect("into_string().err() failed");
abe05a73
XL
547 /// assert_eq!(err.utf8_error().valid_up_to(), 1);
548 /// ```
549
9cc50fc6 550 #[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf 551 pub fn into_string(self) -> Result<String, IntoStringError> {
dfeec247
XL
552 String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
553 error: e.utf8_error(),
554 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
555 })
b039eaaf
SL
556 }
557
abe05a73 558 /// Consumes the `CString` and returns the underlying byte buffer.
b039eaaf 559 ///
abe05a73
XL
560 /// The returned buffer does **not** contain the trailing nul
561 /// terminator, and it is guaranteed to not have any interior nul
562 /// bytes.
041b39d2
XL
563 ///
564 /// # Examples
565 ///
566 /// ```
567 /// use std::ffi::CString;
568 ///
b7449926 569 /// let c_string = CString::new("foo").expect("CString::new failed");
041b39d2
XL
570 /// let bytes = c_string.into_bytes();
571 /// assert_eq!(bytes, vec![b'f', b'o', b'o']);
572 /// ```
9cc50fc6 573 #[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf 574 pub fn into_bytes(self) -> Vec<u8> {
9e0c209e 575 let mut vec = self.into_inner().into_vec();
b039eaaf
SL
576 let _nul = vec.pop();
577 debug_assert_eq!(_nul, Some(0u8));
578 vec
579 }
580
3dfed10e
XL
581 /// Equivalent to [`CString::into_bytes()`] except that the
582 /// returned vector includes the trailing nul terminator.
041b39d2
XL
583 ///
584 /// # Examples
585 ///
586 /// ```
587 /// use std::ffi::CString;
588 ///
b7449926 589 /// let c_string = CString::new("foo").expect("CString::new failed");
041b39d2
XL
590 /// let bytes = c_string.into_bytes_with_nul();
591 /// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
592 /// ```
9cc50fc6 593 #[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf 594 pub fn into_bytes_with_nul(self) -> Vec<u8> {
9e0c209e 595 self.into_inner().into_vec()
b039eaaf
SL
596 }
597
85aaf69f
SL
598 /// Returns the contents of this `CString` as a slice of bytes.
599 ///
abe05a73
XL
600 /// The returned slice does **not** contain the trailing nul
601 /// terminator, and it is guaranteed to not have any interior nul
602 /// bytes. If you need the nul terminator, use
3dfed10e 603 /// [`CString::as_bytes_with_nul`] instead.
041b39d2
XL
604 ///
605 /// # Examples
606 ///
607 /// ```
608 /// use std::ffi::CString;
609 ///
b7449926 610 /// let c_string = CString::new("foo").expect("CString::new failed");
041b39d2
XL
611 /// let bytes = c_string.as_bytes();
612 /// assert_eq!(bytes, &[b'f', b'o', b'o']);
613 /// ```
614 #[inline]
c34b1796 615 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 616 pub fn as_bytes(&self) -> &[u8] {
cdc7bbd5
XL
617 // SAFETY: CString has a length at least 1
618 unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
1a4d82fc
JJ
619 }
620
3dfed10e
XL
621 /// Equivalent to [`CString::as_bytes()`] except that the
622 /// returned slice includes the trailing nul terminator.
041b39d2
XL
623 ///
624 /// # Examples
625 ///
626 /// ```
627 /// use std::ffi::CString;
628 ///
b7449926 629 /// let c_string = CString::new("foo").expect("CString::new failed");
041b39d2
XL
630 /// let bytes = c_string.as_bytes_with_nul();
631 /// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
632 /// ```
633 #[inline]
c34b1796 634 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 635 pub fn as_bytes_with_nul(&self) -> &[u8] {
85aaf69f 636 &self.inner
1a4d82fc 637 }
9e0c209e 638
7cac9316
XL
639 /// Extracts a [`CStr`] slice containing the entire string.
640 ///
041b39d2
XL
641 /// # Examples
642 ///
643 /// ```
644 /// use std::ffi::{CString, CStr};
645 ///
b7449926 646 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
e1599b0c
XL
647 /// let cstr = c_string.as_c_str();
648 /// assert_eq!(cstr,
b7449926 649 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
041b39d2
XL
650 /// ```
651 #[inline]
652 #[stable(feature = "as_c_str", since = "1.20.0")]
cc61c64b
XL
653 pub fn as_c_str(&self) -> &CStr {
654 &*self
655 }
656
7cac9316
XL
657 /// Converts this `CString` into a boxed [`CStr`].
658 ///
041b39d2
XL
659 /// # Examples
660 ///
661 /// ```
662 /// use std::ffi::{CString, CStr};
663 ///
b7449926 664 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
041b39d2 665 /// let boxed = c_string.into_boxed_c_str();
b7449926
XL
666 /// assert_eq!(&*boxed,
667 /// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
041b39d2
XL
668 /// ```
669 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
8bb4bdeb 670 pub fn into_boxed_c_str(self) -> Box<CStr> {
ea8adc8c 671 unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
8bb4bdeb
XL
672 }
673
b7449926 674 /// Bypass "move out of struct which implements [`Drop`] trait" restriction.
17df50a5 675 #[inline]
9e0c209e 676 fn into_inner(self) -> Box<[u8]> {
416331ca
XL
677 // Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
678 // so we use `ManuallyDrop` to ensure `self` is not dropped.
679 // Then we can return the box directly without invalidating it.
680 // See https://github.com/rust-lang/rust/issues/62553.
681 let this = mem::ManuallyDrop::new(self);
682 unsafe { ptr::read(&this.inner) }
9e0c209e 683 }
f035d41b 684
3dfed10e
XL
685 /// Converts a [`Vec`]`<u8>` to a [`CString`] without checking the
686 /// invariants on the given [`Vec`].
f035d41b
XL
687 ///
688 /// # Safety
689 ///
3dfed10e 690 /// The given [`Vec`] **must** have one nul byte as its last element.
f035d41b
XL
691 /// This means it cannot be empty nor have any other nul byte anywhere else.
692 ///
693 /// # Example
694 ///
695 /// ```
696 /// #![feature(cstring_from_vec_with_nul)]
697 /// use std::ffi::CString;
698 /// assert_eq!(
699 /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
700 /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
701 /// );
702 /// ```
703 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
704 pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
705 Self { inner: v.into_boxed_slice() }
706 }
707
3dfed10e 708 /// Attempts to converts a [`Vec`]`<u8>` to a [`CString`].
f035d41b
XL
709 ///
710 /// Runtime checks are present to ensure there is only one nul byte in the
3dfed10e 711 /// [`Vec`], its last element.
f035d41b
XL
712 ///
713 /// # Errors
714 ///
715 /// If a nul byte is present and not the last element or no nul bytes
716 /// is present, an error will be returned.
717 ///
718 /// # Examples
719 ///
3dfed10e
XL
720 /// A successful conversion will produce the same result as [`CString::new`]
721 /// when called without the ending nul byte.
f035d41b
XL
722 ///
723 /// ```
724 /// #![feature(cstring_from_vec_with_nul)]
725 /// use std::ffi::CString;
726 /// assert_eq!(
727 /// CString::from_vec_with_nul(b"abc\0".to_vec())
728 /// .expect("CString::from_vec_with_nul failed"),
729 /// CString::new(b"abc".to_vec()).expect("CString::new failed")
730 /// );
731 /// ```
732 ///
3dfed10e 733 /// A incorrectly formatted [`Vec`] will produce an error.
f035d41b
XL
734 ///
735 /// ```
736 /// #![feature(cstring_from_vec_with_nul)]
737 /// use std::ffi::{CString, FromVecWithNulError};
738 /// // Interior nul byte
739 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
740 /// // No nul byte
741 /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
742 /// ```
f035d41b
XL
743 #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
744 pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
745 let nul_pos = memchr::memchr(0, &v);
746 match nul_pos {
747 Some(nul_pos) if nul_pos + 1 == v.len() => {
748 // SAFETY: We know there is only one nul byte, at the end
749 // of the vec.
750 Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
751 }
752 Some(nul_pos) => Err(FromVecWithNulError {
753 error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
754 bytes: v,
755 }),
756 None => Err(FromVecWithNulError {
757 error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
758 bytes: v,
759 }),
760 }
761 }
9e0c209e
SL
762}
763
764// Turns this `CString` into an empty string to prevent
e1599b0c 765// memory-unsafe code from working by accident. Inline
c30ab7b3 766// to prevent LLVM from optimizing it away in debug builds.
9e0c209e
SL
767#[stable(feature = "cstring_drop", since = "1.13.0")]
768impl Drop for CString {
c30ab7b3 769 #[inline]
9e0c209e 770 fn drop(&mut self) {
dfeec247
XL
771 unsafe {
772 *self.inner.get_unchecked_mut(0) = 0;
773 }
9e0c209e 774 }
1a4d82fc
JJ
775}
776
c34b1796 777#[stable(feature = "rust1", since = "1.0.0")]
9cc50fc6 778impl ops::Deref for CString {
85aaf69f 779 type Target = CStr;
1a4d82fc 780
041b39d2 781 #[inline]
85aaf69f 782 fn deref(&self) -> &CStr {
cc61c64b 783 unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
1a4d82fc
JJ
784 }
785}
786
85aaf69f
SL
787#[stable(feature = "rust1", since = "1.0.0")]
788impl fmt::Debug for CString {
532ac7d7 789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
c1a9b12d
SL
790 fmt::Debug::fmt(&**self, f)
791 }
792}
793
9cc50fc6
SL
794#[stable(feature = "cstring_into", since = "1.7.0")]
795impl From<CString> for Vec<u8> {
b7449926
XL
796 /// Converts a [`CString`] into a [`Vec`]`<u8>`.
797 ///
798 /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
041b39d2 799 #[inline]
9cc50fc6
SL
800 fn from(s: CString) -> Vec<u8> {
801 s.into_bytes()
802 }
803}
804
c1a9b12d
SL
805#[stable(feature = "cstr_debug", since = "1.3.0")]
806impl fmt::Debug for CStr {
532ac7d7 807 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54a0048b 808 write!(f, "\"")?;
c1a9b12d 809 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
54a0048b 810 f.write_char(byte as char)?;
c1a9b12d
SL
811 }
812 write!(f, "\"")
1a4d82fc
JJ
813 }
814}
815
a7813a04 816#[stable(feature = "cstr_default", since = "1.10.0")]
9fa01778
XL
817impl Default for &CStr {
818 fn default() -> Self {
0731742a 819 const SLICE: &[c_char] = &[0];
a7813a04
XL
820 unsafe { CStr::from_ptr(SLICE.as_ptr()) }
821 }
822}
823
824#[stable(feature = "cstr_default", since = "1.10.0")]
825impl Default for CString {
9e0c209e 826 /// Creates an empty `CString`.
a7813a04
XL
827 fn default() -> CString {
828 let a: &CStr = Default::default();
829 a.to_owned()
830 }
831}
832
c1a9b12d
SL
833#[stable(feature = "cstr_borrow", since = "1.3.0")]
834impl Borrow<CStr> for CString {
041b39d2 835 #[inline]
dfeec247
XL
836 fn borrow(&self) -> &CStr {
837 self
838 }
c1a9b12d
SL
839}
840
94b46f34
XL
841#[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
842impl<'a> From<Cow<'a, CStr>> for CString {
843 #[inline]
844 fn from(s: Cow<'a, CStr>) -> Self {
845 s.into_owned()
846 }
847}
848
8bb4bdeb 849#[stable(feature = "box_from_c_str", since = "1.17.0")]
532ac7d7
XL
850impl From<&CStr> for Box<CStr> {
851 fn from(s: &CStr) -> Box<CStr> {
8bb4bdeb 852 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
ea8adc8c 853 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
8bb4bdeb
XL
854 }
855}
856
f9f354fc
XL
857#[stable(feature = "box_from_cow", since = "1.45.0")]
858impl From<Cow<'_, CStr>> for Box<CStr> {
859 #[inline]
860 fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
861 match cow {
862 Cow::Borrowed(s) => Box::from(s),
863 Cow::Owned(s) => Box::from(s),
864 }
865 }
866}
867
7cac9316 868#[stable(feature = "c_string_from_box", since = "1.18.0")]
cc61c64b 869impl From<Box<CStr>> for CString {
b7449926 870 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
041b39d2 871 #[inline]
cc61c64b
XL
872 fn from(s: Box<CStr>) -> CString {
873 s.into_c_string()
874 }
875}
876
74b04a01
XL
877#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
878impl From<Vec<NonZeroU8>> for CString {
879 /// Converts a [`Vec`]`<`[`NonZeroU8`]`>` into a [`CString`] without
880 /// copying nor checking for inner null bytes.
74b04a01
XL
881 #[inline]
882 fn from(v: Vec<NonZeroU8>) -> CString {
883 unsafe {
884 // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
885 let v: Vec<u8> = {
1b1a35ee 886 // SAFETY:
74b04a01
XL
887 // - transmuting between `NonZeroU8` and `u8` is sound;
888 // - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
889 let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
890 Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
891 };
1b1a35ee 892 // SAFETY: `v` cannot contain null bytes, given the type-level
74b04a01
XL
893 // invariant of `NonZeroU8`.
894 CString::from_vec_unchecked(v)
895 }
896 }
897}
898
8faf50e0
XL
899#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
900impl Clone for Box<CStr> {
901 #[inline]
902 fn clone(&self) -> Self {
903 (**self).into()
904 }
905}
906
041b39d2
XL
907#[stable(feature = "box_from_c_string", since = "1.20.0")]
908impl From<CString> for Box<CStr> {
b7449926 909 /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
041b39d2
XL
910 #[inline]
911 fn from(s: CString) -> Box<CStr> {
912 s.into_boxed_c_str()
cc61c64b
XL
913 }
914}
915
94b46f34
XL
916#[stable(feature = "cow_from_cstr", since = "1.28.0")]
917impl<'a> From<CString> for Cow<'a, CStr> {
918 #[inline]
919 fn from(s: CString) -> Cow<'a, CStr> {
920 Cow::Owned(s)
921 }
922}
923
924#[stable(feature = "cow_from_cstr", since = "1.28.0")]
925impl<'a> From<&'a CStr> for Cow<'a, CStr> {
926 #[inline]
927 fn from(s: &'a CStr) -> Cow<'a, CStr> {
928 Cow::Borrowed(s)
929 }
930}
931
932#[stable(feature = "cow_from_cstr", since = "1.28.0")]
933impl<'a> From<&'a CString> for Cow<'a, CStr> {
934 #[inline]
935 fn from(s: &'a CString) -> Cow<'a, CStr> {
936 Cow::Borrowed(s.as_c_str())
937 }
938}
939
2c00a5a8 940#[stable(feature = "shared_from_slice2", since = "1.24.0")]
ff7c6d11 941impl From<CString> for Arc<CStr> {
b7449926 942 /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
ff7c6d11
XL
943 #[inline]
944 fn from(s: CString) -> Arc<CStr> {
945 let arc: Arc<[u8]> = Arc::from(s.into_inner());
946 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
947 }
948}
949
2c00a5a8 950#[stable(feature = "shared_from_slice2", since = "1.24.0")]
532ac7d7 951impl From<&CStr> for Arc<CStr> {
ff7c6d11
XL
952 #[inline]
953 fn from(s: &CStr) -> Arc<CStr> {
954 let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
955 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
956 }
957}
958
2c00a5a8 959#[stable(feature = "shared_from_slice2", since = "1.24.0")]
ff7c6d11 960impl From<CString> for Rc<CStr> {
b7449926 961 /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
ff7c6d11
XL
962 #[inline]
963 fn from(s: CString) -> Rc<CStr> {
964 let rc: Rc<[u8]> = Rc::from(s.into_inner());
965 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
966 }
967}
968
2c00a5a8 969#[stable(feature = "shared_from_slice2", since = "1.24.0")]
532ac7d7 970impl From<&CStr> for Rc<CStr> {
ff7c6d11
XL
971 #[inline]
972 fn from(s: &CStr) -> Rc<CStr> {
973 let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
974 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
975 }
976}
977
8bb4bdeb
XL
978#[stable(feature = "default_box_extra", since = "1.17.0")]
979impl Default for Box<CStr> {
980 fn default() -> Box<CStr> {
981 let boxed: Box<[u8]> = Box::from([0]);
ea8adc8c 982 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
8bb4bdeb
XL
983 }
984}
985
85aaf69f 986impl NulError {
abe05a73
XL
987 /// Returns the position of the nul byte in the slice that caused
988 /// [`CString::new`] to fail.
7cac9316 989 ///
5bcae85e
SL
990 /// # Examples
991 ///
992 /// ```
993 /// use std::ffi::CString;
994 ///
995 /// let nul_error = CString::new("foo\0bar").unwrap_err();
996 /// assert_eq!(nul_error.nul_position(), 3);
997 ///
998 /// let nul_error = CString::new("foo bar\0").unwrap_err();
999 /// assert_eq!(nul_error.nul_position(), 7);
1000 /// ```
c34b1796 1001 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1002 pub fn nul_position(&self) -> usize {
1003 self.0
1004 }
85aaf69f
SL
1005
1006 /// Consumes this error, returning the underlying vector of bytes which
1007 /// generated the error in the first place.
5bcae85e
SL
1008 ///
1009 /// # Examples
1010 ///
1011 /// ```
1012 /// use std::ffi::CString;
1013 ///
1014 /// let nul_error = CString::new("foo\0bar").unwrap_err();
1015 /// assert_eq!(nul_error.into_vec(), b"foo\0bar");
1016 /// ```
c34b1796 1017 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247
XL
1018 pub fn into_vec(self) -> Vec<u8> {
1019 self.1
1020 }
85aaf69f
SL
1021}
1022
c34b1796 1023#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1024impl Error for NulError {
dfeec247
XL
1025 #[allow(deprecated)]
1026 fn description(&self) -> &str {
1027 "nul byte found in data"
1028 }
85aaf69f
SL
1029}
1030
c34b1796 1031#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1032impl fmt::Display for NulError {
532ac7d7 1033 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85aaf69f
SL
1034 write!(f, "nul byte found in provided data at position: {}", self.0)
1035 }
1036}
1037
c34b1796
AL
1038#[stable(feature = "rust1", since = "1.0.0")]
1039impl From<NulError> for io::Error {
b7449926 1040 /// Converts a [`NulError`] into a [`io::Error`].
c34b1796 1041 fn from(_: NulError) -> io::Error {
cdc7bbd5 1042 io::Error::new_const(io::ErrorKind::InvalidInput, &"data provided contains a nul byte")
85aaf69f
SL
1043 }
1044}
1045
8bb4bdeb
XL
1046#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1047impl Error for FromBytesWithNulError {
dfeec247 1048 #[allow(deprecated)]
8bb4bdeb
XL
1049 fn description(&self) -> &str {
1050 match self.kind {
dfeec247
XL
1051 FromBytesWithNulErrorKind::InteriorNul(..) => {
1052 "data provided contains an interior nul byte"
1053 }
1054 FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
8bb4bdeb
XL
1055 }
1056 }
1057}
1058
1059#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
1060impl fmt::Display for FromBytesWithNulError {
dfeec247 1061 #[allow(deprecated, deprecated_in_future)]
532ac7d7 1062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8bb4bdeb
XL
1063 f.write_str(self.description())?;
1064 if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
1065 write!(f, " at byte pos {}", pos)?;
1066 }
1067 Ok(())
1068 }
1069}
1070
f035d41b
XL
1071#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1072impl Error for FromVecWithNulError {}
1073
1074#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
1075impl fmt::Display for FromVecWithNulError {
1076 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1077 match self.error_kind {
1078 FromBytesWithNulErrorKind::InteriorNul(pos) => {
1079 write!(f, "data provided contains an interior nul byte at pos {}", pos)
1080 }
1081 FromBytesWithNulErrorKind::NotNulTerminated => {
1082 write!(f, "data provided is not nul terminated")
1083 }
1084 }
1085 }
1086}
1087
b039eaaf 1088impl IntoStringError {
7cac9316 1089 /// Consumes this error, returning original [`CString`] which generated the
b039eaaf 1090 /// error.
9cc50fc6 1091 #[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf
SL
1092 pub fn into_cstring(self) -> CString {
1093 self.inner
1094 }
1095
1096 /// Access the underlying UTF-8 error that was the cause of this error.
9cc50fc6 1097 #[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf
SL
1098 pub fn utf8_error(&self) -> Utf8Error {
1099 self.error
1100 }
1101}
1102
9cc50fc6 1103#[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf 1104impl Error for IntoStringError {
dfeec247 1105 #[allow(deprecated)]
b039eaaf 1106 fn description(&self) -> &str {
9cc50fc6
SL
1107 "C string contained non-utf8 bytes"
1108 }
1109
e74abb32 1110 fn source(&self) -> Option<&(dyn Error + 'static)> {
9cc50fc6 1111 Some(&self.error)
b039eaaf
SL
1112 }
1113}
1114
9cc50fc6 1115#[stable(feature = "cstring_into", since = "1.7.0")]
b039eaaf 1116impl fmt::Display for IntoStringError {
dfeec247 1117 #[allow(deprecated, deprecated_in_future)]
532ac7d7 1118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9cc50fc6 1119 self.description().fmt(f)
b039eaaf
SL
1120 }
1121}
1122
85aaf69f 1123impl CStr {
abe05a73 1124 /// Wraps a raw C string with a safe C string wrapper.
85aaf69f 1125 ///
abe05a73 1126 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
e1599b0c
XL
1127 /// allows inspection and interoperation of non-owned C strings. The total
1128 /// size of the raw C string must be smaller than `isize::MAX` **bytes**
1129 /// in memory due to calling the `slice::from_raw_parts` function.
1130 /// This method is unsafe for a number of reasons:
85aaf69f 1131 ///
7cac9316 1132 /// * There is no guarantee to the validity of `ptr`.
85aaf69f 1133 /// * The returned lifetime is not guaranteed to be the actual lifetime of
7cac9316 1134 /// `ptr`.
85aaf69f
SL
1135 /// * There is no guarantee that the memory pointed to by `ptr` contains a
1136 /// valid nul terminator byte at the end of the string.
0531ce1d
XL
1137 /// * It is not guaranteed that the memory pointed by `ptr` won't change
1138 /// before the `CStr` has been destroyed.
85aaf69f
SL
1139 ///
1140 /// > **Note**: This operation is intended to be a 0-cost cast but it is
1141 /// > currently implemented with an up-front calculation of the length of
1142 /// > the string. This is not guaranteed to always be the case.
1143 ///
c34b1796 1144 /// # Examples
85aaf69f 1145 ///
0531ce1d 1146 /// ```ignore (extern-declaration)
85aaf69f
SL
1147 /// # fn main() {
1148 /// use std::ffi::CStr;
92a42be0 1149 /// use std::os::raw::c_char;
85aaf69f 1150 ///
5869c6ff 1151 /// extern "C" {
92a42be0 1152 /// fn my_string() -> *const c_char;
85aaf69f
SL
1153 /// }
1154 ///
1155 /// unsafe {
1156 /// let slice = CStr::from_ptr(my_string());
7453a54e 1157 /// println!("string returned: {}", slice.to_str().unwrap());
85aaf69f
SL
1158 /// }
1159 /// # }
1160 /// ```
c34b1796 1161 #[stable(feature = "rust1", since = "1.0.0")]
92a42be0 1162 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
3dfed10e
XL
1163 // SAFETY: The caller has provided a pointer that points to a valid C
1164 // string with a NUL terminator of size less than `isize::MAX`, whose
1165 // content remain valid and doesn't change for the lifetime of the
1166 // returned `CStr`.
1167 //
1168 // Thus computing the length is fine (a NUL byte exists), the call to
1169 // from_raw_parts is safe because we know the length is at most `isize::MAX`, meaning
1170 // the call to `from_bytes_with_nul_unchecked` is correct.
1171 //
1172 // The cast from c_char to u8 is ok because a c_char is always one byte.
1173 unsafe {
1174 let len = sys::strlen(ptr);
1175 let ptr = ptr as *const u8;
1176 CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
1177 }
85aaf69f
SL
1178 }
1179
7453a54e
SL
1180 /// Creates a C string wrapper from a byte slice.
1181 ///
abe05a73
XL
1182 /// This function will cast the provided `bytes` to a `CStr`
1183 /// wrapper after ensuring that the byte slice is nul-terminated
1184 /// and does not contain any interior nul bytes.
7453a54e
SL
1185 ///
1186 /// # Examples
1187 ///
1188 /// ```
7453a54e
SL
1189 /// use std::ffi::CStr;
1190 ///
7453a54e 1191 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
a7813a04 1192 /// assert!(cstr.is_ok());
7453a54e 1193 /// ```
041b39d2 1194 ///
abe05a73 1195 /// Creating a `CStr` without a trailing nul terminator is an error:
041b39d2
XL
1196 ///
1197 /// ```
1198 /// use std::ffi::CStr;
1199 ///
e1599b0c
XL
1200 /// let cstr = CStr::from_bytes_with_nul(b"hello");
1201 /// assert!(cstr.is_err());
041b39d2
XL
1202 /// ```
1203 ///
1204 /// Creating a `CStr` with an interior nul byte is an error:
1205 ///
1206 /// ```
1207 /// use std::ffi::CStr;
1208 ///
e1599b0c
XL
1209 /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
1210 /// assert!(cstr.is_err());
041b39d2 1211 /// ```
a7813a04 1212 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
dfeec247 1213 pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
8bb4bdeb
XL
1214 let nul_pos = memchr::memchr(0, bytes);
1215 if let Some(nul_pos) = nul_pos {
1216 if nul_pos + 1 != bytes.len() {
1217 return Err(FromBytesWithNulError::interior_nul(nul_pos));
1218 }
1219 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
7453a54e 1220 } else {
8bb4bdeb 1221 Err(FromBytesWithNulError::not_nul_terminated())
7453a54e
SL
1222 }
1223 }
1224
1225 /// Unsafely creates a C string wrapper from a byte slice.
1226 ///
1227 /// This function will cast the provided `bytes` to a `CStr` wrapper without
abe05a73 1228 /// performing any sanity checks. The provided slice **must** be nul-terminated
7453a54e
SL
1229 /// and not contain any interior nul bytes.
1230 ///
1231 /// # Examples
1232 ///
1233 /// ```
7453a54e
SL
1234 /// use std::ffi::{CStr, CString};
1235 ///
7453a54e 1236 /// unsafe {
b7449926 1237 /// let cstring = CString::new("hello").expect("CString::new failed");
7453a54e
SL
1238 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
1239 /// assert_eq!(cstr, &*cstring);
1240 /// }
7453a54e 1241 /// ```
041b39d2 1242 #[inline]
a7813a04 1243 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
dfeec247 1244 #[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
0bf4aa26 1245 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
3dfed10e
XL
1246 // SAFETY: Casting to CStr is safe because its internal representation
1247 // is a [u8] too (safe only inside std).
1248 // Dereferencing the obtained pointer is safe because it comes from a
1249 // reference. Making a reference is then safe because its lifetime
1250 // is bound by the lifetime of the given `bytes`.
1251 unsafe { &*(bytes as *const [u8] as *const CStr) }
7453a54e
SL
1252 }
1253
9346a6ac 1254 /// Returns the inner pointer to this C string.
85aaf69f 1255 ///
abe05a73 1256 /// The returned pointer will be valid for as long as `self` is, and points
c34b1796 1257 /// to a contiguous region of memory terminated with a 0 byte to represent
85aaf69f 1258 /// the end of the string.
3157f602
XL
1259 ///
1260 /// **WARNING**
1261 ///
48663c56
XL
1262 /// The returned pointer is read-only; writing to it (including passing it
1263 /// to C code that writes to it) causes undefined behavior.
1264 ///
3157f602
XL
1265 /// It is your responsibility to make sure that the underlying memory is not
1266 /// freed too early. For example, the following code will cause undefined
3b2f2976 1267 /// behavior when `ptr` is used inside the `unsafe` block:
3157f602
XL
1268 ///
1269 /// ```no_run
fc512014 1270 /// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
416331ca 1271 /// use std::ffi::CString;
3157f602 1272 ///
b7449926 1273 /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
3157f602
XL
1274 /// unsafe {
1275 /// // `ptr` is dangling
1276 /// *ptr;
1277 /// }
1278 /// ```
1279 ///
1280 /// This happens because the pointer returned by `as_ptr` does not carry any
abe05a73 1281 /// lifetime information and the [`CString`] is deallocated immediately after
3dfed10e
XL
1282 /// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
1283 /// expression is evaluated.
abe05a73 1284 /// To fix the problem, bind the `CString` to a local variable:
3157f602
XL
1285 ///
1286 /// ```no_run
83c7162d 1287 /// # #![allow(unused_must_use)]
416331ca 1288 /// use std::ffi::CString;
3157f602 1289 ///
b7449926 1290 /// let hello = CString::new("Hello").expect("CString::new failed");
3157f602
XL
1291 /// let ptr = hello.as_ptr();
1292 /// unsafe {
1293 /// // `ptr` is valid because `hello` is in scope
1294 /// *ptr;
1295 /// }
1296 /// ```
abe05a73 1297 ///
3dfed10e 1298 /// This way, the lifetime of the [`CString`] in `hello` encompasses
abe05a73 1299 /// the lifetime of `ptr` and the `unsafe` block.
041b39d2 1300 #[inline]
c34b1796 1301 #[stable(feature = "rust1", since = "1.0.0")]
dfeec247 1302 #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
a1dfa0c6 1303 pub const fn as_ptr(&self) -> *const c_char {
85aaf69f
SL
1304 self.inner.as_ptr()
1305 }
1306
9346a6ac 1307 /// Converts this C string to a byte slice.
85aaf69f 1308 ///
abe05a73 1309 /// The returned slice will **not** contain the trailing nul terminator that this C
85aaf69f
SL
1310 /// string has.
1311 ///
2c00a5a8
XL
1312 /// > **Note**: This method is currently implemented as a constant-time
1313 /// > cast, but it is planned to alter its definition in the future to
1314 /// > perform the length calculation whenever this method is called.
041b39d2
XL
1315 ///
1316 /// # Examples
1317 ///
1318 /// ```
1319 /// use std::ffi::CStr;
1320 ///
e1599b0c
XL
1321 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1322 /// assert_eq!(cstr.to_bytes(), b"foo");
041b39d2
XL
1323 /// ```
1324 #[inline]
c34b1796 1325 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1326 pub fn to_bytes(&self) -> &[u8] {
1327 let bytes = self.to_bytes_with_nul();
cdc7bbd5
XL
1328 // SAFETY: to_bytes_with_nul returns slice with length at least 1
1329 unsafe { bytes.get_unchecked(..bytes.len() - 1) }
85aaf69f
SL
1330 }
1331
9346a6ac 1332 /// Converts this C string to a byte slice containing the trailing 0 byte.
85aaf69f 1333 ///
3dfed10e
XL
1334 /// This function is the equivalent of [`CStr::to_bytes`] except that it
1335 /// will retain the trailing nul terminator instead of chopping it off.
85aaf69f
SL
1336 ///
1337 /// > **Note**: This method is currently implemented as a 0-cost cast, but
1338 /// > it is planned to alter its definition in the future to perform the
1339 /// > length calculation whenever this method is called.
7cac9316 1340 ///
041b39d2
XL
1341 /// # Examples
1342 ///
1343 /// ```
1344 /// use std::ffi::CStr;
1345 ///
e1599b0c
XL
1346 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1347 /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
041b39d2
XL
1348 /// ```
1349 #[inline]
c34b1796 1350 #[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1351 pub fn to_bytes_with_nul(&self) -> &[u8] {
ea8adc8c 1352 unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
85aaf69f 1353 }
62682a34 1354
7cac9316 1355 /// Yields a [`&str`] slice if the `CStr` contains valid UTF-8.
62682a34 1356 ///
abe05a73
XL
1357 /// If the contents of the `CStr` are valid UTF-8 data, this
1358 /// function will return the corresponding [`&str`] slice. Otherwise,
1359 /// it will return an error with details of where UTF-8 validation failed.
62682a34 1360 ///
3dfed10e 1361 /// [`&str`]: prim@str
041b39d2
XL
1362 ///
1363 /// # Examples
1364 ///
1365 /// ```
1366 /// use std::ffi::CStr;
1367 ///
e1599b0c
XL
1368 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
1369 /// assert_eq!(cstr.to_str(), Ok("foo"));
041b39d2 1370 /// ```
e9174d1e 1371 #[stable(feature = "cstr_to_str", since = "1.4.0")]
62682a34 1372 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
0731742a
XL
1373 // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
1374 // instead of in `from_ptr()`, it may be worth considering if this should
e9174d1e
SL
1375 // be rewritten to do the UTF-8 check inline with the length calculation
1376 // instead of doing it afterwards.
62682a34
SL
1377 str::from_utf8(self.to_bytes())
1378 }
1379
7cac9316 1380 /// Converts a `CStr` into a [`Cow`]`<`[`str`]`>`.
62682a34 1381 ///
abe05a73
XL
1382 /// If the contents of the `CStr` are valid UTF-8 data, this
1383 /// function will return a [`Cow`]`::`[`Borrowed`]`(`[`&str`]`)`
a1dfa0c6 1384 /// with the corresponding [`&str`] slice. Otherwise, it will
b7449926
XL
1385 /// replace any invalid UTF-8 sequences with
1386 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
1387 /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
62682a34 1388 ///
29967ef6
XL
1389 /// [`str`]: primitive@str
1390 /// [`&str`]: primitive@str
3dfed10e
XL
1391 /// [`Borrowed`]: Cow::Borrowed
1392 /// [`Owned`]: Cow::Owned
1393 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
041b39d2
XL
1394 ///
1395 /// # Examples
1396 ///
1397 /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
1398 ///
1399 /// ```
1400 /// use std::borrow::Cow;
1401 /// use std::ffi::CStr;
1402 ///
e1599b0c 1403 /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
b7449926 1404 /// .expect("CStr::from_bytes_with_nul failed");
e1599b0c 1405 /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
041b39d2
XL
1406 /// ```
1407 ///
1408 /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
1409 ///
1410 /// ```
1411 /// use std::borrow::Cow;
1412 /// use std::ffi::CStr;
1413 ///
e1599b0c 1414 /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
b7449926 1415 /// .expect("CStr::from_bytes_with_nul failed");
041b39d2 1416 /// assert_eq!(
e1599b0c 1417 /// cstr.to_string_lossy(),
532ac7d7 1418 /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str>
041b39d2
XL
1419 /// );
1420 /// ```
e9174d1e 1421 #[stable(feature = "cstr_to_str", since = "1.4.0")]
532ac7d7 1422 pub fn to_string_lossy(&self) -> Cow<'_, str> {
62682a34
SL
1423 String::from_utf8_lossy(self.to_bytes())
1424 }
cc61c64b 1425
7cac9316
XL
1426 /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
1427 ///
041b39d2
XL
1428 /// # Examples
1429 ///
1430 /// ```
1431 /// use std::ffi::CString;
1432 ///
b7449926 1433 /// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
041b39d2 1434 /// let boxed = c_string.into_boxed_c_str();
b7449926 1435 /// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
041b39d2
XL
1436 /// ```
1437 #[stable(feature = "into_boxed_c_str", since = "1.20.0")]
cc61c64b 1438 pub fn into_c_string(self: Box<CStr>) -> CString {
ea8adc8c
XL
1439 let raw = Box::into_raw(self) as *mut [u8];
1440 CString { inner: unsafe { Box::from_raw(raw) } }
cc61c64b 1441 }
85aaf69f
SL
1442}
1443
c34b1796 1444#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1445impl PartialEq for CStr {
1446 fn eq(&self, other: &CStr) -> bool {
c34b1796 1447 self.to_bytes().eq(other.to_bytes())
85aaf69f
SL
1448 }
1449}
c34b1796 1450#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f 1451impl Eq for CStr {}
c34b1796 1452#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1453impl PartialOrd for CStr {
1454 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
1455 self.to_bytes().partial_cmp(&other.to_bytes())
1456 }
1457}
c34b1796 1458#[stable(feature = "rust1", since = "1.0.0")]
85aaf69f
SL
1459impl Ord for CStr {
1460 fn cmp(&self, other: &CStr) -> Ordering {
1461 self.to_bytes().cmp(&other.to_bytes())
1462 }
1463}
1464
c1a9b12d
SL
1465#[stable(feature = "cstr_borrow", since = "1.3.0")]
1466impl ToOwned for CStr {
1467 type Owned = CString;
1468
1469 fn to_owned(&self) -> CString {
8bb4bdeb 1470 CString { inner: self.to_bytes_with_nul().into() }
c1a9b12d 1471 }
ba9703b0
XL
1472
1473 fn clone_into(&self, target: &mut CString) {
1474 let mut b = Vec::from(mem::take(&mut target.inner));
1475 self.to_bytes_with_nul().clone_into(&mut b);
1476 target.inner = b.into_boxed_slice();
1477 }
c1a9b12d
SL
1478}
1479
9cc50fc6 1480#[stable(feature = "cstring_asref", since = "1.7.0")]
532ac7d7
XL
1481impl From<&CStr> for CString {
1482 fn from(s: &CStr) -> CString {
9cc50fc6
SL
1483 s.to_owned()
1484 }
1485}
1486
1487#[stable(feature = "cstring_asref", since = "1.7.0")]
1488impl ops::Index<ops::RangeFull> for CString {
1489 type Output = CStr;
1490
1491 #[inline]
1492 fn index(&self, _index: ops::RangeFull) -> &CStr {
1493 self
1494 }
1495}
1496
3dfed10e
XL
1497#[stable(feature = "cstr_range_from", since = "1.47.0")]
1498impl ops::Index<ops::RangeFrom<usize>> for CStr {
1499 type Output = CStr;
1500
1501 fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
1502 let bytes = self.to_bytes_with_nul();
1503 // we need to manually check the starting index to account for the null
1504 // byte, since otherwise we could get an empty string that doesn't end
1505 // in a null.
1506 if index.start < bytes.len() {
1507 unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
1508 } else {
1509 panic!(
1510 "index out of bounds: the len is {} but the index is {}",
1511 bytes.len(),
1512 index.start
1513 );
1514 }
1515 }
1516}
1517
9cc50fc6
SL
1518#[stable(feature = "cstring_asref", since = "1.7.0")]
1519impl AsRef<CStr> for CStr {
041b39d2 1520 #[inline]
9cc50fc6
SL
1521 fn as_ref(&self) -> &CStr {
1522 self
1523 }
1524}
1525
1526#[stable(feature = "cstring_asref", since = "1.7.0")]
1527impl AsRef<CStr> for CString {
041b39d2 1528 #[inline]
9cc50fc6
SL
1529 fn as_ref(&self) -> &CStr {
1530 self
1531 }
1532}