2020-08-14 17:33:04 +00:00
|
|
|
|
#![deny(unsafe_op_in_unsafe_fn)]
|
2020-08-27 13:45:01 +00:00
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests;
|
|
|
|
|
|
2019-02-10 19:23:21 +00:00
|
|
|
|
use crate::ascii;
|
2019-12-22 22:42:04 +00:00
|
|
|
|
use crate::borrow::{Borrow, Cow};
|
2019-02-10 19:23:21 +00:00
|
|
|
|
use crate::cmp::Ordering;
|
|
|
|
|
use crate::error::Error;
|
|
|
|
|
use crate::fmt::{self, Write};
|
|
|
|
|
use crate::io;
|
|
|
|
|
use crate::mem;
|
2019-09-01 15:23:20 +00:00
|
|
|
|
use crate::num::NonZeroU8;
|
2019-02-10 19:23:21 +00:00
|
|
|
|
use crate::ops;
|
|
|
|
|
use crate::os::raw::c_char;
|
|
|
|
|
use crate::ptr;
|
|
|
|
|
use crate::rc::Rc;
|
|
|
|
|
use crate::slice;
|
|
|
|
|
use crate::str::{self, Utf8Error};
|
|
|
|
|
use crate::sync::Arc;
|
|
|
|
|
use crate::sys;
|
2021-05-14 01:54:46 +00:00
|
|
|
|
use crate::sys_common::memchr;
|
2014-11-25 21:28:35 +00:00
|
|
|
|
|
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")]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.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
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Representation of a borrowed C string.
|
|
|
|
|
///
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// This type represents a borrowed reference to a nul-terminated
|
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
|
|
|
|
/// array of bytes. It can be constructed safely from a <code>&[[u8]]</code>
|
2017-10-11 22:53:13 +00:00
|
|
|
|
/// slice, or unsafely from a raw `*const c_char`. It can then be
|
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
|
|
|
|
/// converted to a Rust <code>&[str]</code> by performing UTF-8 validation, or
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// into an owned [`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
|
|
|
|
/// `&CStr` is to [`CString`] as <code>&[str]</code> is to [`String`]: the former
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// in each pair are borrowed references; the latter are owned
|
|
|
|
|
/// strings.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
|
|
|
|
/// Note that this structure is **not** `repr(C)` and is not recommended to be
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// functions may leverage the unsafe [`CStr::from_ptr`] constructor to provide
|
|
|
|
|
/// a safe interface to other consumers.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// Inspecting a foreign C string:
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2018-02-18 14:30:10 +00:00
|
|
|
|
/// ```ignore (extern-declaration)
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// use std::ffi::CStr;
|
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 my_string() -> *const c_char; }
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2016-08-08 04:07:36 +00:00
|
|
|
|
/// unsafe {
|
|
|
|
|
/// let slice = CStr::from_ptr(my_string());
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// Passing a Rust-originating C string:
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2018-02-18 14:30:10 +00:00
|
|
|
|
/// ```ignore (extern-declaration)
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// use std::ffi::{CString, CStr};
|
2015-11-11 17:02:55 +00:00
|
|
|
|
/// use std::os::raw::c_char;
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
|
|
|
|
/// fn work(data: &CStr) {
|
2020-09-01 21:12:52 +00:00
|
|
|
|
/// extern "C" { fn work_with(data: *const c_char); }
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
|
|
|
|
/// unsafe { work_with(data.as_ptr()) }
|
|
|
|
|
/// }
|
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let s = CString::new("data data data data").expect("CString::new failed");
|
2016-08-08 04:07:36 +00:00
|
|
|
|
/// work(&s);
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// ```
|
2015-05-14 21:49:32 +00:00
|
|
|
|
///
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// Converting a foreign C string into a Rust [`String`]:
|
|
|
|
|
///
|
2018-02-18 14:30:10 +00:00
|
|
|
|
/// ```ignore (extern-declaration)
|
2015-05-14 21:49:32 +00:00
|
|
|
|
/// use std::ffi::CStr;
|
2015-11-11 17:02:55 +00:00
|
|
|
|
/// use std::os::raw::c_char;
|
2015-05-14 21:49:32 +00:00
|
|
|
|
///
|
2020-09-01 21:12:52 +00:00
|
|
|
|
/// extern "C" { fn my_string() -> *const c_char; }
|
2015-05-14 21:49:32 +00:00
|
|
|
|
///
|
|
|
|
|
/// fn my_string_safe() -> String {
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
|
|
|
|
|
/// }
|
|
|
|
|
/// }
|
|
|
|
|
///
|
2016-08-08 04:07:36 +00:00
|
|
|
|
/// println!("string: {}", my_string_safe());
|
2015-05-14 21:49:32 +00:00
|
|
|
|
/// ```
|
2017-09-25 01:12:51 +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"
|
2015-02-18 06:47:40 +00:00
|
|
|
|
#[derive(Hash)]
|
2021-05-18 13:33:38 +00:00
|
|
|
|
#[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-06-19 20:15:19 +00:00
|
|
|
|
// FIXME:
|
|
|
|
|
// `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
|
|
|
|
|
// on `CStr` being layout-compatible with `[u8]`.
|
|
|
|
|
// When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
|
|
|
|
|
// Anyway, `CStr` representation and layout are considered implementation detail, are
|
|
|
|
|
// not documented and must not be relied upon.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
pub struct CStr {
|
2015-03-02 18:46:05 +00:00
|
|
|
|
// FIXME: this should not be represented with a DST slice but rather with
|
2015-11-11 17:02:55 +00:00
|
|
|
|
// just a raw `c_char` along with some form of marker to make
|
2015-03-02 18:46:05 +00:00
|
|
|
|
// this an unsized type. Essentially `sizeof(&CStr)` should be the
|
|
|
|
|
// same as `sizeof(&c_char)` but `CStr` should be an unsized type.
|
2019-12-22 22:42:04 +00:00
|
|
|
|
inner: [c_char],
|
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)]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
pub struct NulError(usize, Vec<u8>);
|
|
|
|
|
|
2017-10-11 22:51:37 +00:00
|
|
|
|
/// An error indicating that a nul byte was not in the expected position.
|
2017-09-25 15:53:13 +00:00
|
|
|
|
///
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// The slice used to create a [`CStr`] must have one and only one nul byte,
|
|
|
|
|
/// positioned at the end.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// This error is created by the [`CStr::from_bytes_with_nul`] method.
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// See its documentation for more.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2017-06-19 00:44:41 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::{CStr, FromBytesWithNulError};
|
|
|
|
|
///
|
|
|
|
|
/// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
|
|
|
|
|
/// ```
|
2016-09-12 19:37:41 +00:00
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
std: Stabilize APIs for the 1.10 release
This commit applies the FCP decisions made by the libs team for the 1.10 cycle,
including both new stabilizations and deprecations. Specifically, the list of
APIs is:
Stabilized:
* `os::windows::fs::OpenOptionsExt::access_mode`
* `os::windows::fs::OpenOptionsExt::share_mode`
* `os::windows::fs::OpenOptionsExt::custom_flags`
* `os::windows::fs::OpenOptionsExt::attributes`
* `os::windows::fs::OpenOptionsExt::security_qos_flags`
* `os::unix::fs::OpenOptionsExt::custom_flags`
* `sync::Weak::new`
* `Default for sync::Weak`
* `panic::set_hook`
* `panic::take_hook`
* `panic::PanicInfo`
* `panic::PanicInfo::payload`
* `panic::PanicInfo::location`
* `panic::Location`
* `panic::Location::file`
* `panic::Location::line`
* `ffi::CStr::from_bytes_with_nul`
* `ffi::CStr::from_bytes_with_nul_unchecked`
* `ffi::FromBytesWithNulError`
* `fs::Metadata::modified`
* `fs::Metadata::accessed`
* `fs::Metadata::created`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange_weak`
* `collections::{btree,hash}_map::{Occupied,Vacant,}Entry::key`
* `os::unix::net::{UnixStream, UnixListener, UnixDatagram, SocketAddr}`
* `SocketAddr::is_unnamed`
* `SocketAddr::as_pathname`
* `UnixStream::connect`
* `UnixStream::pair`
* `UnixStream::try_clone`
* `UnixStream::local_addr`
* `UnixStream::peer_addr`
* `UnixStream::set_read_timeout`
* `UnixStream::set_write_timeout`
* `UnixStream::read_timeout`
* `UnixStream::write_Timeout`
* `UnixStream::set_nonblocking`
* `UnixStream::take_error`
* `UnixStream::shutdown`
* Read/Write/RawFd impls for `UnixStream`
* `UnixListener::bind`
* `UnixListener::accept`
* `UnixListener::try_clone`
* `UnixListener::local_addr`
* `UnixListener::set_nonblocking`
* `UnixListener::take_error`
* `UnixListener::incoming`
* RawFd impls for `UnixListener`
* `UnixDatagram::bind`
* `UnixDatagram::unbound`
* `UnixDatagram::pair`
* `UnixDatagram::connect`
* `UnixDatagram::try_clone`
* `UnixDatagram::local_addr`
* `UnixDatagram::peer_addr`
* `UnixDatagram::recv_from`
* `UnixDatagram::recv`
* `UnixDatagram::send_to`
* `UnixDatagram::send`
* `UnixDatagram::set_read_timeout`
* `UnixDatagram::set_write_timeout`
* `UnixDatagram::read_timeout`
* `UnixDatagram::write_timeout`
* `UnixDatagram::set_nonblocking`
* `UnixDatagram::take_error`
* `UnixDatagram::shutdown`
* RawFd impls for `UnixDatagram`
* `{BTree,Hash}Map::values_mut`
* `<[_]>::binary_search_by_key`
Deprecated:
* `StaticCondvar` - this, and all other static synchronization primitives
below, are usable today through the lazy-static crate on
stable Rust today. Additionally, we'd like the non-static
versions to be directly usable in a static context one day,
so they're unlikely to be the final forms of the APIs in any
case.
* `CONDVAR_INIT`
* `StaticMutex`
* `MUTEX_INIT`
* `StaticRwLock`
* `RWLOCK_INIT`
* `iter::Peekable::is_empty`
Closes #27717
Closes #27720
cc #27784 (but encode methods still exist)
Closes #30014
Closes #30425
Closes #30449
Closes #31190
Closes #31399
Closes #31767
Closes #32111
Closes #32281
Closes #32312
Closes #32551
Closes #33018
2016-05-17 18:57:07 +00:00
|
|
|
|
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
|
2017-03-09 12:31:26 +00:00
|
|
|
|
pub struct FromBytesWithNulError {
|
|
|
|
|
kind: FromBytesWithNulErrorKind,
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// #![feature(cstring_from_vec_with_nul)]
|
|
|
|
|
/// use std::ffi::{CString, FromVecWithNulError};
|
|
|
|
|
///
|
|
|
|
|
/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err();
|
|
|
|
|
/// ```
|
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
|
|
|
|
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
|
|
|
|
|
pub struct FromVecWithNulError {
|
|
|
|
|
error_kind: FromBytesWithNulErrorKind,
|
|
|
|
|
bytes: Vec<u8>,
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-09 12:31:26 +00:00
|
|
|
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
|
|
|
|
enum FromBytesWithNulErrorKind {
|
|
|
|
|
InteriorNul(usize),
|
|
|
|
|
NotNulTerminated,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl FromBytesWithNulError {
|
|
|
|
|
fn interior_nul(pos: usize) -> FromBytesWithNulError {
|
2019-12-22 22:42:04 +00:00
|
|
|
|
FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
|
2017-03-09 12:31:26 +00:00
|
|
|
|
}
|
|
|
|
|
fn not_nul_terminated() -> FromBytesWithNulError {
|
2019-12-22 22:42:04 +00:00
|
|
|
|
FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
|
2017-03-09 12:31:26 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
std: Stabilize APIs for the 1.10 release
This commit applies the FCP decisions made by the libs team for the 1.10 cycle,
including both new stabilizations and deprecations. Specifically, the list of
APIs is:
Stabilized:
* `os::windows::fs::OpenOptionsExt::access_mode`
* `os::windows::fs::OpenOptionsExt::share_mode`
* `os::windows::fs::OpenOptionsExt::custom_flags`
* `os::windows::fs::OpenOptionsExt::attributes`
* `os::windows::fs::OpenOptionsExt::security_qos_flags`
* `os::unix::fs::OpenOptionsExt::custom_flags`
* `sync::Weak::new`
* `Default for sync::Weak`
* `panic::set_hook`
* `panic::take_hook`
* `panic::PanicInfo`
* `panic::PanicInfo::payload`
* `panic::PanicInfo::location`
* `panic::Location`
* `panic::Location::file`
* `panic::Location::line`
* `ffi::CStr::from_bytes_with_nul`
* `ffi::CStr::from_bytes_with_nul_unchecked`
* `ffi::FromBytesWithNulError`
* `fs::Metadata::modified`
* `fs::Metadata::accessed`
* `fs::Metadata::created`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange_weak`
* `collections::{btree,hash}_map::{Occupied,Vacant,}Entry::key`
* `os::unix::net::{UnixStream, UnixListener, UnixDatagram, SocketAddr}`
* `SocketAddr::is_unnamed`
* `SocketAddr::as_pathname`
* `UnixStream::connect`
* `UnixStream::pair`
* `UnixStream::try_clone`
* `UnixStream::local_addr`
* `UnixStream::peer_addr`
* `UnixStream::set_read_timeout`
* `UnixStream::set_write_timeout`
* `UnixStream::read_timeout`
* `UnixStream::write_Timeout`
* `UnixStream::set_nonblocking`
* `UnixStream::take_error`
* `UnixStream::shutdown`
* Read/Write/RawFd impls for `UnixStream`
* `UnixListener::bind`
* `UnixListener::accept`
* `UnixListener::try_clone`
* `UnixListener::local_addr`
* `UnixListener::set_nonblocking`
* `UnixListener::take_error`
* `UnixListener::incoming`
* RawFd impls for `UnixListener`
* `UnixDatagram::bind`
* `UnixDatagram::unbound`
* `UnixDatagram::pair`
* `UnixDatagram::connect`
* `UnixDatagram::try_clone`
* `UnixDatagram::local_addr`
* `UnixDatagram::peer_addr`
* `UnixDatagram::recv_from`
* `UnixDatagram::recv`
* `UnixDatagram::send_to`
* `UnixDatagram::send`
* `UnixDatagram::set_read_timeout`
* `UnixDatagram::set_write_timeout`
* `UnixDatagram::read_timeout`
* `UnixDatagram::write_timeout`
* `UnixDatagram::set_nonblocking`
* `UnixDatagram::take_error`
* `UnixDatagram::shutdown`
* RawFd impls for `UnixDatagram`
* `{BTree,Hash}Map::values_mut`
* `<[_]>::binary_search_by_key`
Deprecated:
* `StaticCondvar` - this, and all other static synchronization primitives
below, are usable today through the lazy-static crate on
stable Rust today. Additionally, we'd like the non-static
versions to be directly usable in a static context one day,
so they're unlikely to be the final forms of the APIs in any
case.
* `CONDVAR_INIT`
* `StaticMutex`
* `MUTEX_INIT`
* `StaticRwLock`
* `RWLOCK_INIT`
* `iter::Peekable::is_empty`
Closes #27717
Closes #27720
cc #27784 (but encode methods still exist)
Closes #30014
Closes #30425
Closes #30449
Closes #31190
Closes #31399
Closes #31767
Closes #32111
Closes #32281
Closes #32312
Closes #32551
Closes #33018
2016-05-17 18:57:07 +00:00
|
|
|
|
|
2020-06-14 21:21:40 +00:00
|
|
|
|
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
|
|
|
|
|
impl FromVecWithNulError {
|
|
|
|
|
/// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`].
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// #![feature(cstring_from_vec_with_nul)]
|
|
|
|
|
/// 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());
|
|
|
|
|
/// ```
|
|
|
|
|
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:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// #![feature(cstring_from_vec_with_nul)]
|
|
|
|
|
/// 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());
|
|
|
|
|
/// ```
|
|
|
|
|
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)]
|
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 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> {
|
2019-10-18 07:10:13 +00:00
|
|
|
|
trait SpecIntoVec {
|
|
|
|
|
fn into_vec(self) -> Vec<u8>;
|
|
|
|
|
}
|
|
|
|
|
impl<T: Into<Vec<u8>>> SpecIntoVec for T {
|
|
|
|
|
default fn into_vec(self) -> Vec<u8> {
|
|
|
|
|
self.into()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// Specialization for avoiding reallocation.
|
|
|
|
|
impl SpecIntoVec for &'_ [u8] {
|
|
|
|
|
fn into_vec(self) -> Vec<u8> {
|
|
|
|
|
let mut v = Vec::with_capacity(self.len() + 1);
|
|
|
|
|
v.extend(self);
|
|
|
|
|
v
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
impl SpecIntoVec for &'_ str {
|
|
|
|
|
fn into_vec(self) -> Vec<u8> {
|
|
|
|
|
let mut v = Vec::with_capacity(self.len() + 1);
|
|
|
|
|
v.extend(self.as_bytes());
|
|
|
|
|
v
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Self::_new(SpecIntoVec::into_vec(t))
|
2015-09-09 19:37:59 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
|
2015-12-14 23:03:42 +00:00
|
|
|
|
match memchr::memchr(0, &bytes) {
|
2015-02-18 06:47:40 +00:00
|
|
|
|
Some(i) => Err(NulError(i, bytes)),
|
|
|
|
|
None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-11-25 21:28:35 +00:00
|
|
|
|
pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
|
2016-08-21 11:33:28 +00:00
|
|
|
|
v.reserve_exact(1);
|
2014-11-25 21:28:35 +00:00
|
|
|
|
v.push(0);
|
2015-06-03 21:35:50 +00:00
|
|
|
|
CString { 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);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
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 {
|
|
|
|
|
let len = sys::strlen(ptr) + 1; // Including the NUL byte
|
|
|
|
|
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);
|
|
|
|
|
/// assert_eq!(b'o', *ptr.offset(1) as u8);
|
|
|
|
|
/// assert_eq!(b'o', *ptr.offset(2) as u8);
|
|
|
|
|
/// assert_eq!(b'\0', *ptr.offset(3) as u8);
|
|
|
|
|
///
|
|
|
|
|
/// // retake pointer to free memory
|
|
|
|
|
/// let _ = CString::from_raw(ptr);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
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> {
|
2019-12-22 22:42:04 +00:00
|
|
|
|
String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
|
|
|
|
|
error: e.utf8_error(),
|
|
|
|
|
inner: unsafe { CString::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']);
|
|
|
|
|
/// ```
|
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> {
|
2016-09-04 15:37:30 +00:00
|
|
|
|
let mut vec = self.into_inner().into_vec();
|
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']);
|
|
|
|
|
/// ```
|
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> {
|
2016-09-04 15:37:30 +00:00
|
|
|
|
self.into_inner().into_vec()
|
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]
|
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]
|
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]
|
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
|
|
|
|
/// ```
|
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
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// #![feature(cstring_from_vec_with_nul)]
|
2020-06-08 16:31:45 +00:00
|
|
|
|
/// 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()) }
|
|
|
|
|
/// );
|
|
|
|
|
/// ```
|
2020-06-09 20:15:05 +00:00
|
|
|
|
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
|
2020-06-08 16:31:45 +00:00
|
|
|
|
pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
|
|
|
|
|
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
|
|
|
|
///
|
|
|
|
|
/// ```
|
2020-06-14 21:22:36 +00:00
|
|
|
|
/// #![feature(cstring_from_vec_with_nul)]
|
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
|
|
|
|
/// #![feature(cstring_from_vec_with_nul)]
|
|
|
|
|
/// 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
|
|
|
|
/// ```
|
2020-06-09 20:15:05 +00:00
|
|
|
|
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
|
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.
|
|
|
|
|
Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
|
|
|
|
|
}
|
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) {
|
2019-12-22 22:42:04 +00:00
|
|
|
|
unsafe {
|
|
|
|
|
*self.inner.get_unchecked_mut(0) = 0;
|
|
|
|
|
}
|
2016-09-04 15:37:30 +00:00
|
|
|
|
}
|
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 {
|
2017-04-06 18:43: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()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-07-11 20:55:52 +00:00
|
|
|
|
#[stable(feature = "cstr_debug", since = "1.3.0")]
|
|
|
|
|
impl fmt::Debug for CStr {
|
2019-03-01 08:34:11 +00:00
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2016-03-23 03:01:37 +00:00
|
|
|
|
write!(f, "\"")?;
|
2015-07-11 20:55:52 +00:00
|
|
|
|
for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
|
2016-03-23 03:01:37 +00:00
|
|
|
|
f.write_char(byte as char)?;
|
2015-07-11 20:55:52 +00:00
|
|
|
|
}
|
|
|
|
|
write!(f, "\"")
|
2014-11-25 21:28:35 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-15 15:58:59 +00:00
|
|
|
|
#[stable(feature = "cstr_default", since = "1.10.0")]
|
2019-02-18 03:42:36 +00:00
|
|
|
|
impl Default for &CStr {
|
|
|
|
|
fn default() -> Self {
|
2018-12-04 09:21:42 +00:00
|
|
|
|
const SLICE: &[c_char] = &[0];
|
2016-04-15 15:58:59 +00:00
|
|
|
|
unsafe { CStr::from_ptr(SLICE.as_ptr()) }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[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]
|
2019-12-22 22:42:04 +00:00
|
|
|
|
fn borrow(&self) -> &CStr {
|
|
|
|
|
self
|
|
|
|
|
}
|
2015-07-09 23:38:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
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 {
|
|
|
|
|
#[inline]
|
|
|
|
|
fn from(s: Cow<'a, CStr>) -> Self {
|
|
|
|
|
s.into_owned()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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> {
|
|
|
|
|
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> {
|
|
|
|
|
#[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 {
|
|
|
|
|
s.into_c_string()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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`.
|
|
|
|
|
CString::from_vec_unchecked(v)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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> {
|
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 an <code>[Arc]<[CStr]></code> without copying or allocating.
|
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) }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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> {
|
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> {
|
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 an <code>[Rc]<[CStr]></code> without copying or allocating.
|
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> {
|
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) }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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);
|
|
|
|
|
/// ```
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-12-22 22:42:04 +00:00
|
|
|
|
pub fn nul_position(&self) -> usize {
|
|
|
|
|
self.0
|
|
|
|
|
}
|
2015-02-18 06:47:40 +00:00
|
|
|
|
|
|
|
|
|
/// 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");
|
|
|
|
|
/// ```
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-12-22 22:42:04 +00:00
|
|
|
|
pub fn into_vec(self) -> Vec<u8> {
|
|
|
|
|
self.1
|
|
|
|
|
}
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl Error for NulError {
|
2019-12-01 04:01:48 +00:00
|
|
|
|
#[allow(deprecated)]
|
2019-12-22 22:42:04 +00:00
|
|
|
|
fn description(&self) -> &str {
|
|
|
|
|
"nul byte found in data"
|
|
|
|
|
}
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
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)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-03-31 00:56:48 +00:00
|
|
|
|
impl From<NulError> for io::Error {
|
2018-07-11 11:32:03 +00:00
|
|
|
|
/// Converts a [`NulError`] into a [`io::Error`].
|
2015-03-31 00:56:48 +00:00
|
|
|
|
fn from(_: NulError) -> io::Error {
|
2021-03-21 19:22:38 +00:00
|
|
|
|
io::Error::new_const(io::ErrorKind::InvalidInput, &"data provided contains a nul byte")
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-21 15:39:32 +00:00
|
|
|
|
#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
|
2017-02-19 14:36:28 +00:00
|
|
|
|
impl Error for FromBytesWithNulError {
|
2019-12-01 04:01:48 +00:00
|
|
|
|
#[allow(deprecated)]
|
2017-02-19 14:36:28 +00:00
|
|
|
|
fn description(&self) -> &str {
|
2017-03-09 12:31:26 +00:00
|
|
|
|
match self.kind {
|
2019-12-22 22:42:04 +00:00
|
|
|
|
FromBytesWithNulErrorKind::InteriorNul(..) => {
|
|
|
|
|
"data provided contains an interior nul byte"
|
|
|
|
|
}
|
|
|
|
|
FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
|
2017-03-09 12:31:26 +00:00
|
|
|
|
}
|
2017-02-19 14:36:28 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-21 15:39:32 +00:00
|
|
|
|
#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
|
2017-02-19 14:36:28 +00:00
|
|
|
|
impl fmt::Display for FromBytesWithNulError {
|
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 {
|
2017-03-09 12:31:26 +00:00
|
|
|
|
f.write_str(self.description())?;
|
|
|
|
|
if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
|
|
|
|
|
write!(f, " at byte pos {}", pos)?;
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
2017-02-19 14:36:28 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-14 21:21:40 +00:00
|
|
|
|
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
|
|
|
|
|
impl Error for FromVecWithNulError {}
|
|
|
|
|
|
|
|
|
|
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
|
|
|
|
|
impl fmt::Display for FromVecWithNulError {
|
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
|
match self.error_kind {
|
|
|
|
|
FromBytesWithNulErrorKind::InteriorNul(pos) => {
|
|
|
|
|
write!(f, "data provided contains an interior nul byte at pos {}", pos)
|
|
|
|
|
}
|
|
|
|
|
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.
|
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.
|
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
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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 Error for IntoStringError {
|
2019-12-01 04:01:48 +00:00
|
|
|
|
#[allow(deprecated)]
|
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"
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-13 09:43:26 +00:00
|
|
|
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
2016-01-15 18:07:52 +00:00
|
|
|
|
Some(&self.error)
|
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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl CStr {
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// Wraps a raw C string with a safe C string wrapper.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// This function will wrap the provided `ptr` with a `CStr` wrapper, which
|
2019-09-09 23:50:11 +00:00
|
|
|
|
/// allows inspection and interoperation of non-owned C strings. The total
|
|
|
|
|
/// size of the raw C string must be smaller than `isize::MAX` **bytes**
|
2019-09-10 01:09:17 +00:00
|
|
|
|
/// in memory due to calling the `slice::from_raw_parts` function.
|
2019-09-09 23:50:11 +00:00
|
|
|
|
/// This method is unsafe for a number of reasons:
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// * There is no guarantee to the validity of `ptr`.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// * The returned lifetime is not guaranteed to be the actual lifetime of
|
2017-05-22 14:55:00 +00:00
|
|
|
|
/// `ptr`.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// * There is no guarantee that the memory pointed to by `ptr` contains a
|
|
|
|
|
/// valid nul terminator byte at the end of the string.
|
2018-02-24 15:50:44 +00:00
|
|
|
|
/// * It is not guaranteed that the memory pointed by `ptr` won't change
|
|
|
|
|
/// before the `CStr` has been destroyed.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
|
|
|
|
/// > **Note**: This operation is intended to be a 0-cost cast but it is
|
|
|
|
|
/// > currently implemented with an up-front calculation of the length of
|
|
|
|
|
/// > the string. This is not guaranteed to always be the case.
|
|
|
|
|
///
|
2015-03-12 01:11:40 +00:00
|
|
|
|
/// # Examples
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2018-02-18 14:30:10 +00:00
|
|
|
|
/// ```ignore (extern-declaration)
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// # fn main() {
|
|
|
|
|
/// use std::ffi::CStr;
|
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" {
|
2015-11-11 17:02:55 +00:00
|
|
|
|
/// fn my_string() -> *const c_char;
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// let slice = CStr::from_ptr(my_string());
|
2016-01-19 05:29:53 +00:00
|
|
|
|
/// println!("string returned: {}", slice.to_str().unwrap());
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// # }
|
|
|
|
|
/// ```
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-11-11 17:02:55 +00:00
|
|
|
|
pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
|
2020-08-14 17:33:04 +00:00
|
|
|
|
// SAFETY: The caller has provided a pointer that points to a valid C
|
|
|
|
|
// string with a NUL terminator of size less than `isize::MAX`, whose
|
|
|
|
|
// content remain valid and doesn't change for the lifetime of the
|
|
|
|
|
// returned `CStr`.
|
|
|
|
|
//
|
|
|
|
|
// Thus computing the length is fine (a NUL byte exists), the call to
|
|
|
|
|
// from_raw_parts is safe because we know the length is at most `isize::MAX`, meaning
|
|
|
|
|
// the call to `from_bytes_with_nul_unchecked` is correct.
|
|
|
|
|
//
|
|
|
|
|
// The cast from c_char to u8 is ok because a c_char is always one byte.
|
|
|
|
|
unsafe {
|
|
|
|
|
let len = sys::strlen(ptr);
|
|
|
|
|
let ptr = ptr as *const u8;
|
|
|
|
|
CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
|
|
|
|
|
}
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-12-29 18:41:43 +00:00
|
|
|
|
/// Creates a C string wrapper from a byte slice.
|
|
|
|
|
///
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// This function will cast the provided `bytes` to a `CStr`
|
|
|
|
|
/// wrapper after ensuring that the byte slice is nul-terminated
|
|
|
|
|
/// and does not contain any interior nul bytes.
|
2015-12-29 18:41:43 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2016-01-25 00:51:19 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"hello\0");
|
std: Stabilize APIs for the 1.10 release
This commit applies the FCP decisions made by the libs team for the 1.10 cycle,
including both new stabilizations and deprecations. Specifically, the list of
APIs is:
Stabilized:
* `os::windows::fs::OpenOptionsExt::access_mode`
* `os::windows::fs::OpenOptionsExt::share_mode`
* `os::windows::fs::OpenOptionsExt::custom_flags`
* `os::windows::fs::OpenOptionsExt::attributes`
* `os::windows::fs::OpenOptionsExt::security_qos_flags`
* `os::unix::fs::OpenOptionsExt::custom_flags`
* `sync::Weak::new`
* `Default for sync::Weak`
* `panic::set_hook`
* `panic::take_hook`
* `panic::PanicInfo`
* `panic::PanicInfo::payload`
* `panic::PanicInfo::location`
* `panic::Location`
* `panic::Location::file`
* `panic::Location::line`
* `ffi::CStr::from_bytes_with_nul`
* `ffi::CStr::from_bytes_with_nul_unchecked`
* `ffi::FromBytesWithNulError`
* `fs::Metadata::modified`
* `fs::Metadata::accessed`
* `fs::Metadata::created`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange_weak`
* `collections::{btree,hash}_map::{Occupied,Vacant,}Entry::key`
* `os::unix::net::{UnixStream, UnixListener, UnixDatagram, SocketAddr}`
* `SocketAddr::is_unnamed`
* `SocketAddr::as_pathname`
* `UnixStream::connect`
* `UnixStream::pair`
* `UnixStream::try_clone`
* `UnixStream::local_addr`
* `UnixStream::peer_addr`
* `UnixStream::set_read_timeout`
* `UnixStream::set_write_timeout`
* `UnixStream::read_timeout`
* `UnixStream::write_Timeout`
* `UnixStream::set_nonblocking`
* `UnixStream::take_error`
* `UnixStream::shutdown`
* Read/Write/RawFd impls for `UnixStream`
* `UnixListener::bind`
* `UnixListener::accept`
* `UnixListener::try_clone`
* `UnixListener::local_addr`
* `UnixListener::set_nonblocking`
* `UnixListener::take_error`
* `UnixListener::incoming`
* RawFd impls for `UnixListener`
* `UnixDatagram::bind`
* `UnixDatagram::unbound`
* `UnixDatagram::pair`
* `UnixDatagram::connect`
* `UnixDatagram::try_clone`
* `UnixDatagram::local_addr`
* `UnixDatagram::peer_addr`
* `UnixDatagram::recv_from`
* `UnixDatagram::recv`
* `UnixDatagram::send_to`
* `UnixDatagram::send`
* `UnixDatagram::set_read_timeout`
* `UnixDatagram::set_write_timeout`
* `UnixDatagram::read_timeout`
* `UnixDatagram::write_timeout`
* `UnixDatagram::set_nonblocking`
* `UnixDatagram::take_error`
* `UnixDatagram::shutdown`
* RawFd impls for `UnixDatagram`
* `{BTree,Hash}Map::values_mut`
* `<[_]>::binary_search_by_key`
Deprecated:
* `StaticCondvar` - this, and all other static synchronization primitives
below, are usable today through the lazy-static crate on
stable Rust today. Additionally, we'd like the non-static
versions to be directly usable in a static context one day,
so they're unlikely to be the final forms of the APIs in any
case.
* `CONDVAR_INIT`
* `StaticMutex`
* `MUTEX_INIT`
* `StaticRwLock`
* `RWLOCK_INIT`
* `iter::Peekable::is_empty`
Closes #27717
Closes #27720
cc #27784 (but encode methods still exist)
Closes #30014
Closes #30425
Closes #30449
Closes #31190
Closes #31399
Closes #31767
Closes #32111
Closes #32281
Closes #32312
Closes #32551
Closes #33018
2016-05-17 18:57:07 +00:00
|
|
|
|
/// assert!(cstr.is_ok());
|
2015-12-29 18:41:43 +00:00
|
|
|
|
/// ```
|
2017-06-18 21:28:10 +00:00
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// Creating a `CStr` without a trailing nul terminator is an error:
|
2017-06-18 21:28:10 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"hello");
|
|
|
|
|
/// assert!(cstr.is_err());
|
2017-06-18 21:28:10 +00:00
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// Creating a `CStr` with an interior nul byte is an error:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
|
|
|
|
|
/// assert!(cstr.is_err());
|
2017-06-18 21:28:10 +00:00
|
|
|
|
/// ```
|
std: Stabilize APIs for the 1.10 release
This commit applies the FCP decisions made by the libs team for the 1.10 cycle,
including both new stabilizations and deprecations. Specifically, the list of
APIs is:
Stabilized:
* `os::windows::fs::OpenOptionsExt::access_mode`
* `os::windows::fs::OpenOptionsExt::share_mode`
* `os::windows::fs::OpenOptionsExt::custom_flags`
* `os::windows::fs::OpenOptionsExt::attributes`
* `os::windows::fs::OpenOptionsExt::security_qos_flags`
* `os::unix::fs::OpenOptionsExt::custom_flags`
* `sync::Weak::new`
* `Default for sync::Weak`
* `panic::set_hook`
* `panic::take_hook`
* `panic::PanicInfo`
* `panic::PanicInfo::payload`
* `panic::PanicInfo::location`
* `panic::Location`
* `panic::Location::file`
* `panic::Location::line`
* `ffi::CStr::from_bytes_with_nul`
* `ffi::CStr::from_bytes_with_nul_unchecked`
* `ffi::FromBytesWithNulError`
* `fs::Metadata::modified`
* `fs::Metadata::accessed`
* `fs::Metadata::created`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange_weak`
* `collections::{btree,hash}_map::{Occupied,Vacant,}Entry::key`
* `os::unix::net::{UnixStream, UnixListener, UnixDatagram, SocketAddr}`
* `SocketAddr::is_unnamed`
* `SocketAddr::as_pathname`
* `UnixStream::connect`
* `UnixStream::pair`
* `UnixStream::try_clone`
* `UnixStream::local_addr`
* `UnixStream::peer_addr`
* `UnixStream::set_read_timeout`
* `UnixStream::set_write_timeout`
* `UnixStream::read_timeout`
* `UnixStream::write_Timeout`
* `UnixStream::set_nonblocking`
* `UnixStream::take_error`
* `UnixStream::shutdown`
* Read/Write/RawFd impls for `UnixStream`
* `UnixListener::bind`
* `UnixListener::accept`
* `UnixListener::try_clone`
* `UnixListener::local_addr`
* `UnixListener::set_nonblocking`
* `UnixListener::take_error`
* `UnixListener::incoming`
* RawFd impls for `UnixListener`
* `UnixDatagram::bind`
* `UnixDatagram::unbound`
* `UnixDatagram::pair`
* `UnixDatagram::connect`
* `UnixDatagram::try_clone`
* `UnixDatagram::local_addr`
* `UnixDatagram::peer_addr`
* `UnixDatagram::recv_from`
* `UnixDatagram::recv`
* `UnixDatagram::send_to`
* `UnixDatagram::send`
* `UnixDatagram::set_read_timeout`
* `UnixDatagram::set_write_timeout`
* `UnixDatagram::read_timeout`
* `UnixDatagram::write_timeout`
* `UnixDatagram::set_nonblocking`
* `UnixDatagram::take_error`
* `UnixDatagram::shutdown`
* RawFd impls for `UnixDatagram`
* `{BTree,Hash}Map::values_mut`
* `<[_]>::binary_search_by_key`
Deprecated:
* `StaticCondvar` - this, and all other static synchronization primitives
below, are usable today through the lazy-static crate on
stable Rust today. Additionally, we'd like the non-static
versions to be directly usable in a static context one day,
so they're unlikely to be the final forms of the APIs in any
case.
* `CONDVAR_INIT`
* `StaticMutex`
* `MUTEX_INIT`
* `StaticRwLock`
* `RWLOCK_INIT`
* `iter::Peekable::is_empty`
Closes #27717
Closes #27720
cc #27784 (but encode methods still exist)
Closes #30014
Closes #30425
Closes #30449
Closes #31190
Closes #31399
Closes #31767
Closes #32111
Closes #32281
Closes #32312
Closes #32551
Closes #33018
2016-05-17 18:57:07 +00:00
|
|
|
|
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
|
2019-12-22 22:42:04 +00:00
|
|
|
|
pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
|
2017-03-09 12:31:26 +00:00
|
|
|
|
let nul_pos = memchr::memchr(0, bytes);
|
|
|
|
|
if let Some(nul_pos) = nul_pos {
|
|
|
|
|
if nul_pos + 1 != bytes.len() {
|
|
|
|
|
return Err(FromBytesWithNulError::interior_nul(nul_pos));
|
|
|
|
|
}
|
|
|
|
|
Ok(unsafe { CStr::from_bytes_with_nul_unchecked(bytes) })
|
2015-12-29 18:41:43 +00:00
|
|
|
|
} else {
|
2017-03-09 12:31:26 +00:00
|
|
|
|
Err(FromBytesWithNulError::not_nul_terminated())
|
2015-12-29 18:41:43 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Unsafely creates a C string wrapper from a byte slice.
|
|
|
|
|
///
|
|
|
|
|
/// This function will cast the provided `bytes` to a `CStr` wrapper without
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// performing any sanity checks. The provided slice **must** be nul-terminated
|
2015-12-29 18:41:43 +00:00
|
|
|
|
/// and not contain any interior nul bytes.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::{CStr, CString};
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let cstring = CString::new("hello").expect("CString::new failed");
|
2016-01-25 00:51:19 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
|
2015-12-29 18:41:43 +00:00
|
|
|
|
/// assert_eq!(cstr, &*cstring);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
std: Stabilize APIs for the 1.10 release
This commit applies the FCP decisions made by the libs team for the 1.10 cycle,
including both new stabilizations and deprecations. Specifically, the list of
APIs is:
Stabilized:
* `os::windows::fs::OpenOptionsExt::access_mode`
* `os::windows::fs::OpenOptionsExt::share_mode`
* `os::windows::fs::OpenOptionsExt::custom_flags`
* `os::windows::fs::OpenOptionsExt::attributes`
* `os::windows::fs::OpenOptionsExt::security_qos_flags`
* `os::unix::fs::OpenOptionsExt::custom_flags`
* `sync::Weak::new`
* `Default for sync::Weak`
* `panic::set_hook`
* `panic::take_hook`
* `panic::PanicInfo`
* `panic::PanicInfo::payload`
* `panic::PanicInfo::location`
* `panic::Location`
* `panic::Location::file`
* `panic::Location::line`
* `ffi::CStr::from_bytes_with_nul`
* `ffi::CStr::from_bytes_with_nul_unchecked`
* `ffi::FromBytesWithNulError`
* `fs::Metadata::modified`
* `fs::Metadata::accessed`
* `fs::Metadata::created`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange`
* `sync::atomic::Atomic{Usize,Isize,Bool,Ptr}::compare_exchange_weak`
* `collections::{btree,hash}_map::{Occupied,Vacant,}Entry::key`
* `os::unix::net::{UnixStream, UnixListener, UnixDatagram, SocketAddr}`
* `SocketAddr::is_unnamed`
* `SocketAddr::as_pathname`
* `UnixStream::connect`
* `UnixStream::pair`
* `UnixStream::try_clone`
* `UnixStream::local_addr`
* `UnixStream::peer_addr`
* `UnixStream::set_read_timeout`
* `UnixStream::set_write_timeout`
* `UnixStream::read_timeout`
* `UnixStream::write_Timeout`
* `UnixStream::set_nonblocking`
* `UnixStream::take_error`
* `UnixStream::shutdown`
* Read/Write/RawFd impls for `UnixStream`
* `UnixListener::bind`
* `UnixListener::accept`
* `UnixListener::try_clone`
* `UnixListener::local_addr`
* `UnixListener::set_nonblocking`
* `UnixListener::take_error`
* `UnixListener::incoming`
* RawFd impls for `UnixListener`
* `UnixDatagram::bind`
* `UnixDatagram::unbound`
* `UnixDatagram::pair`
* `UnixDatagram::connect`
* `UnixDatagram::try_clone`
* `UnixDatagram::local_addr`
* `UnixDatagram::peer_addr`
* `UnixDatagram::recv_from`
* `UnixDatagram::recv`
* `UnixDatagram::send_to`
* `UnixDatagram::send`
* `UnixDatagram::set_read_timeout`
* `UnixDatagram::set_write_timeout`
* `UnixDatagram::read_timeout`
* `UnixDatagram::write_timeout`
* `UnixDatagram::set_nonblocking`
* `UnixDatagram::take_error`
* `UnixDatagram::shutdown`
* RawFd impls for `UnixDatagram`
* `{BTree,Hash}Map::values_mut`
* `<[_]>::binary_search_by_key`
Deprecated:
* `StaticCondvar` - this, and all other static synchronization primitives
below, are usable today through the lazy-static crate on
stable Rust today. Additionally, we'd like the non-static
versions to be directly usable in a static context one day,
so they're unlikely to be the final forms of the APIs in any
case.
* `CONDVAR_INIT`
* `StaticMutex`
* `MUTEX_INIT`
* `StaticRwLock`
* `RWLOCK_INIT`
* `iter::Peekable::is_empty`
Closes #27717
Closes #27720
cc #27784 (but encode methods still exist)
Closes #30014
Closes #30425
Closes #30449
Closes #31190
Closes #31399
Closes #31767
Closes #32111
Closes #32281
Closes #32312
Closes #32551
Closes #33018
2016-05-17 18:57:07 +00:00
|
|
|
|
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
|
2019-12-21 11:16:18 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_cstr_unchecked", issue = "none")]
|
2018-10-02 10:42:01 +00:00
|
|
|
|
pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
|
2020-08-14 17:33:04 +00:00
|
|
|
|
// SAFETY: Casting to CStr is safe because its internal representation
|
|
|
|
|
// is a [u8] too (safe only inside std).
|
|
|
|
|
// Dereferencing the obtained pointer is safe because it comes from a
|
|
|
|
|
// reference. Making a reference is then safe because its lifetime
|
|
|
|
|
// is bound by the lifetime of the given `bytes`.
|
|
|
|
|
unsafe { &*(bytes as *const [u8] as *const CStr) }
|
2015-12-29 18:41:43 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
|
/// Returns the inner pointer to this C string.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// The returned pointer will be valid for as long as `self` is, and points
|
2015-02-22 13:52:07 +00:00
|
|
|
|
/// to a contiguous region of memory terminated with a 0 byte to represent
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// the end of the string.
|
2016-06-19 08:55:34 +00:00
|
|
|
|
///
|
|
|
|
|
/// **WARNING**
|
|
|
|
|
///
|
2019-05-01 15:59:48 +00:00
|
|
|
|
/// The returned pointer is read-only; writing to it (including passing it
|
|
|
|
|
/// to C code that writes to it) causes undefined behavior.
|
|
|
|
|
///
|
2016-06-19 08:55:34 +00:00
|
|
|
|
/// It is your responsibility to make sure that the underlying memory is not
|
|
|
|
|
/// freed too early. For example, the following code will cause undefined
|
2017-08-15 19:45:21 +00:00
|
|
|
|
/// behavior when `ptr` is used inside the `unsafe` block:
|
2016-06-19 08:55:34 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```no_run
|
2020-11-19 20:01:48 +00:00
|
|
|
|
/// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
|
2019-08-01 08:13:53 +00:00
|
|
|
|
/// use std::ffi::CString;
|
2016-06-19 08:55:34 +00:00
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
|
2016-06-19 08:55:34 +00:00
|
|
|
|
/// unsafe {
|
|
|
|
|
/// // `ptr` is dangling
|
|
|
|
|
/// *ptr;
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// This happens because the pointer returned by `as_ptr` does not carry any
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// lifetime information and the [`CString`] is deallocated immediately after
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
|
|
|
|
|
/// expression is evaluated.
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// To fix the problem, bind the `CString` to a local variable:
|
2016-06-19 08:55:34 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```no_run
|
2018-03-11 00:23:28 +00:00
|
|
|
|
/// # #![allow(unused_must_use)]
|
2019-08-01 08:13:53 +00:00
|
|
|
|
/// use std::ffi::CString;
|
2016-06-19 08:55:34 +00:00
|
|
|
|
///
|
2018-09-05 21:54:07 +00:00
|
|
|
|
/// let hello = CString::new("Hello").expect("CString::new failed");
|
2016-06-19 08:55:34 +00:00
|
|
|
|
/// let ptr = hello.as_ptr();
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// // `ptr` is valid because `hello` is in scope
|
|
|
|
|
/// *ptr;
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2017-09-25 01:12:51 +00:00
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// This way, the lifetime of the [`CString`] in `hello` encompasses
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// the lifetime of `ptr` and the `unsafe` block.
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-12-18 17:00:59 +00:00
|
|
|
|
#[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
|
2018-10-23 00:04:42 +00:00
|
|
|
|
pub const fn as_ptr(&self) -> *const c_char {
|
2015-02-18 06:47:40 +00:00
|
|
|
|
self.inner.as_ptr()
|
|
|
|
|
}
|
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
|
/// Converts this C string to a byte slice.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2017-09-23 01:36:44 +00:00
|
|
|
|
/// The returned slice will **not** contain the trailing nul terminator that this C
|
2015-02-18 06:47:40 +00:00
|
|
|
|
/// string has.
|
|
|
|
|
///
|
2018-01-27 16:54:01 +00:00
|
|
|
|
/// > **Note**: This method is currently implemented as a constant-time
|
|
|
|
|
/// > cast, but it is planned to alter its definition in the future to
|
|
|
|
|
/// > perform the length calculation whenever this method is called.
|
2017-06-18 21:11:34 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
|
|
|
|
|
/// assert_eq!(cstr.to_bytes(), b"foo");
|
2017-06-18 21:11:34 +00:00
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
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 to_bytes(&self) -> &[u8] {
|
|
|
|
|
let bytes = self.to_bytes_with_nul();
|
2021-03-28 16:55:09 +00:00
|
|
|
|
// SAFETY: to_bytes_with_nul returns slice with length at least 1
|
|
|
|
|
unsafe { bytes.get_unchecked(..bytes.len() - 1) }
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
|
/// Converts this C string to a byte slice containing the trailing 0 byte.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
2020-08-13 21:19:45 +00:00
|
|
|
|
/// This function is the equivalent of [`CStr::to_bytes`] except that it
|
|
|
|
|
/// will retain the trailing nul terminator instead of chopping it off.
|
2015-02-18 06:47:40 +00:00
|
|
|
|
///
|
|
|
|
|
/// > **Note**: This method is currently implemented as a 0-cost cast, but
|
|
|
|
|
/// > it is planned to alter its definition in the future to perform the
|
|
|
|
|
/// > length calculation whenever this method is called.
|
2017-05-22 14:55:00 +00:00
|
|
|
|
///
|
2017-06-18 21:12:17 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
|
|
|
|
|
/// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
|
2017-06-18 21:12:17 +00:00
|
|
|
|
/// ```
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
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 to_bytes_with_nul(&self) -> &[u8] {
|
2017-09-28 04:51:38 +00:00
|
|
|
|
unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
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
|
|
|
|
/// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
|
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 the corresponding <code>&[str]</code> slice. Otherwise,
|
2017-09-25 01:12:51 +00:00
|
|
|
|
/// it will return an error with details of where UTF-8 validation failed.
|
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"
|
2017-06-18 23:12:39 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ffi::CStr;
|
|
|
|
|
///
|
2019-08-22 13:09:03 +00:00
|
|
|
|
/// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
|
|
|
|
|
/// assert_eq!(cstr.to_str(), Ok("foo"));
|
2017-06-18 23:12:39 +00:00
|
|
|
|
/// ```
|
2015-09-10 20:26:44 +00:00
|
|
|
|
#[stable(feature = "cstr_to_str", since = "1.4.0")]
|
2015-05-14 21:49:32 +00:00
|
|
|
|
pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
|
2018-11-27 02:59:49 +00:00
|
|
|
|
// N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
|
|
|
|
|
// instead of in `from_ptr()`, it may be worth considering if this should
|
2015-08-13 17:12:38 +00:00
|
|
|
|
// be rewritten to do the UTF-8 check inline with the length calculation
|
|
|
|
|
// instead of doing it afterwards.
|
2015-05-14 21:49:32 +00:00
|
|
|
|
str::from_utf8(self.to_bytes())
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
/// [U+FFFD]: crate::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
|
|
|
|
/// );
|
|
|
|
|
/// ```
|
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
|
|
|
|
/// ```
|
2017-07-20 22:44:35 +00:00
|
|
|
|
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
|
2017-02-14 01:37:42 +00:00
|
|
|
|
pub fn into_c_string(self: Box<CStr>) -> CString {
|
2017-09-28 04:51:38 +00:00
|
|
|
|
let raw = Box::into_raw(self) as *mut [u8];
|
|
|
|
|
CString { inner: unsafe { Box::from_raw(raw) } }
|
2017-02-14 01:37:42 +00:00
|
|
|
|
}
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl PartialEq for CStr {
|
|
|
|
|
fn eq(&self, other: &CStr) -> bool {
|
2015-02-20 17:32:55 +00:00
|
|
|
|
self.to_bytes().eq(other.to_bytes())
|
2015-02-18 06:47:40 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl Eq for CStr {}
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl PartialOrd for CStr {
|
|
|
|
|
fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
|
|
|
|
|
self.to_bytes().partial_cmp(&other.to_bytes())
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-03-02 18:46:05 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-02-18 06:47:40 +00:00
|
|
|
|
impl Ord for CStr {
|
|
|
|
|
fn cmp(&self, other: &CStr) -> Ordering {
|
|
|
|
|
self.to_bytes().cmp(&other.to_bytes())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-07-09 23:38:55 +00:00
|
|
|
|
#[stable(feature = "cstr_borrow", since = "1.3.0")]
|
|
|
|
|
impl ToOwned for CStr {
|
|
|
|
|
type Owned = CString;
|
|
|
|
|
|
|
|
|
|
fn to_owned(&self) -> CString {
|
2017-02-01 03:46:16 +00:00
|
|
|
|
CString { inner: self.to_bytes_with_nul().into() }
|
2015-07-09 23:38:55 +00:00
|
|
|
|
}
|
2020-03-20 22:42:56 +00:00
|
|
|
|
|
|
|
|
|
fn clone_into(&self, target: &mut CString) {
|
|
|
|
|
let mut b = Vec::from(mem::take(&mut target.inner));
|
|
|
|
|
self.to_bytes_with_nul().clone_into(&mut b);
|
|
|
|
|
target.inner = b.into_boxed_slice();
|
|
|
|
|
}
|
2015-07-09 23:38:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-12-31 19:21:40 +00:00
|
|
|
|
#[stable(feature = "cstring_asref", since = "1.7.0")]
|
2019-03-10 03:10:28 +00:00
|
|
|
|
impl From<&CStr> for CString {
|
|
|
|
|
fn from(s: &CStr) -> CString {
|
2015-12-31 18:56:21 +00:00
|
|
|
|
s.to_owned()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-12-31 19:21:40 +00:00
|
|
|
|
#[stable(feature = "cstring_asref", since = "1.7.0")]
|
2015-12-29 18:02:08 +00:00
|
|
|
|
impl ops::Index<ops::RangeFull> for CString {
|
|
|
|
|
type Output = CStr;
|
|
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
|
fn index(&self, _index: ops::RangeFull) -> &CStr {
|
|
|
|
|
self
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-07-18 19:16:25 +00:00
|
|
|
|
#[stable(feature = "cstr_range_from", since = "1.47.0")]
|
2020-07-04 02:11:10 +00:00
|
|
|
|
impl ops::Index<ops::RangeFrom<usize>> for CStr {
|
|
|
|
|
type Output = CStr;
|
|
|
|
|
|
|
|
|
|
fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
|
|
|
|
|
let bytes = self.to_bytes_with_nul();
|
|
|
|
|
// we need to manually check the starting index to account for the null
|
|
|
|
|
// byte, since otherwise we could get an empty string that doesn't end
|
|
|
|
|
// in a null.
|
|
|
|
|
if index.start < bytes.len() {
|
|
|
|
|
unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
|
|
|
|
|
} else {
|
|
|
|
|
panic!(
|
|
|
|
|
"index out of bounds: the len is {} but the index is {}",
|
|
|
|
|
bytes.len(),
|
|
|
|
|
index.start
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-12-31 19:21:40 +00:00
|
|
|
|
#[stable(feature = "cstring_asref", since = "1.7.0")]
|
2015-12-29 18:02:08 +00:00
|
|
|
|
impl AsRef<CStr> for CStr {
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2015-12-29 18:02:08 +00:00
|
|
|
|
fn as_ref(&self) -> &CStr {
|
|
|
|
|
self
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-12-31 19:21:40 +00:00
|
|
|
|
#[stable(feature = "cstring_asref", since = "1.7.0")]
|
2015-12-29 18:02:08 +00:00
|
|
|
|
impl AsRef<CStr> for CString {
|
2017-06-17 12:50:55 +00:00
|
|
|
|
#[inline]
|
2015-12-29 18:02:08 +00:00
|
|
|
|
fn as_ref(&self) -> &CStr {
|
|
|
|
|
self
|
|
|
|
|
}
|
|
|
|
|
}
|