1//! [`CStr`] and its related types.
23use crate::cmp::Ordering;
4use crate::error::Error;
5use crate::ffi::c_char;
6use crate::intrinsics::const_eval_select;
7use crate::iter::FusedIterator;
8use crate::marker::PhantomData;
9use crate::num::niche_types::UsizeNoHighBitMinusOne;
10use crate::ptr::NonNull;
11use crate::slice::memchr;
12use crate::{fmt, ops, range, slice, str};
1314// FIXME: because this is doc(inline)d, we *have* to use intra-doc links because the actual link
15// depends on where the item is being documented. however, since this is libcore, we can't
16// actually reference libstd or liballoc in intra-doc links. so, the best we can do is remove the
17// links to `CString` and `String` for now until a solution is developed
1819/// A dynamically-sized view of a C string.
20///
21/// The type `&CStr` represents a reference to a borrowed nul-terminated
22/// array of bytes. It can be constructed safely from a <code>&[[u8]]</code>
23/// slice, or unsafely from a raw `*const c_char`. It can be expressed as a
24/// literal in the form `c"Hello world"`.
25///
26/// The `&CStr` can then be converted to a Rust <code>&[str]</code> by performing
27/// UTF-8 validation, or into an owned `CString`.
28///
29/// `&CStr` is to `CString` as <code>&[str]</code> is to `String`: the former
30/// in each pair are borrowing references; the latter are owned
31/// strings.
32///
33/// Note that this structure does **not** have a guaranteed layout (the `repr(transparent)`
34/// notwithstanding) and should not be placed in the signatures of FFI functions.
35/// Instead, safe wrappers of FFI functions may leverage [`CStr::as_ptr`] and the unsafe
36/// [`CStr::from_ptr`] constructor to provide a safe interface to other consumers.
37///
38/// # Examples
39///
40/// Inspecting a foreign C string:
41///
42/// ```
43/// use std::ffi::CStr;
44/// use std::os::raw::c_char;
45///
46/// # /* Extern functions are awkward in doc comments - fake it instead
47/// extern "C" { fn my_string() -> *const c_char; }
48/// # */ unsafe extern "C" fn my_string() -> *const c_char { c"hello".as_ptr() }
49///
50/// unsafe {
51/// let slice = CStr::from_ptr(my_string());
52/// println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
53/// }
54/// ```
55///
56/// Passing a Rust-originating C string:
57///
58/// ```
59/// use std::ffi::CStr;
60/// use std::os::raw::c_char;
61///
62/// fn work(data: &CStr) {
63/// unsafe extern "C" fn work_with(s: *const c_char) {}
64/// unsafe { work_with(data.as_ptr()) }
65/// }
66///
67/// let s = c"Hello world!";
68/// work(&s);
69/// ```
70///
71/// Converting a foreign C string into a Rust `String`:
72///
73/// ```
74/// use std::ffi::CStr;
75/// use std::os::raw::c_char;
76///
77/// # /* Extern functions are awkward in doc comments - fake it instead
78/// extern "C" { fn my_string() -> *const c_char; }
79/// # */ unsafe extern "C" fn my_string() -> *const c_char { c"hello".as_ptr() }
80///
81/// fn my_string_safe() -> String {
82/// let cstr = unsafe { CStr::from_ptr(my_string()) };
83/// // Get a copy-on-write Cow<'_, str>, then extract the
84/// // allocated String (or allocate a fresh one if needed).
85/// cstr.to_string_lossy().into_owned()
86/// }
87///
88/// println!("string: {}", my_string_safe());
89/// ```
90///
91/// [str]: prim@str "str"
92#[derive(#[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::hash::Hash for CStr {
#[inline]
fn hash<__H: crate::hash::Hasher>(&self, state: &mut __H) {
crate::hash::Hash::hash(&self.inner, state)
}
}Hash)]
93#[derive_const(#[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::marker::StructuralPartialEq for CStr { }
#[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "core_c_str", since = "1.64.0")]
const impl crate::cmp::PartialEq for CStr {
#[inline]
fn eq(&self, other: &Self) -> bool { self.inner == other.inner }
}PartialEq, #[automatically_derived]
#[rustc_const_unstable(feature = "derive_const", issue = "118304")]
#[stable(feature = "core_c_str", since = "1.64.0")]
const impl crate::cmp::Eq for CStr {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: crate::cmp::AssertParamIsEq<[c_char]>;
}
}Eq)]
94#[stable(feature = "core_c_str", since = "1.64.0")]
95#[rustc_diagnostic_item = "cstr_type"]
96#[rustc_has_incoherent_inherent_impls]
97#[lang = "CStr"]
98// `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
99// on `CStr` being layout-compatible with `[u8]`.
100// However, `CStr` layout is considered an implementation detail and must not be relied upon. We
101// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under
102// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy.
103#[repr(transparent)]
104pub struct CStr {
105// FIXME: this should not be represented with a DST slice but rather with
106 // just a raw `c_char` along with some form of marker to make
107 // this an unsized type. Essentially `sizeof(&CStr)` should be the
108 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
109inner: [c_char],
110}
111112/// An error indicating that a nul byte was not in the expected position.
113///
114/// The slice used to create a [`CStr`] must have one and only one nul byte,
115/// positioned at the end.
116///
117/// This error is created by the [`CStr::from_bytes_with_nul`] method.
118/// See its documentation for more.
119///
120/// # Examples
121///
122/// ```
123/// use std::ffi::{CStr, FromBytesWithNulError};
124///
125/// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
126/// ```
127#[derive(#[automatically_derived]
#[doc(hidden)]
#[stable(feature = "core_c_str", since = "1.64.0")]
unsafe impl crate::clone::TrivialClone for FromBytesWithNulError { }
#[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::clone::Clone for FromBytesWithNulError {
#[inline]
fn clone(&self) -> Self {
let _: crate::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::marker::Copy for FromBytesWithNulError { }Copy, #[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::marker::StructuralPartialEq for FromBytesWithNulError { }
#[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::cmp::PartialEq for FromBytesWithNulError {
#[inline]
fn eq(&self, other: &Self) -> bool {
crate::intrinsics::discriminant_value(self) ==
crate::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::InteriorNul { position: __self_0 }, Self::InteriorNul {
position: __arg1_0 }) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::cmp::Eq for FromBytesWithNulError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: crate::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
#[stable(feature = "core_c_str", since = "1.64.0")]
impl crate::fmt::Debug for FromBytesWithNulError {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
match self {
Self::InteriorNul { position: __self_0 } =>
crate::fmt::Formatter::debug_struct_field1_finish(f,
"InteriorNul", "position", &__self_0),
Self::NotNulTerminated =>
crate::fmt::Formatter::write_str(f, "NotNulTerminated"),
}
}
}Debug)]
128#[stable(feature = "core_c_str", since = "1.64.0")]
129pub enum FromBytesWithNulError {
130/// Data provided contains an interior nul byte at byte `position`.
131InteriorNul {
132/// The position of the interior nul byte.
133position: usize,
134 },
135/// Data provided is not nul terminated.
136NotNulTerminated,
137}
138139#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
140impl fmt::Displayfor FromBytesWithNulError {
141fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142match self {
143Self::InteriorNul { position } => {
144f.write_fmt(format_args!("data provided contains an interior nul byte at byte position {0}",
position))write!(f, "data provided contains an interior nul byte at byte position {position}")145 }
146Self::NotNulTerminated => f.write_fmt(format_args!("data provided is not nul terminated"))write!(f, "data provided is not nul terminated"),
147 }
148 }
149}
150151#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
152impl Errorfor FromBytesWithNulError {}
153154/// An error indicating that no nul byte was present.
155///
156/// A slice used to create a [`CStr`] must contain a nul byte somewhere
157/// within the slice.
158///
159/// This error is created by the [`CStr::from_bytes_until_nul`] method.
160#[derive(#[automatically_derived]
#[doc(hidden)]
#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
unsafe impl crate::clone::TrivialClone for FromBytesUntilNulError { }
#[automatically_derived]
#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
impl crate::clone::Clone for FromBytesUntilNulError {
#[inline]
fn clone(&self) -> Self {
let _: crate::clone::AssertParamIsClone<()>;
*self
}
}Clone, #[automatically_derived]
#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
impl crate::marker::Copy for FromBytesUntilNulError { }Copy, #[automatically_derived]
#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
impl crate::marker::StructuralPartialEq for FromBytesUntilNulError { }
#[automatically_derived]
#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
impl crate::cmp::PartialEq for FromBytesUntilNulError {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
impl crate::cmp::Eq for FromBytesUntilNulError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) { let _: crate::cmp::AssertParamIsEq<()>; }
}Eq, #[automatically_derived]
#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
impl crate::fmt::Debug for FromBytesUntilNulError {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_tuple_field1_finish(f,
"FromBytesUntilNulError", &&self.0)
}
}Debug)]
161#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
162pub struct FromBytesUntilNulError(());
163164#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
165impl fmt::Displayfor FromBytesUntilNulError {
166fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167f.write_fmt(format_args!("data provided does not contain a nul"))write!(f, "data provided does not contain a nul")168 }
169}
170171/// Shows the underlying bytes as a normal string, with invalid UTF-8
172/// presented as hex escape sequences.
173#[stable(feature = "cstr_debug", since = "1.3.0")]
174impl fmt::Debugfor CStr {
175fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 fmt::Debug::fmt(crate::bstr::ByteStr::from_bytes(self.to_bytes()), f)
177 }
178}
179180#[stable(feature = "cstr_default", since = "1.10.0")]
181#[rustc_const_unstable(feature = "const_default", issue = "143894")]
182const impl Defaultfor &CStr {
183#[inline]
184fn default() -> Self {
185c""
186}
187}
188189impl CStr {
190/// Wraps a raw C string with a safe C string wrapper.
191 ///
192 /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
193 /// allows inspection and interoperation of non-owned C strings. The total
194 /// size of the terminated buffer must be smaller than [`isize::MAX`] **bytes**
195 /// in memory (a restriction from [`slice::from_raw_parts`]).
196 ///
197 /// # Safety
198 ///
199 /// * The memory pointed to by `ptr` must contain a valid nul terminator at the
200 /// end of the string.
201 ///
202 /// * `ptr` must be [valid] for reads of bytes up to and including the nul terminator.
203 /// This means in particular:
204 ///
205 /// * The entire memory range of this `CStr` must be contained within a single allocation!
206 /// * `ptr` must be non-null even for a zero-length cstr.
207 ///
208 /// * The memory referenced by the returned `CStr` must not be mutated for
209 /// the duration of lifetime `'a`.
210 ///
211 /// * The nul terminator must be within `isize::MAX` from `ptr`
212 ///
213 /// > **Note**: This operation is intended to be a 0-cost cast but it is
214 /// > currently implemented with an up-front calculation of the length of
215 /// > the string. This is not guaranteed to always be the case.
216 ///
217 /// # Caveat
218 ///
219 /// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
220 /// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
221 /// such as by providing a helper function taking the lifetime of a host value for the slice,
222 /// or by explicit annotation.
223 ///
224 /// # Examples
225 ///
226 /// ```
227 /// use std::ffi::{c_char, CStr};
228 ///
229 /// fn my_string() -> *const c_char {
230 /// c"hello".as_ptr()
231 /// }
232 ///
233 /// unsafe {
234 /// let slice = CStr::from_ptr(my_string());
235 /// assert_eq!(slice.to_str().unwrap(), "hello");
236 /// }
237 /// ```
238 ///
239 /// ```
240 /// use std::ffi::{c_char, CStr};
241 ///
242 /// const HELLO_PTR: *const c_char = {
243 /// const BYTES: &[u8] = b"Hello, world!\0";
244 /// BYTES.as_ptr().cast()
245 /// };
246 /// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) };
247 ///
248 /// assert_eq!(c"Hello, world!", HELLO);
249 /// ```
250 ///
251 /// [valid]: core::ptr#safety
252#[inline] // inline is necessary for codegen to see strlen.
253#[must_use]
254 #[stable(feature = "rust1", since = "1.0.0")]
255 #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
256pub const unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
257// SAFETY: The caller has provided a pointer that points to a valid C
258 // string with a NUL terminator less than `isize::MAX` from `ptr`.
259let len = unsafe { strlen(ptr) };
260261// SAFETY: The caller has provided a valid pointer with length less than
262 // `isize::MAX`, so `from_raw_parts` is safe. The content remains valid
263 // and doesn't change for the lifetime of the returned `CStr`. This
264 // means the call to `from_bytes_with_nul_unchecked` is correct.
265 //
266 // The cast from c_char to u8 is ok because a c_char is always one byte.
267unsafe {
268Self::from_bytes_with_nul_unchecked(slice::from_raw_parts(
269ptr.cast(),
270len.as_inner() + 1,
271 ))
272 }
273 }
274275/// Creates a C string wrapper from a byte slice with any number of nuls.
276 ///
277 /// This method will create a `CStr` from any byte slice that contains at
278 /// least one nul byte. Unlike with [`CStr::from_bytes_with_nul`], the caller
279 /// does not need to know where the nul byte is located.
280 ///
281 /// If the first byte is a nul character, this method will return an
282 /// empty `CStr`. If multiple nul characters are present, the `CStr` will
283 /// end at the first one.
284 ///
285 /// If the slice only has a single nul byte at the end, this method is
286 /// equivalent to [`CStr::from_bytes_with_nul`].
287 ///
288 /// # Examples
289 /// ```
290 /// use std::ffi::CStr;
291 ///
292 /// let mut buffer = [0u8; 16];
293 /// unsafe {
294 /// // Here we might call an unsafe C function that writes a string
295 /// // into the buffer.
296 /// let buf_ptr = buffer.as_mut_ptr();
297 /// buf_ptr.write_bytes(b'A', 8);
298 /// }
299 /// // Attempt to extract a C nul-terminated string from the buffer.
300 /// let c_str = CStr::from_bytes_until_nul(&buffer[..]).unwrap();
301 /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA");
302 /// ```
303 ///
304#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
305 #[rustc_const_stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
306pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> {
307let nul_pos = memchr::memchr(0, bytes);
308match nul_pos {
309Some(nul_pos) => {
310// FIXME(const-hack) replace with range index
311 // SAFETY: nul_pos + 1 <= bytes.len()
312let subslice = unsafe { crate::slice::from_raw_parts(bytes.as_ptr(), nul_pos + 1) };
313// SAFETY: We know there is a nul byte at nul_pos, so this slice
314 // (ending at the nul byte) is a well-formed C string.
315Ok(unsafe { CStr::from_bytes_with_nul_unchecked(subslice) })
316 }
317None => Err(FromBytesUntilNulError(())),
318 }
319 }
320321/// Creates a C string wrapper from a byte slice with exactly one nul
322 /// terminator.
323 ///
324 /// This function will cast the provided `bytes` to a `CStr`
325 /// wrapper after ensuring that the byte slice is nul-terminated
326 /// and does not contain any interior nul bytes.
327 ///
328 /// If the nul byte may not be at the end,
329 /// [`CStr::from_bytes_until_nul`] can be used instead.
330 ///
331 /// # Examples
332 ///
333 /// ```
334 /// use std::ffi::CStr;
335 ///
336 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
337 /// assert_eq!(cstr, Ok(c"hello"));
338 /// ```
339 ///
340 /// Creating a `CStr` without a trailing nul terminator is an error:
341 ///
342 /// ```
343 /// use std::ffi::{CStr, FromBytesWithNulError};
344 ///
345 /// let cstr = CStr::from_bytes_with_nul(b"hello");
346 /// assert_eq!(cstr, Err(FromBytesWithNulError::NotNulTerminated));
347 /// ```
348 ///
349 /// Creating a `CStr` with an interior nul byte is an error:
350 ///
351 /// ```
352 /// use std::ffi::{CStr, FromBytesWithNulError};
353 ///
354 /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
355 /// assert_eq!(cstr, Err(FromBytesWithNulError::InteriorNul { position: 2 }));
356 /// ```
357#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
358 #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
359pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {
360let nul_pos = memchr::memchr(0, bytes);
361match nul_pos {
362Some(nul_pos) if nul_pos + 1 == bytes.len() => {
363// SAFETY: We know there is only one nul byte, at the end
364 // of the byte slice.
365Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
366 }
367Some(position) => Err(FromBytesWithNulError::InteriorNul { position }),
368None => Err(FromBytesWithNulError::NotNulTerminated),
369 }
370 }
371372/// Unsafely creates a C string wrapper from a byte slice.
373 ///
374 /// This function will cast the provided `bytes` to a `CStr` wrapper without
375 /// performing any sanity checks.
376 ///
377 /// # Safety
378 /// The provided slice **must** be nul-terminated and not contain any interior
379 /// nul bytes.
380 ///
381 /// # Examples
382 ///
383 /// ```
384 /// use std::ffi::CStr;
385 ///
386 /// let bytes = b"Hello world!\0";
387 ///
388 /// let cstr = unsafe { CStr::from_bytes_with_nul_unchecked(bytes) };
389 /// assert_eq!(cstr.to_bytes_with_nul(), bytes);
390 /// ```
391#[inline]
392 #[must_use]
393 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
394 #[rustc_const_stable(feature = "const_cstr_unchecked", since = "1.59.0")]
395 #[rustc_allow_const_fn_unstable(const_eval_select)]
396pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
397{
#[inline]
fn runtime(bytes: &[u8]) -> &CStr {
{
if true {
if !(!bytes.is_empty() && bytes[bytes.len() - 1] == 0) {
crate::panicking::panic("assertion failed: !bytes.is_empty() && bytes[bytes.len() - 1] == 0")
};
};
unsafe { &*(bytes as *const [u8] as *const CStr) }
}
}
#[inline]
const fn compiletime(bytes: &[u8]) -> &CStr {
let _ = bytes;
{
let mut i = bytes.len().saturating_sub(1);
if !(!bytes.is_empty() && bytes[i] == 0) {
{
crate::panicking::panic_fmt(format_args!("input was not nul-terminated"));
}
};
while i != 0 {
i -= 1;
let byte = bytes[i];
if !(byte != 0) {
{
crate::panicking::panic_fmt(format_args!("input contained interior nul"));
}
};
}
unsafe { &*(bytes as *const [u8] as *const CStr) }
}
}
const_eval_select((bytes,), compiletime, runtime)
}const_eval_select!(
398 @capture { bytes: &[u8] } -> &CStr:
399if const {
400// Saturating so that an empty slice panics in the assert with a good
401 // message, not here due to underflow.
402let mut i = bytes.len().saturating_sub(1);
403assert!(!bytes.is_empty() && bytes[i] == 0, "input was not nul-terminated");
404405// Ending nul byte exists, skip to the rest.
406while i != 0 {
407 i -= 1;
408let byte = bytes[i];
409assert!(byte != 0, "input contained interior nul");
410 }
411412// SAFETY: See runtime cast comment below.
413unsafe { &*(bytes as *const [u8] as *const CStr) }
414 } else {
415// Chance at catching some UB at runtime with debug builds.
416debug_assert!(!bytes.is_empty() && bytes[bytes.len() - 1] == 0);
417418// SAFETY: Casting to CStr is safe because its internal representation
419 // is a [u8] too (safe only inside std).
420 // Dereferencing the obtained pointer is safe because it comes from a
421 // reference. Making a reference is then safe because its lifetime
422 // is bound by the lifetime of the given `bytes`.
423unsafe { &*(bytes as *const [u8] as *const CStr) }
424 }
425 )426 }
427428/// Returns the inner pointer to this C string.
429 ///
430 /// The returned pointer will be valid for as long as `self` is, and points
431 /// to a contiguous region of memory terminated with a 0 byte to represent
432 /// the end of the string.
433 ///
434 /// The type of the returned pointer is
435 /// [`*const c_char`][crate::ffi::c_char], and whether it's
436 /// an alias for `*const i8` or `*const u8` is platform-specific.
437 ///
438 /// **WARNING**
439 ///
440 /// The returned pointer is read-only; writing to it (including passing it
441 /// to C code that writes to it) causes undefined behavior.
442 ///
443 /// It is your responsibility to make sure that the underlying memory is not
444 /// freed too early. For example, the following code will cause undefined
445 /// behavior when `ptr` is used inside the `unsafe` block:
446 ///
447 /// ```no_run
448 /// # #![expect(dangling_pointers_from_temporaries)]
449 /// use std::ffi::{CStr, CString};
450 ///
451 /// // 💀 The meaning of this entire program is undefined,
452 /// // 💀 and nothing about its behavior is guaranteed,
453 /// // 💀 not even that its behavior resembles the code as written,
454 /// // 💀 just because it contains a single instance of undefined behavior!
455 ///
456 /// // 🚨 creates a dangling pointer to a temporary `CString`
457 /// // 🚨 that is deallocated at the end of the statement
458 /// let ptr = CString::new("Hi!".to_uppercase()).unwrap().as_ptr();
459 ///
460 /// // without undefined behavior, you would expect that `ptr` equals:
461 /// dbg!(CStr::from_bytes_with_nul(b"HI!\0").unwrap());
462 ///
463 /// // 🙏 Possibly the program behaved as expected so far,
464 /// // 🙏 and this just shows `ptr` is now garbage..., but
465 /// // 💀 this violates `CStr::from_ptr`'s safety contract
466 /// // 💀 leading to a dereference of a dangling pointer,
467 /// // 💀 which is immediate undefined behavior.
468 /// // 💀 *BOOM*, you're dead, your entire program has no meaning.
469 /// dbg!(unsafe { CStr::from_ptr(ptr) });
470 /// ```
471 ///
472 /// This happens because, the pointer returned by `as_ptr` does not carry any
473 /// lifetime information, and the `CString` is deallocated immediately after
474 /// the expression that it is part of has been evaluated.
475 /// To fix the problem, bind the `CString` to a local variable:
476 ///
477 /// ```
478 /// use std::ffi::{CStr, CString};
479 ///
480 /// let c_str = CString::new("Hi!".to_uppercase()).unwrap();
481 /// let ptr = c_str.as_ptr();
482 ///
483 /// assert_eq!(unsafe { CStr::from_ptr(ptr) }, c"HI!");
484 /// ```
485#[inline]
486 #[must_use]
487 #[stable(feature = "rust1", since = "1.0.0")]
488 #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
489 #[rustc_as_ptr]
490 #[rustc_never_returns_null_ptr]
491pub const fn as_ptr(&self) -> *const c_char {
492self.inner.as_ptr()
493 }
494495/// We could eventually expose this publicly, if we wanted.
496#[inline]
497 #[must_use]
498const fn as_non_null_ptr(&self) -> NonNull<c_char> {
499// FIXME(const_trait_impl) replace with `NonNull::from`
500 // SAFETY: a reference is never null
501unsafe { NonNull::new_unchecked(&self.inner as *const [c_char] as *mut [c_char]) }
502 .as_non_null_ptr()
503 }
504505/// Returns the length of `self`. Like C's `strlen`, this does not include the nul terminator.
506 ///
507 /// > **Note**: This method is currently implemented as a constant-time
508 /// > cast, but it is planned to alter its definition in the future to
509 /// > perform the length calculation whenever this method is called.
510 ///
511 /// # Examples
512 ///
513 /// ```
514 /// assert_eq!(c"foo".count_bytes(), 3);
515 /// assert_eq!(c"".count_bytes(), 0);
516 /// ```
517#[inline]
518 #[must_use]
519 #[doc(alias("len", "strlen"))]
520 #[stable(feature = "cstr_count_bytes", since = "1.79.0")]
521 #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
522pub const fn count_bytes(&self) -> usize {
523// SAFETY: This length includes the nul-terminator, so it's at least one.
524unsafe { self.inner.len().unchecked_sub(1) }
525 }
526527/// Returns `true` if `self.to_bytes()` has a length of 0.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// assert!(!c"foo".is_empty());
533 /// assert!(c"".is_empty());
534 /// ```
535#[inline]
536 #[stable(feature = "cstr_is_empty", since = "1.71.0")]
537 #[rustc_const_stable(feature = "cstr_is_empty", since = "1.71.0")]
538pub const fn is_empty(&self) -> bool {
539// SAFETY: We know there is at least one byte; for empty strings it
540 // is the NUL terminator.
541 // FIXME(const-hack): use get_unchecked
542unsafe { *self.inner.as_ptr() == 0 }
543 }
544545/// Converts this C string to a byte slice.
546 ///
547 /// The returned slice will **not** contain the trailing nul terminator that this C
548 /// string has.
549 ///
550 /// > **Note**: This method is currently implemented as a constant-time
551 /// > cast, but it is planned to alter its definition in the future to
552 /// > perform the length calculation whenever this method is called.
553 ///
554 /// # Examples
555 ///
556 /// ```
557 /// assert_eq!(c"foo".to_bytes(), b"foo");
558 /// ```
559#[inline]
560 #[must_use = "this returns the result of the operation, \
561 without modifying the original"]
562 #[stable(feature = "rust1", since = "1.0.0")]
563 #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
564pub const fn to_bytes(&self) -> &[u8] {
565let bytes = self.to_bytes_with_nul();
566// FIXME(const-hack) replace with range index
567 // SAFETY: to_bytes_with_nul returns slice with length at least 1
568unsafe { slice::from_raw_parts(bytes.as_ptr(), bytes.len() - 1) }
569 }
570571/// Converts this C string to a byte slice containing the trailing 0 byte.
572 ///
573 /// This function is the equivalent of [`CStr::to_bytes`] except that it
574 /// will retain the trailing nul terminator instead of chopping it off.
575 ///
576 /// > **Note**: This method is currently implemented as a 0-cost cast, but
577 /// > it is planned to alter its definition in the future to perform the
578 /// > length calculation whenever this method is called.
579 ///
580 /// # Examples
581 ///
582 /// ```
583 /// assert_eq!(c"foo".to_bytes_with_nul(), b"foo\0");
584 /// ```
585#[inline]
586 #[must_use = "this returns the result of the operation, \
587 without modifying the original"]
588 #[stable(feature = "rust1", since = "1.0.0")]
589 #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
590pub const fn to_bytes_with_nul(&self) -> &[u8] {
591// SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s
592 // is safe on all supported targets.
593let bytes = unsafe { &*((&raw const self.inner) as *const [u8]) };
594595// SAFETY: A valid `CStr` always contains at least its trailing nul byte.
596unsafe { crate::hint::assert_unchecked(!bytes.is_empty()) };
597598bytes599 }
600601/// Iterates over the bytes in this C string.
602 ///
603 /// The returned iterator will **not** contain the trailing nul terminator
604 /// that this C string has.
605 ///
606 /// # Examples
607 ///
608 /// ```
609 /// #![feature(cstr_bytes)]
610 ///
611 /// assert!(c"foo".bytes().eq(*b"foo"));
612 /// ```
613#[inline]
614 #[unstable(feature = "cstr_bytes", issue = "112115")]
615pub fn bytes(&self) -> Bytes<'_> {
616Bytes::new(self)
617 }
618619/// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
620 ///
621 /// If the contents of the `CStr` are valid UTF-8 data, this
622 /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
623 /// it will return an error with details of where UTF-8 validation failed.
624 ///
625 /// [str]: prim@str "str"
626 ///
627 /// # Examples
628 ///
629 /// ```
630 /// assert_eq!(c"foo".to_str(), Ok("foo"));
631 /// ```
632#[stable(feature = "cstr_to_str", since = "1.4.0")]
633 #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")]
634pub const fn to_str(&self) -> Result<&str, str::Utf8Error> {
635// N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
636 // instead of in `from_ptr()`, it may be worth considering if this should
637 // be rewritten to do the UTF-8 check inline with the length calculation
638 // instead of doing it afterwards.
639str::from_utf8(self.to_bytes())
640 }
641642/// Returns an object that implements [`Display`] for safely printing a [`CStr`] that may
643 /// contain non-Unicode data.
644 ///
645 /// Behaves as if `self` were first lossily converted to a `str`, with invalid UTF-8 presented
646 /// as the Unicode replacement character: �.
647 ///
648 /// [`Display`]: fmt::Display
649 ///
650 /// # Examples
651 ///
652 /// ```
653 /// let cstr = c"Hello, world!";
654 /// println!("{}", cstr.display());
655 /// ```
656#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
657 #[must_use = "this does not display the `CStr`; \
658 it returns an object that can be displayed"]
659 #[inline]
660pub fn display(&self) -> Display<'_> {
661Display { c_str: self }
662 }
663664/// Returns the same string as a string slice `&CStr`.
665 ///
666 /// This method is redundant when used directly on `&CStr`, but
667 /// it helps dereferencing other string-like types to string slices,
668 /// for example references to `Box<CStr>` or `Arc<CStr>`.
669#[inline]
670 #[unstable(feature = "str_as_str", issue = "130366")]
671pub const fn as_c_str(&self) -> &CStr {
672self673 }
674}
675676#[stable(feature = "c_string_eq_c_str", since = "1.90.0")]
677impl PartialEq<&Self> for CStr {
678#[inline]
679fn eq(&self, other: &&Self) -> bool {
680*self == **other681 }
682683#[inline]
684fn ne(&self, other: &&Self) -> bool {
685*self != **other686 }
687}
688689// `.to_bytes()` representations are compared instead of the inner `[c_char]`s,
690// because `c_char` is `i8` (not `u8`) on some platforms.
691// That is why this is implemented manually and not derived.
692#[stable(feature = "rust1", since = "1.0.0")]
693#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
694const impl PartialOrdfor CStr {
695#[inline]
696fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
697self.to_bytes().partial_cmp(other.to_bytes())
698 }
699}
700701#[stable(feature = "rust1", since = "1.0.0")]
702#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
703const impl Ordfor CStr {
704#[inline]
705fn cmp(&self, other: &CStr) -> Ordering {
706self.to_bytes().cmp(other.to_bytes())
707 }
708}
709710#[stable(feature = "cstr_range_from", since = "1.47.0")]
711impl ops::Index<ops::RangeFrom<usize>> for CStr {
712type Output = CStr;
713714#[inline]
715fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
716let bytes = self.to_bytes_with_nul();
717// we need to manually check the starting index to account for the null
718 // byte, since otherwise we could get an empty string that doesn't end
719 // in a null.
720if index.start < bytes.len() {
721// SAFETY: Non-empty tail of a valid `CStr` is still a valid `CStr`.
722unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
723 } else {
724{
crate::panicking::panic_fmt(format_args!("index out of bounds: the len is {0} but the index is {1}",
bytes.len(), index.start));
};panic!(
725"index out of bounds: the len is {} but the index is {}",
726 bytes.len(),
727 index.start
728 );
729 }
730 }
731}
732733#[stable(feature = "new_range_from_api", since = "1.96.0")]
734impl ops::Index<range::RangeFrom<usize>> for CStr {
735type Output = CStr;
736737#[inline]
738fn index(&self, index: range::RangeFrom<usize>) -> &CStr {
739 ops::Index::index(self, ops::RangeFrom::from(index))
740 }
741}
742743#[stable(feature = "cstring_asref", since = "1.7.0")]
744#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
745const impl AsRef<CStr> for CStr {
746#[inline]
747fn as_ref(&self) -> &CStr {
748self749 }
750}
751752/// Calculate the length of a nul-terminated string. Defers to C's `strlen` when possible.
753///
754/// # Safety
755///
756/// The pointer must point to a valid buffer that contains a NUL terminator. The NUL must be
757/// located within `isize::MAX` from `ptr`.
758#[inline]
759#[unstable(feature = "cstr_internals", issue = "none")]
760#[rustc_allow_const_fn_unstable(const_eval_select)]
761const unsafe fn strlen(ptr: *const c_char) -> UsizeNoHighBitMinusOne {
762{
#[inline]
fn runtime(s: *const c_char) -> UsizeNoHighBitMinusOne {
{
unsafe extern "C" {
#[doc = r" Provided by libc or compiler_builtins."]
fn strlen(s: *const c_char)
-> usize;
}
unsafe { UsizeNoHighBitMinusOne::new_unchecked(strlen(s)) }
}
}
#[inline]
const fn compiletime(s: *const c_char) -> UsizeNoHighBitMinusOne {
let _ = s;
{
let mut len = 0;
while unsafe { *s.add(len) } != 0 { len += 1; }
UsizeNoHighBitMinusOne::new(len).unwrap()
}
}
const_eval_select((ptr,), compiletime, runtime)
}const_eval_select!(
763 @capture { s: *const c_char = ptr } -> UsizeNoHighBitMinusOne:
764if const {
765let mut len = 0;
766767// SAFETY: Outer caller has provided a pointer to a valid C string.
768while unsafe { *s.add(len) } != 0 {
769 len += 1;
770 }
771772 UsizeNoHighBitMinusOne::new(len).unwrap()
773 } else {
774unsafe extern "C" {
775/// Provided by libc or compiler_builtins.
776fn strlen(s: *const c_char) -> usize;
777 }
778779// SAFETY: Outer caller has provided a pointer to a valid C string,
780 // and its length is within bounds.
781unsafe { UsizeNoHighBitMinusOne::new_unchecked(strlen(s)) }
782 }
783 )784}
785786/// An iterator over the bytes of a [`CStr`], without the nul terminator.
787///
788/// This struct is created by the [`bytes`] method on [`CStr`].
789/// See its documentation for more.
790///
791/// [`bytes`]: CStr::bytes
792#[must_use = "iterators are lazy and do nothing unless consumed"]
793#[unstable(feature = "cstr_bytes", issue = "112115")]
794#[derive(#[automatically_derived]
#[unstable(feature = "cstr_bytes", issue = "112115")]
impl<'a> crate::clone::Clone for Bytes<'a> {
#[inline]
fn clone(&self) -> Self {
Bytes {
ptr: crate::clone::Clone::clone(&self.ptr),
phantom: crate::clone::Clone::clone(&self.phantom),
}
}
}Clone, #[automatically_derived]
#[unstable(feature = "cstr_bytes", issue = "112115")]
impl<'a> crate::fmt::Debug for Bytes<'a> {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::debug_struct_field2_finish(f, "Bytes", "ptr",
&self.ptr, "phantom", &&self.phantom)
}
}Debug)]
795pub struct Bytes<'a> {
796// since we know the string is nul-terminated, we only need one pointer
797ptr: NonNull<u8>,
798 phantom: PhantomData<&'a [c_char]>,
799}
800801#[unstable(feature = "cstr_bytes", issue = "112115")]
802unsafe impl Sendfor Bytes<'_> {}
803804#[unstable(feature = "cstr_bytes", issue = "112115")]
805unsafe impl Syncfor Bytes<'_> {}
806807impl<'a> Bytes<'a> {
808#[inline]
809fn new(s: &'a CStr) -> Self {
810Self { ptr: s.as_non_null_ptr().cast(), phantom: PhantomData }
811 }
812813#[inline]
814fn is_empty(&self) -> bool {
815// SAFETY: We uphold that the pointer is always valid to dereference
816 // by starting with a valid C string and then never incrementing beyond
817 // the nul terminator.
818unsafe { self.ptr.read() == 0 }
819 }
820}
821822#[unstable(feature = "cstr_bytes", issue = "112115")]
823impl Iteratorfor Bytes<'_> {
824type Item = u8;
825826#[inline]
827fn next(&mut self) -> Option<u8> {
828// SAFETY: We only choose a pointer from a valid C string, which must
829 // be non-null and contain at least one value. Since we always stop at
830 // the nul terminator, which is guaranteed to exist, we can assume that
831 // the pointer is non-null and valid. This lets us safely dereference
832 // it and assume that adding 1 will create a new, non-null, valid
833 // pointer.
834unsafe {
835let ret = self.ptr.read();
836if ret == 0 {
837None838 } else {
839self.ptr = self.ptr.add(1);
840Some(ret)
841 }
842 }
843 }
844845#[inline]
846fn size_hint(&self) -> (usize, Option<usize>) {
847if self.is_empty() { (0, Some(0)) } else { (1, None) }
848 }
849850#[inline]
851fn count(self) -> usize {
852// SAFETY: We always hold a valid pointer to a C string
853unsafe { strlen(self.ptr.as_ptr().cast()) }.as_inner()
854 }
855}
856857#[unstable(feature = "cstr_bytes", issue = "112115")]
858impl FusedIteratorfor Bytes<'_> {}
859860/// Helper struct for safely printing a [`CStr`] with [`format!`] and `{}`.
861///
862/// A [`CStr`] might contain non-Unicode data. This `struct` implements the
863/// [`Display`] trait in a way that mitigates that. It is created by the
864/// [`display`](CStr::display) method on [`CStr`]. This may perform lossy
865/// conversion, depending on the platform. If you would like an implementation
866/// which escapes the [`CStr`] please use [`Debug`] instead.
867///
868/// # Examples
869///
870/// ```
871/// let s = c"Hello, world!";
872/// println!("{}", s.display());
873/// ```
874///
875/// [`Display`]: fmt::Display
876/// [`format!`]: ../../../std/macro.format.html
877#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
878pub struct Display<'a> {
879 c_str: &'a CStr,
880}
881882#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
883impl fmt::Debugfor Display<'_> {
884fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885 fmt::Debug::fmt(&self.c_str, f)
886 }
887}
888889#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
890impl fmt::Displayfor Display<'_> {
891fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892 fmt::Display::fmt(crate::bstr::ByteStr::from_bytes(self.c_str.to_bytes()), f)
893 }
894}