2020-08-27 13:45:01 +00:00
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests;
|
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
use crate::borrow::{Cow, ToOwned};
|
|
|
|
|
use crate::boxed::Box;
|
2019-02-10 19:23:21 +00:00
|
|
|
|
use crate::rc::Rc;
|
2022-02-16 11:23:37 +00:00
|
|
|
|
use crate::slice::hack::into_vec;
|
|
|
|
|
use crate::string::String;
|
|
|
|
|
use crate::vec::Vec;
|
|
|
|
|
use core::borrow::Borrow;
|
|
|
|
|
use core::ffi::{c_char, CStr};
|
|
|
|
|
use core::fmt;
|
|
|
|
|
use core::mem;
|
|
|
|
|
use core::num::NonZeroU8;
|
|
|
|
|
use core::ops;
|
|
|
|
|
use core::ptr;
|
|
|
|
|
use core::slice;
|
|
|
|
|
use core::slice::memchr;
|
|
|
|
|
use core::str::{self, Utf8Error};
|
2014-11-25 21:28:35 +00:00
|
|
|
|
|
2022-04-13 13:35:40 +00:00
|
|
|
|
#[cfg(target_has_atomic = "ptr")]
|
|
|
|
|
use crate::sync::Arc;
|
|
|
|
|
|
2017-10-02 18:53:50 +00:00
|
|
|
|
/// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the
|
|
|
|
|
/// middle.
|
2014-11-25 21:28:35 +00:00
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// This type serves the purpose of being able to safely generate a
|
2014-11-25 21:28:35 +00:00
|
|
|
|
/// C-compatible string from a Rust byte slice or vector. An instance of this
|
|
|
|
|
/// type is a static guarantee that the underlying bytes contain no interior 0
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// bytes ("nul characters") and that the final byte is 0 ("nul terminator").
|
2014-11-25 21:28:35 +00:00
|
|
|
|
///
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// `CString` is to <code>&[CStr]</code> as [`String`] is to <code>&[str]</code>: the former
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// in each pair are owned strings; the latter are borrowed
|
|
|
|
|
/// references.
|
2014-11-25 21:28:35 +00:00
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// # Creating a `CString`
|
|
|
|
|
///
|
|
|
|
|
/// A `CString` is created from either a byte slice or a byte vector,
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// or anything that implements <code>[Into]<[Vec]<[u8]>></code> (for
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// example, you can build a `CString` straight out of a [`String`] or
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// a <code>&[str]</code>, since both implement that trait).
|
2017-09-23 01:36:44 +00:00
|
|
|
|
///
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// The [`CString::new`] method will actually check that the provided <code>&[[u8]]</code>
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// does not have 0 bytes in the middle, and return an error if it
|
|
|
|
|
/// finds one.
|
|
|
|
|
///
|
|
|
|
|
/// # Extracting a raw pointer to the whole C string
|
|
|
|
|
///
|
2021-08-22 12:46:15 +00:00
|
|
|
|
/// `CString` implements an [`as_ptr`][`CStr::as_ptr`] method through the [`Deref`]
|
2017-10-11 22:53:13 +00:00
|
|
|
|
/// trait. This method will give you a `*const c_char` which you can
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// feed directly to extern functions that expect a nul-terminated
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// string, like C's `strdup()`. Notice that [`as_ptr`][`CStr::as_ptr`] returns a
|
2019-05-01 15:59:48 +00:00
|
|
|
|
/// read-only pointer; if the C code writes to it, that causes
|
|
|
|
|
/// undefined behavior.
|
2017-09-23 01:36:44 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Extracting a slice of the whole C string
|
|
|
|
|
///
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Alternatively, you can obtain a <code>&[[u8]]</code> slice from a
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// `CString` with the [`CString::as_bytes`] method. Slices produced in this
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// way do *not* contain the trailing nul terminator. This is useful
|
|
|
|
|
/// when you will be calling an extern function that takes a `*const
|
|
|
|
|
/// u8` argument which is not necessarily nul-terminated, plus another
|
|
|
|
|
/// argument with the length of the string — like C's `strndup()`.
|
|
|
|
|
/// You can of course get the slice's length with its
|
2020-12-19 13:23:59 +00:00
|
|
|
|
/// [`len`][slice::len] method.
|
2017-09-23 01:36:44 +00:00
|
|
|
|
///
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// If you need a <code>&[[u8]]</code> slice *with* the nul terminator, you
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// can use [`CString::as_bytes_with_nul`] instead.
|
2017-09-23 01:36:44 +00:00
|
|
|
|
///
|
|
|
|
|
/// Once you have the kind of slice you need (with or without a nul
|
|
|
|
|
/// terminator), you can call the slice's own
|
2020-12-19 13:23:59 +00:00
|
|
|
|
/// [`as_ptr`][slice::as_ptr] method to get a read-only raw pointer to pass to
|
2017-10-11 22:53:13 +00:00
|
|
|
|
/// extern functions. See the documentation for that function for a
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// discussion on ensuring the lifetime of the raw pointer.
|
|
|
|
|
///
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// [str]: prim@str "str"
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// [`Deref`]: ops::Deref
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2015-03-12 01:11:40 +00:00
|
|
|
|
/// # Examples
|
2014-11-25 21:28:35 +00:00
|
|
|
|
///
|
2018-02-18 14:30:10 +00:00
|
|
|
|
/// ```ignore (extern-declaration)
|
2014-11-25 21:28:35 +00:00
|
|
|
|
/// # fn main() {
|
|
|
|
|
/// use std::ffi::CString;
|
2015-11-11 17:02:55 +00:00
|
|
|
|
/// use std::os::raw::c_char;
|
2014-11-25 21:28:35 +00:00
|
|
|
|
///
|
2020-09-01 21:12:52 +00:00
|
|
|
|
/// extern "C" {
|
2015-11-11 17:02:55 +00:00
|
|
|
|
/// fn my_printer(s: *const c_char);
|
2014-11-25 21:28:35 +00:00
|
|
|
|
/// }
|
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// // We are certain that our string doesn't have 0 bytes in the middle,
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// // so we can .expect()
|
|
|
|
|
/// let c_to_print = CString::new("Hello, world!").expect("CString::new failed");
|
2014-11-25 21:28:35 +00:00
|
|
|
|
/// unsafe {
|
|
|
|
|
/// my_printer(c_to_print.as_ptr());
|
|
|
|
|
/// }
|
|
|
|
|
/// # }
|
|
|
|
|
/// ```
|
2016-01-24 22:41:44 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
|
|
|
|
/// `CString` is intended for working with traditional C-style strings
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// (a sequence of non-nul bytes terminated by a single nul byte); the
|
2016-01-24 22:41:44 +00:00
|
|
|
|
/// primary use case for these kinds of strings is interoperating with C-like
|
|
|
|
|
/// code. Often you will need to transfer ownership to/from that external
|
|
|
|
|
/// code. It is strongly recommended that you thoroughly read through the
|
|
|
|
|
/// documentation of `CString` before use, as improper ownership management
|
|
|
|
|
/// of `CString` instances can lead to invalid memory accesses, memory leaks,
|
|
|
|
|
/// and other memory errors.
|
2015-07-27 05:12:00 +00:00
|
|
|
|
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
|
2020-09-21 20:32:28 +00:00
|
|
|
|
#[cfg_attr(not(test), rustc_diagnostic_item = "cstring_type")]
|
2022-07-15 10:10:35 +00:00
|
|
|
|
#[stable(feature = "alloc_c_string", since = "1.64.0")]
|
2014-11-25 21:28:35 +00:00
|
|
|
|
pub struct CString {
|
2016-09-04 15:37:30 +00:00
|
|
|
|
// Invariant 1: the slice ends with a zero byte and has a length of at least one.
|
|
|
|
|
// Invariant 2: the slice contains only one zero byte.
|
|
|
|
|
// Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
|
2015-06-03 21:35:50 +00:00
|
|
|
|
inner: Box<[u8]>,
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-10-11 22:51:37 +00:00
|
|
|
|
/// An error indicating that an interior nul byte was found.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2017-10-11 22:51:37 +00:00
|
|
|
|
/// While Rust strings may contain nul bytes in the middle, C strings
|
|
|
|
|
/// can't, as that byte would effectively truncate the string.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2017-10-11 22:51:37 +00:00
|
|
|
|
/// This error is created by the [`new`][`CString::new`] method on
|
2017-09-25 15:53:13 +00:00
|
|
|
|
/// [`CString`]. See its documentation for more.
|
|
|
|
|
///
|
2017-06-19 00:31:06 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::{CString, NulError};
|
|
|
|
|
///
|
|
|
|
|
/// let _: NulError = CString::new(b"f\0oo".to_vec()).unwrap_err();
|
|
|
|
|
/// ```
|
2016-09-12 19:37:41 +00:00
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
2022-07-15 10:10:35 +00:00
|
|
|
|
#[stable(feature = "alloc_c_string", since = "1.64.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
pub struct NulError(usize, Vec<u8>);
|
|
|
|
|
|
2016-09-12 19:37:41 +00:00
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
2022-02-16 11:23:37 +00:00
|
|
|
|
enum FromBytesWithNulErrorKind {
|
|
|
|
|
InteriorNul(usize),
|
|
|
|
|
NotNulTerminated,
|
2017-03-09 12:31:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-14 21:21:40 +00:00
|
|
|
|
/// An error indicating that a nul byte was not in the expected position.
|
|
|
|
|
///
|
|
|
|
|
/// The vector used to create a [`CString`] must have one and only one nul byte,
|
|
|
|
|
/// positioned at the end.
|
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// This error is created by the [`CString::from_vec_with_nul`] method.
|
2020-06-14 21:21:40 +00:00
|
|
|
|
/// See its documentation for more.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::{CString, FromVecWithNulError};
|
|
|
|
|
///
|
|
|
|
|
/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
|
|
|
|
|
/// ```
|
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
2022-07-15 10:10:35 +00:00
|
|
|
|
#[stable(feature = "alloc_c_string", since = "1.64.0")]
|
2020-06-14 21:21:40 +00:00
|
|
|
|
pub struct FromVecWithNulError {
|
|
|
|
|
error_kind: FromBytesWithNulErrorKind,
|
|
|
|
|
bytes: Vec<u8>,
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-26 21:38:51 +00:00
|
|
|
|
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
|
2020-06-14 21:21:40 +00:00
|
|
|
|
impl FromVecWithNulError {
|
|
|
|
|
/// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
|
|
|
|
/// // Some invalid bytes in a vector
|
|
|
|
|
/// let bytes = b"f\0oo".to_vec();
|
|
|
|
|
///
|
|
|
|
|
/// let value = CString::from_vec_with_nul(bytes.clone());
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(&bytes[..], value.unwrap_err().as_bytes());
|
|
|
|
|
/// ```
|
2021-10-11 17:57:38 +00:00
|
|
|
|
#[must_use]
|
2021-09-26 21:38:51 +00:00
|
|
|
|
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
|
2020-06-14 21:21:40 +00:00
|
|
|
|
pub fn as_bytes(&self) -> &[u8] {
|
|
|
|
|
&self.bytes[..]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Returns the bytes that were attempted to convert to a [`CString`].
|
|
|
|
|
///
|
|
|
|
|
/// This method is carefully constructed to avoid allocation. It will
|
|
|
|
|
/// consume the error, moving out the bytes, so that a copy of the bytes
|
|
|
|
|
/// does not need to be made.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
|
|
|
|
/// // Some invalid bytes in a vector
|
|
|
|
|
/// let bytes = b"f\0oo".to_vec();
|
|
|
|
|
///
|
|
|
|
|
/// let value = CString::from_vec_with_nul(bytes.clone());
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(bytes, value.unwrap_err().into_bytes());
|
|
|
|
|
/// ```
|
2021-10-10 23:50:52 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2021-09-26 21:38:51 +00:00
|
|
|
|
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
|
2020-06-14 21:21:40 +00:00
|
|
|
|
pub fn into_bytes(self) -> Vec<u8> {
|
|
|
|
|
self.bytes
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-11 22:51:37 +00:00
|
|
|
|
/// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`].
|
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// `CString` is just a wrapper over a buffer of bytes with a nul terminator;
|
|
|
|
|
/// [`CString::into_string`] performs UTF-8 validation on those bytes and may
|
|
|
|
|
/// return this error.
|
2017-09-25 15:53:13 +00:00
|
|
|
|
///
|
2020-08-14 17:08:09 +00:00
|
|
|
|
/// This `struct` is created by [`CString::into_string()`]. See
|
2017-09-25 15:53:13 +00:00
|
|
|
|
/// its documentation for more.
|
2016-09-12 19:37:41 +00:00
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
2022-07-15 10:10:35 +00:00
|
|
|
|
#[stable(feature = "alloc_c_string", since = "1.64.0")]
|
2015-10-11 23:49:57 +00:00
|
|
|
|
pub struct IntoStringError {
|
|
|
|
|
inner: CString,
|
|
|
|
|
error: Utf8Error,
|
|
|
|
|
}
|
|
|
|
|
|
2014-11-25 21:28:35 +00:00
|
|
|
|
impl CString {
|
2015-04-13 14:21:32 +00:00
|
|
|
|
/// Creates a new C-compatible string from a container of bytes.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2017-10-11 22:52:39 +00:00
|
|
|
|
/// This function will consume the provided data and use the
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// underlying bytes to construct a new string, ensuring that
|
2017-10-11 22:52:39 +00:00
|
|
|
|
/// there is a trailing 0 byte. This trailing 0 byte will be
|
|
|
|
|
/// appended by this function; the provided data should *not*
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// contain any 0 bytes in it.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
2018-02-18 14:30:10 +00:00
|
|
|
|
/// ```ignore (extern-declaration)
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// use std::ffi::CString;
|
2015-11-11 17:02:55 +00:00
|
|
|
|
/// use std::os::raw::c_char;
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2020-09-01 21:12:52 +00:00
|
|
|
|
/// extern "C" { fn puts(s: *const c_char); }
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let to_print = CString::new("Hello!").expect("CString::new failed");
|
2016-08-08 04:07:36 +00:00
|
|
|
|
/// unsafe {
|
|
|
|
|
/// puts(to_print.as_ptr());
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// # Errors
|
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// This function will return an error if the supplied bytes contain an
|
|
|
|
|
/// internal 0 byte. The [`NulError`] returned will contain the bytes as well as
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// the position of the nul byte.
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-03-18 16:14:54 +00:00
|
|
|
|
pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
|
2021-12-20 12:57:47 +00:00
|
|
|
|
trait SpecNewImpl {
|
|
|
|
|
fn spec_new_impl(self) -> Result<CString, NulError>;
|
2019-10-18 07:10:13 +00:00
|
|
|
|
}
|
2021-12-20 12:57:47 +00:00
|
|
|
|
|
|
|
|
|
impl<T: Into<Vec<u8>>> SpecNewImpl for T {
|
|
|
|
|
default fn spec_new_impl(self) -> Result<CString, NulError> {
|
|
|
|
|
let bytes: Vec<u8> = self.into();
|
|
|
|
|
match memchr::memchr(0, &bytes) {
|
|
|
|
|
Some(i) => Err(NulError(i, bytes)),
|
2022-02-13 23:04:11 +00:00
|
|
|
|
None => Ok(unsafe { CString::_from_vec_unchecked(bytes) }),
|
2021-12-20 12:57:47 +00:00
|
|
|
|
}
|
2019-10-18 07:10:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2021-12-20 12:57:47 +00:00
|
|
|
|
|
|
|
|
|
// Specialization for avoiding reallocation
|
|
|
|
|
#[inline(always)] // Without that it is not inlined into specializations
|
|
|
|
|
fn spec_new_impl_bytes(bytes: &[u8]) -> Result<CString, NulError> {
|
|
|
|
|
// We cannot have such large slice that we would overflow here
|
|
|
|
|
// but using `checked_add` allows LLVM to assume that capacity never overflows
|
|
|
|
|
// and generate twice shorter code.
|
|
|
|
|
// `saturating_add` doesn't help for some reason.
|
|
|
|
|
let capacity = bytes.len().checked_add(1).unwrap();
|
|
|
|
|
|
|
|
|
|
// Allocate before validation to avoid duplication of allocation code.
|
|
|
|
|
// We still need to allocate and copy memory even if we get an error.
|
|
|
|
|
let mut buffer = Vec::with_capacity(capacity);
|
|
|
|
|
buffer.extend(bytes);
|
|
|
|
|
|
|
|
|
|
// Check memory of self instead of new buffer.
|
|
|
|
|
// This allows better optimizations if lto enabled.
|
|
|
|
|
match memchr::memchr(0, bytes) {
|
|
|
|
|
Some(i) => Err(NulError(i, buffer)),
|
2022-02-13 23:04:11 +00:00
|
|
|
|
None => Ok(unsafe { CString::_from_vec_unchecked(buffer) }),
|
2019-10-18 07:10:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2021-12-20 12:57:47 +00:00
|
|
|
|
|
|
|
|
|
impl SpecNewImpl for &'_ [u8] {
|
|
|
|
|
fn spec_new_impl(self) -> Result<CString, NulError> {
|
|
|
|
|
spec_new_impl_bytes(self)
|
2019-10-18 07:10:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-20 12:57:47 +00:00
|
|
|
|
impl SpecNewImpl for &'_ str {
|
|
|
|
|
fn spec_new_impl(self) -> Result<CString, NulError> {
|
|
|
|
|
spec_new_impl_bytes(self.as_bytes())
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-09-09 19:37:59 +00:00
|
|
|
|
|
2021-12-20 12:57:47 +00:00
|
|
|
|
impl SpecNewImpl for &'_ mut [u8] {
|
|
|
|
|
fn spec_new_impl(self) -> Result<CString, NulError> {
|
|
|
|
|
spec_new_impl_bytes(self)
|
|
|
|
|
}
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
2021-12-20 12:57:47 +00:00
|
|
|
|
|
|
|
|
|
t.spec_new_impl()
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// Creates a C-compatible string by consuming a byte vector,
|
|
|
|
|
/// without checking for interior 0 bytes.
|
2014-11-25 21:28:35 +00:00
|
|
|
|
///
|
2021-09-28 00:51:52 +00:00
|
|
|
|
/// Trailing 0 byte will be appended by this function.
|
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// This method is equivalent to [`CString::new`] except that no runtime
|
|
|
|
|
/// assertion is made that `v` contains no 0 bytes, and it requires an
|
|
|
|
|
/// actual byte vector, not anything that can be converted to one with Into.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2016-08-12 13:08:37 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
|
|
|
|
/// let raw = b"foo".to_vec();
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// let c_string = CString::from_vec_unchecked(raw);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2021-10-10 22:22:40 +00:00
|
|
|
|
#[must_use]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-02-13 23:04:11 +00:00
|
|
|
|
pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> Self {
|
|
|
|
|
debug_assert!(memchr::memchr(0, &v).is_none());
|
|
|
|
|
unsafe { Self::_from_vec_unchecked(v) }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
unsafe fn _from_vec_unchecked(mut v: Vec<u8>) -> Self {
|
2016-08-21 11:33:28 +00:00
|
|
|
|
v.reserve_exact(1);
|
2014-11-25 21:28:35 +00:00
|
|
|
|
v.push(0);
|
2022-02-13 23:04:11 +00:00
|
|
|
|
Self { inner: v.into_boxed_slice() }
|
2014-11-25 21:28:35 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// Retakes ownership of a `CString` that was transferred to C via
|
|
|
|
|
/// [`CString::into_raw`].
|
2015-08-14 17:29:47 +00:00
|
|
|
|
///
|
2016-08-26 17:17:45 +00:00
|
|
|
|
/// Additionally, the length of the string will be recalculated from the pointer.
|
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2016-01-24 22:41:44 +00:00
|
|
|
|
/// This should only ever be called with a pointer that was earlier
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// obtained by calling [`CString::into_raw`]. Other usage (e.g., trying to take
|
2016-08-26 17:17:45 +00:00
|
|
|
|
/// ownership of a string that was allocated by foreign code) is likely to lead
|
|
|
|
|
/// to undefined behavior or allocator corruption.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2020-06-03 21:32:26 +00:00
|
|
|
|
/// It should be noted that the length isn't just "recomputed," but that
|
|
|
|
|
/// the recomputed length must match the original length from the
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// [`CString::into_raw`] call. This means the [`CString::into_raw`]/`from_raw`
|
|
|
|
|
/// methods should not be used when passing the string to C functions that can
|
2020-06-03 21:32:26 +00:00
|
|
|
|
/// modify the string's length.
|
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// > **Note:** If you need to borrow a string that was allocated by
|
2017-10-11 22:53:13 +00:00
|
|
|
|
/// > foreign code, use [`CStr`]. If you need to take ownership of
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// > a string that was allocated by foreign code, you will need to
|
|
|
|
|
/// > make your own provisions for freeing it appropriately, likely
|
|
|
|
|
/// > with the foreign code's API to do that.
|
|
|
|
|
///
|
2017-06-19 01:22:54 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
2019-02-09 22:16:58 +00:00
|
|
|
|
/// Creates a `CString`, pass ownership to an `extern` function (via raw pointer), then retake
|
2017-06-19 01:22:54 +00:00
|
|
|
|
/// ownership with `from_raw`:
|
|
|
|
|
///
|
2018-02-18 14:30:10 +00:00
|
|
|
|
/// ```ignore (extern-declaration)
|
2017-06-19 01:22:54 +00:00
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
/// use std::os::raw::c_char;
|
|
|
|
|
///
|
2020-09-01 21:12:52 +00:00
|
|
|
|
/// extern "C" {
|
2017-06-19 01:22:54 +00:00
|
|
|
|
/// fn some_extern_function(s: *mut c_char);
|
|
|
|
|
/// }
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new("Hello!").expect("CString::new failed");
|
2017-06-19 01:22:54 +00:00
|
|
|
|
/// let raw = c_string.into_raw();
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// some_extern_function(raw);
|
|
|
|
|
/// let c_string = CString::from_raw(raw);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2021-10-10 22:22:40 +00:00
|
|
|
|
#[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
|
2015-09-10 20:26:44 +00:00
|
|
|
|
#[stable(feature = "cstr_memory", since = "1.4.0")]
|
2015-11-11 17:02:55 +00:00
|
|
|
|
pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
|
2020-08-14 17:33:04 +00:00
|
|
|
|
// SAFETY: This is called with a pointer that was obtained from a call
|
|
|
|
|
// to `CString::into_raw` and the length has not been modified. As such,
|
|
|
|
|
// we know there is a NUL byte (and only one) at the end and that the
|
|
|
|
|
// information about the size of the allocation is correct on Rust's
|
|
|
|
|
// side.
|
|
|
|
|
unsafe {
|
2022-02-16 11:23:37 +00:00
|
|
|
|
extern "C" {
|
|
|
|
|
/// Provided by libc or compiler_builtins.
|
|
|
|
|
fn strlen(s: *const c_char) -> usize;
|
|
|
|
|
}
|
|
|
|
|
let len = strlen(ptr) + 1; // Including the NUL byte
|
2020-08-14 17:33:04 +00:00
|
|
|
|
let slice = slice::from_raw_parts_mut(ptr, len as usize);
|
|
|
|
|
CString { inner: Box::from_raw(slice as *mut [c_char] as *mut [u8]) }
|
|
|
|
|
}
|
2015-05-25 16:37:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// Consumes the `CString` and transfers ownership of the string to a C caller.
|
2015-05-25 16:37:45 +00:00
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// The pointer which this function returns must be returned to Rust and reconstituted using
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// [`CString::from_raw`] to be properly deallocated. Specifically, one
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// should *not* use the standard C `free()` function to deallocate
|
2015-05-25 16:37:45 +00:00
|
|
|
|
/// this string.
|
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// Failure to call [`CString::from_raw`] will lead to a memory leak.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2020-06-03 21:55:41 +00:00
|
|
|
|
/// The C side must **not** modify the length of the string (by writing a
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// `null` somewhere inside the string or removing the final one) before
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// it makes it back into Rust using [`CString::from_raw`]. See the safety section
|
|
|
|
|
/// in [`CString::from_raw`].
|
2017-06-06 03:42:13 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new("foo").expect("CString::new failed");
|
2017-06-06 03:42:13 +00:00
|
|
|
|
///
|
|
|
|
|
/// let ptr = c_string.into_raw();
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// assert_eq!(b'f', *ptr as u8);
|
2022-08-19 09:33:46 +00:00
|
|
|
|
/// assert_eq!(b'o', *ptr.add(1) as u8);
|
|
|
|
|
/// assert_eq!(b'o', *ptr.add(2) as u8);
|
|
|
|
|
/// assert_eq!(b'\0', *ptr.add(3) as u8);
|
2017-06-06 03:42:13 +00:00
|
|
|
|
///
|
|
|
|
|
/// // retake pointer to free memory
|
|
|
|
|
/// let _ = CString::from_raw(ptr);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2021-10-10 23:50:52 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2015-09-10 20:26:44 +00:00
|
|
|
|
#[stable(feature = "cstr_memory", since = "1.4.0")]
|
2015-11-11 17:02:55 +00:00
|
|
|
|
pub fn into_raw(self) -> *mut c_char {
|
2016-09-04 15:37:30 +00:00
|
|
|
|
Box::into_raw(self.into_inner()) as *mut c_char
|
2015-05-25 16:37:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-10-02 18:53:50 +00:00
|
|
|
|
/// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
|
2015-10-11 23:49:57 +00:00
|
|
|
|
///
|
|
|
|
|
/// On failure, ownership of the original `CString` is returned.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
|
|
|
|
/// let valid_utf8 = vec![b'f', b'o', b'o'];
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let cstring = CString::new(valid_utf8).expect("CString::new failed");
|
|
|
|
|
/// assert_eq!(cstring.into_string().expect("into_string() call failed"), "foo");
|
2017-09-23 01:36:44 +00:00
|
|
|
|
///
|
|
|
|
|
/// let invalid_utf8 = vec![b'f', 0xff, b'o', b'o'];
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let cstring = CString::new(invalid_utf8).expect("CString::new failed");
|
|
|
|
|
/// let err = cstring.into_string().err().expect("into_string().err() failed");
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// assert_eq!(err.utf8_error().valid_up_to(), 1);
|
|
|
|
|
/// ```
|
2016-01-15 18:07:52 +00:00
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
2015-10-11 23:49:57 +00:00
|
|
|
|
pub fn into_string(self) -> Result<String, IntoStringError> {
|
|
|
|
|
String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
|
|
|
|
|
error: e.utf8_error(),
|
2022-02-13 23:04:11 +00:00
|
|
|
|
inner: unsafe { Self::_from_vec_unchecked(e.into_bytes()) },
|
2015-10-11 23:49:57 +00:00
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// Consumes the `CString` and returns the underlying byte buffer.
|
2015-10-11 23:49:57 +00:00
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// The returned buffer does **not** contain the trailing nul
|
|
|
|
|
/// terminator, and it is guaranteed to not have any interior nul
|
|
|
|
|
/// bytes.
|
2017-06-06 03:46:44 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new("foo").expect("CString::new failed");
|
2017-06-06 03:46:44 +00:00
|
|
|
|
/// let bytes = c_string.into_bytes();
|
|
|
|
|
/// assert_eq!(bytes, vec![b'f', b'o', b'o']);
|
|
|
|
|
/// ```
|
2021-10-10 23:50:52 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2016-01-15 18:07:52 +00:00
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
2015-10-11 23:49:57 +00:00
|
|
|
|
pub fn into_bytes(self) -> Vec<u8> {
|
2022-02-16 11:23:37 +00:00
|
|
|
|
let mut vec = into_vec(self.into_inner());
|
2015-10-11 23:49:57 +00:00
|
|
|
|
let _nul = vec.pop();
|
|
|
|
|
debug_assert_eq!(_nul, Some(0u8));
|
|
|
|
|
vec
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-14 17:08:09 +00:00
|
|
|
|
/// Equivalent to [`CString::into_bytes()`] except that the
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// returned vector includes the trailing nul terminator.
|
2017-06-06 03:48:13 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new("foo").expect("CString::new failed");
|
2017-06-06 03:48:13 +00:00
|
|
|
|
/// let bytes = c_string.into_bytes_with_nul();
|
|
|
|
|
/// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
|
|
|
|
|
/// ```
|
2021-10-10 23:50:52 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2016-01-15 18:07:52 +00:00
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
2015-10-11 23:49:57 +00:00
|
|
|
|
pub fn into_bytes_with_nul(self) -> Vec<u8> {
|
2022-02-16 11:23:37 +00:00
|
|
|
|
into_vec(self.into_inner())
|
2015-10-11 23:49:57 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// Returns the contents of this `CString` as a slice of bytes.
|
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// The returned slice does **not** contain the trailing nul
|
|
|
|
|
/// terminator, and it is guaranteed to not have any interior nul
|
2017-10-11 22:53:13 +00:00
|
|
|
|
/// bytes. If you need the nul terminator, use
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// [`CString::as_bytes_with_nul`] instead.
|
2017-06-06 03:50:49 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new("foo").expect("CString::new failed");
|
2017-06-06 03:50:49 +00:00
|
|
|
|
/// let bytes = c_string.as_bytes();
|
|
|
|
|
/// assert_eq!(bytes, &[b'f', b'o', b'o']);
|
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2021-10-11 17:57:38 +00:00
|
|
|
|
#[must_use]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-11-25 21:28:35 +00:00
|
|
|
|
pub fn as_bytes(&self) -> &[u8] {
|
2021-03-28 16:55:09 +00:00
|
|
|
|
// SAFETY: CString has a length at least 1
|
|
|
|
|
unsafe { self.inner.get_unchecked(..self.inner.len() - 1) }
|
2014-11-25 21:28:35 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-14 17:08:09 +00:00
|
|
|
|
/// Equivalent to [`CString::as_bytes()`] except that the
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// returned slice includes the trailing nul terminator.
|
2017-06-06 03:49:52 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new("foo").expect("CString::new failed");
|
2017-06-06 03:49:52 +00:00
|
|
|
|
/// let bytes = c_string.as_bytes_with_nul();
|
|
|
|
|
/// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
|
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2021-10-11 17:57:38 +00:00
|
|
|
|
#[must_use]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-11-25 21:28:35 +00:00
|
|
|
|
pub fn as_bytes_with_nul(&self) -> &[u8] {
|
2015-02-18 06:47:40 +00:00
|
|
|
|
&self.inner
|
2014-11-25 21:28:35 +00:00
|
|
|
|
}
|
2016-09-04 15:37:30 +00:00
|
|
|
|
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// Extracts a [`CStr`] slice containing the entire string.
|
|
|
|
|
///
|
2017-06-18 23:05:00 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::{CString, CStr};
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = c_string.as_c_str();
|
|
|
|
|
/// assert_eq!(cstr,
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
|
2017-06-18 23:05:00 +00:00
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2021-10-11 17:57:38 +00:00
|
|
|
|
#[must_use]
|
2017-07-20 22:44:35 +00:00
|
|
|
|
#[stable(feature = "as_c_str", since = "1.20.0")]
|
2017-04-05 21:13:46 +00:00
|
|
|
|
pub fn as_c_str(&self) -> &CStr {
|
|
|
|
|
&*self
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// Converts this `CString` into a boxed [`CStr`].
|
|
|
|
|
///
|
2017-06-18 22:45:00 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::{CString, CStr};
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
|
2017-06-18 22:45:00 +00:00
|
|
|
|
/// let boxed = c_string.into_boxed_c_str();
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// assert_eq!(&*boxed,
|
|
|
|
|
/// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
|
2017-06-18 22:45:00 +00:00
|
|
|
|
/// ```
|
2021-10-10 23:50:52 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2017-07-20 22:44:35 +00:00
|
|
|
|
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
|
2017-02-01 03:46:16 +00:00
|
|
|
|
pub fn into_boxed_c_str(self) -> Box<CStr> {
|
2017-09-28 04:51:38 +00:00
|
|
|
|
unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
|
2017-02-01 03:46:16 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// Bypass "move out of struct which implements [`Drop`] trait" restriction.
|
2021-05-26 10:12:54 +00:00
|
|
|
|
#[inline]
|
2016-09-04 15:37:30 +00:00
|
|
|
|
fn into_inner(self) -> Box<[u8]> {
|
2019-07-12 07:30:58 +00:00
|
|
|
|
// Rationale: `mem::forget(self)` invalidates the previous call to `ptr::read(&self.inner)`
|
|
|
|
|
// so we use `ManuallyDrop` to ensure `self` is not dropped.
|
|
|
|
|
// Then we can return the box directly without invalidating it.
|
|
|
|
|
// See https://github.com/rust-lang/rust/issues/62553.
|
|
|
|
|
let this = mem::ManuallyDrop::new(self);
|
|
|
|
|
unsafe { ptr::read(&this.inner) }
|
2016-09-04 15:37:30 +00:00
|
|
|
|
}
|
2020-06-08 16:31:45 +00:00
|
|
|
|
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Converts a <code>[Vec]<[u8]></code> to a [`CString`] without checking the
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// invariants on the given [`Vec`].
|
2020-06-08 16:31:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// The given [`Vec`] **must** have one nul byte as its last element.
|
2020-06-08 16:31:45 +00:00
|
|
|
|
/// This means it cannot be empty nor have any other nul byte anywhere else.
|
|
|
|
|
///
|
|
|
|
|
/// # Example
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
/// assert_eq!(
|
|
|
|
|
/// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
|
|
|
|
|
/// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
|
|
|
|
|
/// );
|
|
|
|
|
/// ```
|
2021-10-10 22:22:40 +00:00
|
|
|
|
#[must_use]
|
2021-09-26 21:38:51 +00:00
|
|
|
|
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
|
2020-06-08 16:31:45 +00:00
|
|
|
|
pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
|
2022-02-13 23:04:11 +00:00
|
|
|
|
debug_assert!(memchr::memchr(0, &v).unwrap() + 1 == v.len());
|
|
|
|
|
unsafe { Self::_from_vec_with_nul_unchecked(v) }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
unsafe fn _from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
|
2020-06-08 16:31:45 +00:00
|
|
|
|
Self { inner: v.into_boxed_slice() }
|
|
|
|
|
}
|
|
|
|
|
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Attempts to converts a <code>[Vec]<[u8]></code> to a [`CString`].
|
2020-06-08 16:31:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// Runtime checks are present to ensure there is only one nul byte in the
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// [`Vec`], its last element.
|
2020-06-08 16:31:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Errors
|
|
|
|
|
///
|
|
|
|
|
/// If a nul byte is present and not the last element or no nul bytes
|
|
|
|
|
/// is present, an error will be returned.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// A successful conversion will produce the same result as [`CString::new`]
|
|
|
|
|
/// when called without the ending nul byte.
|
2020-06-08 16:31:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
/// assert_eq!(
|
|
|
|
|
/// CString::from_vec_with_nul(b"abc\0".to_vec())
|
|
|
|
|
/// .expect("CString::from_vec_with_nul failed"),
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// CString::new(b"abc".to_vec()).expect("CString::new failed")
|
2020-06-08 16:31:45 +00:00
|
|
|
|
/// );
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
2021-08-22 12:46:15 +00:00
|
|
|
|
/// An incorrectly formatted [`Vec`] will produce an error.
|
2020-06-08 16:31:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// use std::ffi::{CString, FromVecWithNulError};
|
2020-06-08 16:31:45 +00:00
|
|
|
|
/// // Interior nul byte
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
|
2020-06-08 16:31:45 +00:00
|
|
|
|
/// // No nul byte
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
|
2020-06-08 16:31:45 +00:00
|
|
|
|
/// ```
|
2021-09-26 21:38:51 +00:00
|
|
|
|
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
|
2020-06-14 21:22:36 +00:00
|
|
|
|
pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> {
|
2020-06-08 16:31:45 +00:00
|
|
|
|
let nul_pos = memchr::memchr(0, &v);
|
|
|
|
|
match nul_pos {
|
|
|
|
|
Some(nul_pos) if nul_pos + 1 == v.len() => {
|
|
|
|
|
// SAFETY: We know there is only one nul byte, at the end
|
|
|
|
|
// of the vec.
|
2022-02-13 23:04:11 +00:00
|
|
|
|
Ok(unsafe { Self::_from_vec_with_nul_unchecked(v) })
|
2020-06-08 16:31:45 +00:00
|
|
|
|
}
|
2020-06-14 21:22:36 +00:00
|
|
|
|
Some(nul_pos) => Err(FromVecWithNulError {
|
|
|
|
|
error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos),
|
|
|
|
|
bytes: v,
|
|
|
|
|
}),
|
|
|
|
|
None => Err(FromVecWithNulError {
|
|
|
|
|
error_kind: FromBytesWithNulErrorKind::NotNulTerminated,
|
|
|
|
|
bytes: v,
|
|
|
|
|
}),
|
2020-06-08 16:31:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2016-09-04 15:37:30 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Turns this `CString` into an empty string to prevent
|
2019-09-05 16:15:28 +00:00
|
|
|
|
// memory-unsafe code from working by accident. Inline
|
2016-09-26 12:22:22 +00:00
|
|
|
|
// to prevent LLVM from optimizing it away in debug builds.
|
2016-09-04 15:37:30 +00:00
|
|
|
|
#[stable(feature = "cstring_drop", since = "1.13.0")]
|
|
|
|
|
impl Drop for CString {
|
2016-09-26 12:22:22 +00:00
|
|
|
|
#[inline]
|
2016-09-04 15:37:30 +00:00
|
|
|
|
fn drop(&mut self) {
|
|
|
|
|
unsafe {
|
|
|
|
|
*self.inner.get_unchecked_mut(0) = 0;
|
|
|
|
|
}
|
|
|
|
|
}
|
2014-11-25 21:28:35 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-12-29 18:02:08 +00:00
|
|
|
|
impl ops::Deref for CString {
|
2015-02-18 06:47:40 +00:00
|
|
|
|
type Target = CStr;
|
2014-11-25 21:28:35 +00:00
|
|
|
|
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
fn deref(&self) -> &CStr {
|
2022-02-16 11:23:37 +00:00
|
|
|
|
unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
|
2014-11-25 21:28:35 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-01-24 17:15:42 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-01-20 23:45:07 +00:00
|
|
|
|
impl fmt::Debug for CString {
|
2019-03-01 08:34:11 +00:00
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-07-11 20:55:52 +00:00
|
|
|
|
fmt::Debug::fmt(&**self, f)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-01-15 18:07:52 +00:00
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
|
|
|
|
impl From<CString> for Vec<u8> {
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
|
2018-07-23 13:38:15 +00:00
|
|
|
|
///
|
2018-07-11 11:32:03 +00:00
|
|
|
|
/// The conversion consumes the [`CString`], and removes the terminating NUL byte.
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2016-01-15 18:07:52 +00:00
|
|
|
|
fn from(s: CString) -> Vec<u8> {
|
|
|
|
|
s.into_bytes()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-15 15:58:59 +00:00
|
|
|
|
#[stable(feature = "cstr_default", since = "1.10.0")]
|
|
|
|
|
impl Default for CString {
|
2016-09-11 17:28:01 +00:00
|
|
|
|
/// Creates an empty `CString`.
|
2016-04-15 15:58:59 +00:00
|
|
|
|
fn default() -> CString {
|
|
|
|
|
let a: &CStr = Default::default();
|
|
|
|
|
a.to_owned()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-07-09 23:38:55 +00:00
|
|
|
|
#[stable(feature = "cstr_borrow", since = "1.3.0")]
|
|
|
|
|
impl Borrow<CStr> for CString {
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2015-07-09 23:38:55 +00:00
|
|
|
|
fn borrow(&self) -> &CStr {
|
|
|
|
|
self
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-05-09 06:32:50 +00:00
|
|
|
|
#[stable(feature = "cstring_from_cow_cstr", since = "1.28.0")]
|
2018-04-27 19:27:38 +00:00
|
|
|
|
impl<'a> From<Cow<'a, CStr>> for CString {
|
2021-10-13 15:46:34 +00:00
|
|
|
|
/// Converts a `Cow<'a, CStr>` into a `CString`, by copying the contents if they are
|
|
|
|
|
/// borrowed.
|
2018-04-27 19:27:38 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: Cow<'a, CStr>) -> Self {
|
|
|
|
|
s.into_owned()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[cfg(not(test))]
|
2017-02-01 03:46:16 +00:00
|
|
|
|
#[stable(feature = "box_from_c_str", since = "1.17.0")]
|
2019-03-10 03:10:28 +00:00
|
|
|
|
impl From<&CStr> for Box<CStr> {
|
2021-10-13 15:46:34 +00:00
|
|
|
|
/// Converts a `&CStr` into a `Box<CStr>`,
|
|
|
|
|
/// by copying the contents into a newly allocated [`Box`].
|
2019-03-10 03:10:28 +00:00
|
|
|
|
fn from(s: &CStr) -> Box<CStr> {
|
2017-02-01 03:46:16 +00:00
|
|
|
|
let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
|
2017-09-28 04:51:38 +00:00
|
|
|
|
unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
|
2017-02-01 03:46:16 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-22 20:03:05 +00:00
|
|
|
|
#[stable(feature = "box_from_cow", since = "1.45.0")]
|
|
|
|
|
impl From<Cow<'_, CStr>> for Box<CStr> {
|
2021-10-13 15:46:34 +00:00
|
|
|
|
/// Converts a `Cow<'a, CStr>` into a `Box<CStr>`,
|
|
|
|
|
/// by copying the contents if they are borrowed.
|
2020-04-22 20:03:05 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(cow: Cow<'_, CStr>) -> Box<CStr> {
|
|
|
|
|
match cow {
|
|
|
|
|
Cow::Borrowed(s) => Box::from(s),
|
|
|
|
|
Cow::Owned(s) => Box::from(s),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-20 07:38:39 +00:00
|
|
|
|
#[stable(feature = "c_string_from_box", since = "1.18.0")]
|
2017-02-14 01:37:42 +00:00
|
|
|
|
impl From<Box<CStr>> for CString {
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2017-02-14 01:37:42 +00:00
|
|
|
|
fn from(s: Box<CStr>) -> CString {
|
2022-02-16 11:23:37 +00:00
|
|
|
|
let raw = Box::into_raw(s) as *mut [u8];
|
|
|
|
|
CString { inner: unsafe { Box::from_raw(raw) } }
|
2017-02-14 01:37:42 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-01 15:23:20 +00:00
|
|
|
|
#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
|
|
|
|
|
impl From<Vec<NonZeroU8>> for CString {
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Converts a <code>[Vec]<[NonZeroU8]></code> into a [`CString`] without
|
2019-09-01 15:23:20 +00:00
|
|
|
|
/// copying nor checking for inner null bytes.
|
|
|
|
|
#[inline]
|
|
|
|
|
fn from(v: Vec<NonZeroU8>) -> CString {
|
|
|
|
|
unsafe {
|
|
|
|
|
// Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
|
|
|
|
|
let v: Vec<u8> = {
|
2020-09-09 02:26:44 +00:00
|
|
|
|
// SAFETY:
|
2019-09-01 15:23:20 +00:00
|
|
|
|
// - transmuting between `NonZeroU8` and `u8` is sound;
|
|
|
|
|
// - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
|
|
|
|
|
let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
|
|
|
|
|
Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
|
|
|
|
|
};
|
2020-09-09 02:26:44 +00:00
|
|
|
|
// SAFETY: `v` cannot contain null bytes, given the type-level
|
2019-09-01 15:23:20 +00:00
|
|
|
|
// invariant of `NonZeroU8`.
|
2022-02-13 23:04:11 +00:00
|
|
|
|
Self::_from_vec_unchecked(v)
|
2019-09-01 15:23:20 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[cfg(not(test))]
|
2018-06-29 18:49:32 +00:00
|
|
|
|
#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
|
|
|
|
|
impl Clone for Box<CStr> {
|
|
|
|
|
#[inline]
|
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
|
(**self).into()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-12 23:08:37 +00:00
|
|
|
|
#[stable(feature = "box_from_c_string", since = "1.20.0")]
|
2017-05-20 19:40:53 +00:00
|
|
|
|
impl From<CString> for Box<CStr> {
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Converts a [`CString`] into a <code>[Box]<[CStr]></code> without copying or allocating.
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2017-05-20 19:40:53 +00:00
|
|
|
|
fn from(s: CString) -> Box<CStr> {
|
|
|
|
|
s.into_boxed_c_str()
|
2017-02-14 01:37:42 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-05-09 06:23:02 +00:00
|
|
|
|
#[stable(feature = "cow_from_cstr", since = "1.28.0")]
|
2018-04-22 21:57:52 +00:00
|
|
|
|
impl<'a> From<CString> for Cow<'a, CStr> {
|
2021-09-15 16:14:20 +00:00
|
|
|
|
/// Converts a [`CString`] into an owned [`Cow`] without copying or allocating.
|
2018-04-22 21:57:52 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: CString) -> Cow<'a, CStr> {
|
|
|
|
|
Cow::Owned(s)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-05-09 06:23:02 +00:00
|
|
|
|
#[stable(feature = "cow_from_cstr", since = "1.28.0")]
|
2018-04-22 21:57:52 +00:00
|
|
|
|
impl<'a> From<&'a CStr> for Cow<'a, CStr> {
|
2021-09-15 16:14:20 +00:00
|
|
|
|
/// Converts a [`CStr`] into a borrowed [`Cow`] without copying or allocating.
|
2018-04-22 21:57:52 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: &'a CStr) -> Cow<'a, CStr> {
|
|
|
|
|
Cow::Borrowed(s)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-05-09 06:23:02 +00:00
|
|
|
|
#[stable(feature = "cow_from_cstr", since = "1.28.0")]
|
2018-04-22 21:57:52 +00:00
|
|
|
|
impl<'a> From<&'a CString> for Cow<'a, CStr> {
|
2021-09-15 16:14:20 +00:00
|
|
|
|
/// Converts a `&`[`CString`] into a borrowed [`Cow`] without copying or allocating.
|
2018-04-22 21:57:52 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: &'a CString) -> Cow<'a, CStr> {
|
|
|
|
|
Cow::Borrowed(s.as_c_str())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-13 13:35:40 +00:00
|
|
|
|
#[cfg(target_has_atomic = "ptr")]
|
2017-12-27 14:11:05 +00:00
|
|
|
|
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
|
2017-11-14 19:31:07 +00:00
|
|
|
|
impl From<CString> for Arc<CStr> {
|
2022-01-20 09:54:03 +00:00
|
|
|
|
/// Converts a [`CString`] into an <code>[Arc]<[CStr]></code> by moving the [`CString`]
|
|
|
|
|
/// data into a new [`Arc`] buffer.
|
2017-11-14 19:31:07 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: CString) -> Arc<CStr> {
|
|
|
|
|
let arc: Arc<[u8]> = Arc::from(s.into_inner());
|
|
|
|
|
unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-13 13:35:40 +00:00
|
|
|
|
#[cfg(target_has_atomic = "ptr")]
|
2017-12-27 14:11:05 +00:00
|
|
|
|
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
|
2019-03-10 03:10:28 +00:00
|
|
|
|
impl From<&CStr> for Arc<CStr> {
|
2021-10-13 15:46:34 +00:00
|
|
|
|
/// Converts a `&CStr` into a `Arc<CStr>`,
|
|
|
|
|
/// by copying the contents into a newly allocated [`Arc`].
|
2017-11-14 19:31:07 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: &CStr) -> Arc<CStr> {
|
|
|
|
|
let arc: Arc<[u8]> = Arc::from(s.to_bytes_with_nul());
|
|
|
|
|
unsafe { Arc::from_raw(Arc::into_raw(arc) as *const CStr) }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-12-27 14:11:05 +00:00
|
|
|
|
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
|
2017-11-14 19:31:07 +00:00
|
|
|
|
impl From<CString> for Rc<CStr> {
|
2022-01-20 09:54:03 +00:00
|
|
|
|
/// Converts a [`CString`] into an <code>[Rc]<[CStr]></code> by moving the [`CString`]
|
|
|
|
|
/// data into a new [`Arc`] buffer.
|
2017-11-14 19:31:07 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: CString) -> Rc<CStr> {
|
|
|
|
|
let rc: Rc<[u8]> = Rc::from(s.into_inner());
|
|
|
|
|
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-12-27 14:11:05 +00:00
|
|
|
|
#[stable(feature = "shared_from_slice2", since = "1.24.0")]
|
2019-03-10 03:10:28 +00:00
|
|
|
|
impl From<&CStr> for Rc<CStr> {
|
2021-10-13 15:46:34 +00:00
|
|
|
|
/// Converts a `&CStr` into a `Rc<CStr>`,
|
|
|
|
|
/// by copying the contents into a newly allocated [`Rc`].
|
2017-11-14 19:31:07 +00:00
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: &CStr) -> Rc<CStr> {
|
|
|
|
|
let rc: Rc<[u8]> = Rc::from(s.to_bytes_with_nul());
|
|
|
|
|
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const CStr) }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[cfg(not(test))]
|
2017-02-01 03:46:16 +00:00
|
|
|
|
#[stable(feature = "default_box_extra", since = "1.17.0")]
|
|
|
|
|
impl Default for Box<CStr> {
|
|
|
|
|
fn default() -> Box<CStr> {
|
|
|
|
|
let boxed: Box<[u8]> = Box::from([0]);
|
2017-09-28 04:51:38 +00:00
|
|
|
|
unsafe { Box::from_raw(Box::into_raw(boxed) as *mut CStr) }
|
2017-02-01 03:46:16 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl NulError {
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// Returns the position of the nul byte in the slice that caused
|
|
|
|
|
/// [`CString::new`] to fail.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2016-08-02 12:49:05 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
|
|
|
|
/// let nul_error = CString::new("foo\0bar").unwrap_err();
|
|
|
|
|
/// assert_eq!(nul_error.nul_position(), 3);
|
|
|
|
|
///
|
|
|
|
|
/// let nul_error = CString::new("foo bar\0").unwrap_err();
|
|
|
|
|
/// assert_eq!(nul_error.nul_position(), 7);
|
|
|
|
|
/// ```
|
2021-10-31 02:58:27 +00:00
|
|
|
|
#[must_use]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
pub fn nul_position(&self) -> usize {
|
|
|
|
|
self.0
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Consumes this error, returning the underlying vector of bytes which
|
|
|
|
|
/// generated the error in the first place.
|
2016-08-06 21:50:37 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
|
|
|
|
/// let nul_error = CString::new("foo\0bar").unwrap_err();
|
|
|
|
|
/// assert_eq!(nul_error.into_vec(), b"foo\0bar");
|
|
|
|
|
/// ```
|
2021-10-10 23:50:52 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
pub fn into_vec(self) -> Vec<u8> {
|
|
|
|
|
self.1
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl fmt::Display for NulError {
|
2019-03-01 08:34:11 +00:00
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-02-18 06:47:40 +00:00
|
|
|
|
write!(f, "nul byte found in provided data at position: {}", self.0)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-26 21:38:51 +00:00
|
|
|
|
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
|
2020-06-14 21:21:40 +00:00
|
|
|
|
impl fmt::Display for FromVecWithNulError {
|
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
|
match self.error_kind {
|
|
|
|
|
FromBytesWithNulErrorKind::InteriorNul(pos) => {
|
2022-02-12 19:16:17 +00:00
|
|
|
|
write!(f, "data provided contains an interior nul byte at pos {pos}")
|
2020-06-14 21:21:40 +00:00
|
|
|
|
}
|
|
|
|
|
FromBytesWithNulErrorKind::NotNulTerminated => {
|
|
|
|
|
write!(f, "data provided is not nul terminated")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-10-11 23:49:57 +00:00
|
|
|
|
impl IntoStringError {
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// Consumes this error, returning original [`CString`] which generated the
|
2015-10-11 23:49:57 +00:00
|
|
|
|
/// error.
|
2021-10-10 23:50:52 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2016-01-15 18:07:52 +00:00
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
2015-10-11 23:49:57 +00:00
|
|
|
|
pub fn into_cstring(self) -> CString {
|
|
|
|
|
self.inner
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Access the underlying UTF-8 error that was the cause of this error.
|
2021-10-31 02:58:27 +00:00
|
|
|
|
#[must_use]
|
2016-01-15 18:07:52 +00:00
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
2015-10-11 23:49:57 +00:00
|
|
|
|
pub fn utf8_error(&self) -> Utf8Error {
|
|
|
|
|
self.error
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
impl IntoStringError {
|
2015-10-11 23:49:57 +00:00
|
|
|
|
fn description(&self) -> &str {
|
2016-01-15 18:07:52 +00:00
|
|
|
|
"C string contained non-utf8 bytes"
|
|
|
|
|
}
|
2015-10-11 23:49:57 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-01-15 18:07:52 +00:00
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
2015-10-11 23:49:57 +00:00
|
|
|
|
impl fmt::Display for IntoStringError {
|
2019-12-01 04:01:48 +00:00
|
|
|
|
#[allow(deprecated, deprecated_in_future)]
|
2019-03-01 08:34:11 +00:00
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2016-01-15 18:07:52 +00:00
|
|
|
|
self.description().fmt(f)
|
2015-10-11 23:49:57 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[stable(feature = "cstr_borrow", since = "1.3.0")]
|
|
|
|
|
impl ToOwned for CStr {
|
|
|
|
|
type Owned = CString;
|
2015-02-18 06:47:40 +00:00
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
fn to_owned(&self) -> CString {
|
|
|
|
|
CString { inner: self.to_bytes_with_nul().into() }
|
2022-03-15 23:47:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
fn clone_into(&self, target: &mut CString) {
|
|
|
|
|
let mut b = into_vec(mem::take(&mut target.inner));
|
|
|
|
|
self.to_bytes_with_nul().clone_into(&mut b);
|
|
|
|
|
target.inner = b.into_boxed_slice();
|
2015-12-29 18:41:43 +00:00
|
|
|
|
}
|
2022-02-16 11:23:37 +00:00
|
|
|
|
}
|
2015-12-29 18:41:43 +00:00
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[stable(feature = "cstring_asref", since = "1.7.0")]
|
|
|
|
|
impl From<&CStr> for CString {
|
|
|
|
|
fn from(s: &CStr) -> CString {
|
|
|
|
|
s.to_owned()
|
2022-02-13 23:04:11 +00:00
|
|
|
|
}
|
2022-02-16 11:23:37 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[stable(feature = "cstring_asref", since = "1.7.0")]
|
|
|
|
|
impl ops::Index<ops::RangeFull> for CString {
|
|
|
|
|
type Output = CStr;
|
2022-02-13 23:04:11 +00:00
|
|
|
|
|
|
|
|
|
#[inline]
|
2022-02-16 11:23:37 +00:00
|
|
|
|
fn index(&self, _index: ops::RangeFull) -> &CStr {
|
|
|
|
|
self
|
2015-12-29 18:41:43 +00:00
|
|
|
|
}
|
2022-02-16 11:23:37 +00:00
|
|
|
|
}
|
2015-12-29 18:41:43 +00:00
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[stable(feature = "cstring_asref", since = "1.7.0")]
|
|
|
|
|
impl AsRef<CStr> for CString {
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2022-02-16 11:23:37 +00:00
|
|
|
|
fn as_ref(&self) -> &CStr {
|
|
|
|
|
self
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
2022-02-16 11:23:37 +00:00
|
|
|
|
}
|
2015-02-18 06:47:40 +00:00
|
|
|
|
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[cfg(not(test))]
|
|
|
|
|
impl CStr {
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Converts a `CStr` into a <code>[Cow]<[str]></code>.
|
2015-05-14 21:49:32 +00:00
|
|
|
|
///
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// If the contents of the `CStr` are valid UTF-8 data, this
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// function will return a <code>[Cow]::[Borrowed]\(&[str])</code>
|
|
|
|
|
/// with the corresponding <code>&[str]</code> slice. Otherwise, it will
|
2018-08-11 18:09:59 +00:00
|
|
|
|
/// replace any invalid UTF-8 sequences with
|
|
|
|
|
/// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// <code>[Cow]::[Owned]\(&[str])</code> with the result.
|
2015-05-14 21:49:32 +00:00
|
|
|
|
///
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// [str]: prim@str "str"
|
|
|
|
|
/// [Borrowed]: Cow::Borrowed
|
|
|
|
|
/// [Owned]: Cow::Owned
|
2022-02-16 11:23:37 +00:00
|
|
|
|
/// [U+FFFD]: core::char::REPLACEMENT_CHARACTER "std::char::REPLACEMENT_CHARACTER"
|
2017-06-18 21:46:19 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::borrow::Cow;
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"Hello World\0")
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// .expect("CStr::from_bytes_with_nul failed");
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World"));
|
2017-06-18 21:46:19 +00:00
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::borrow::Cow;
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0")
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// .expect("CStr::from_bytes_with_nul failed");
|
2017-06-18 21:46:19 +00:00
|
|
|
|
/// assert_eq!(
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// cstr.to_string_lossy(),
|
2019-03-01 08:34:11 +00:00
|
|
|
|
/// Cow::Owned(String::from("Hello <20>World")) as Cow<'_, str>
|
2017-06-18 21:46:19 +00:00
|
|
|
|
/// );
|
|
|
|
|
/// ```
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[rustc_allow_incoherent_impl]
|
2021-10-11 23:04:24 +00:00
|
|
|
|
#[must_use = "this returns the result of the operation, \
|
|
|
|
|
without modifying the original"]
|
2015-09-10 20:26:44 +00:00
|
|
|
|
#[stable(feature = "cstr_to_str", since = "1.4.0")]
|
2019-03-01 08:34:11 +00:00
|
|
|
|
pub fn to_string_lossy(&self) -> Cow<'_, str> {
|
2015-05-14 21:49:32 +00:00
|
|
|
|
String::from_utf8_lossy(self.to_bytes())
|
|
|
|
|
}
|
2017-02-14 01:37:42 +00:00
|
|
|
|
|
Apply 16 commits (squashed)
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::fmt
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::{rc, sync}
----------
Fix spacing for links inside code blocks, and improve link tooltips in alloc::string
----------
Fix spacing for links inside code blocks in alloc::vec
----------
Fix spacing for links inside code blocks in core::option
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in core::result
----------
Fix spacing for links inside code blocks in core::{iter::{self, iterator}, stream::stream, poll}
----------
Fix spacing for links inside code blocks, and improve a few link tooltips in std::{fs, path}
----------
Fix spacing for links inside code blocks in std::{collections, time}
----------
Fix spacing for links inside code blocks in and make formatting of `&str`-like types consistent in std::ffi::{c_str, os_str}
----------
Fix spacing for links inside code blocks, and improve link tooltips in std::ffi
----------
Fix spacing for links inside code blocks, and improve a few link tooltips
in std::{io::{self, buffered::{bufreader, bufwriter}, cursor, util}, net::{self, addr}}
----------
Fix typo in link to `into` for `OsString` docs
----------
Remove tooltips that will probably become redundant in the future
----------
Apply suggestions from code review
Replacing `…std/primitive.reference.html` paths with just `reference`
Co-authored-by: Joshua Nelson <github@jyn.dev>
----------
Also replace `…std/primitive.reference.html` paths with just `reference` in `core::pin`
2021-08-25 09:45:08 +00:00
|
|
|
|
/// Converts a <code>[Box]<[CStr]></code> into a [`CString`] without copying or allocating.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2017-06-18 22:48:00 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CString;
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
|
2017-06-18 22:48:00 +00:00
|
|
|
|
/// let boxed = c_string.into_boxed_c_str();
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
|
2017-06-18 22:48:00 +00:00
|
|
|
|
/// ```
|
2022-02-16 11:23:37 +00:00
|
|
|
|
#[rustc_allow_incoherent_impl]
|
2021-10-31 02:58:27 +00:00
|
|
|
|
#[must_use = "`self` will be dropped if the result is not used"]
|
2017-07-20 22:44:35 +00:00
|
|
|
|
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
|
2022-02-16 11:23:37 +00:00
|
|
|
|
pub fn into_c_string(self: Box<Self>) -> CString {
|
|
|
|
|
CString::from(self)
|
2015-12-29 18:02:08 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2022-07-29 18:54:47 +00:00
|
|
|
|
|
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
|
impl core::error::Error for NulError {
|
|
|
|
|
#[allow(deprecated)]
|
|
|
|
|
fn description(&self) -> &str {
|
|
|
|
|
"nul byte found in data"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
|
|
|
|
|
impl core::error::Error for FromVecWithNulError {}
|
|
|
|
|
|
|
|
|
|
#[stable(feature = "cstring_into", since = "1.7.0")]
|
|
|
|
|
impl core::error::Error for IntoStringError {
|
|
|
|
|
#[allow(deprecated)]
|
|
|
|
|
fn description(&self) -> &str {
|
|
|
|
|
"C string contained non-utf8 bytes"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
|
2023-01-10 14:59:47 +00:00
|
|
|
|
Some(&self.error)
|
2022-07-29 18:54:47 +00:00
|
|
|
|
}
|
|
|
|
|
}
|