Text of rust.docs.kernel.org › src › core › ffi › c_str.rs.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

c_str.rs - source

Skip to main content core/ffi/ c_str.rs 1 //! [`CStr`] and its related types. 2 3 use crate ::cmp::Ordering ; 4 use crate ::error::Error ; 5 use crate ::ffi::c_char ; 6 use crate ::intrinsics::const_eval_select ; 7 use crate ::iter::FusedIterator ; 8 use crate ::marker::PhantomData ; 9 use crate ::num::niche_types::UsizeNoHighBitMinusOne ; 10 use crate ::ptr::NonNull ; 11 use crate ::slice::memchr ; 12 use crate ::{ fmt , ops , range , slice , str }; 13 14 // 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 18 19 /// 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( Hash )] 93 #[derive_const( PartialEq , 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)] 104 pub 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. 109 inner: [ c_char ], 110 } 111 112 /// 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( Clone , Copy , PartialEq , Eq , Debug )] 128 #[stable(feature = "core_c_str" , since = "1.64.0" )] 129 pub enum FromBytesWithNulError { 130 /// Data provided contains an interior nul byte at byte `position`.

131 InteriorNul { 132 /// The position of the interior nul byte. 133 position: usize , 134 }, 135 /// Data provided is not nul terminated. 136 NotNulTerminated, 137 } 138 139 #[stable(feature = "frombyteswithnulerror_impls" , since = "1.17.0" )] 140 impl fmt::Display for FromBytesWithNulError { 141 fn fmt( & self , f: &mut fmt:: Formatter < '_ >) -> fmt:: Result { 142 match self { 143 Self :: InteriorNul { position } => { 144 write! ( f , "data provided contains an interior nul byte at byte position {position}" ) 145 } 146 Self :: NotNulTerminated => write! ( f , "data provided is not nul terminated" ), 147 } 148 } 149 } 150 151 #[stable(feature = "frombyteswithnulerror_impls" , since = "1.17.0" )] 152 impl Error for FromBytesWithNulError {} 153 154 /// 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( Clone , Copy , PartialEq , Eq , Debug )] 161 #[stable(feature = "cstr_from_bytes_until_nul" , since = "1.69.0" )] 162 pub struct FromBytesUntilNulError (()); 163 164 #[stable(feature = "cstr_from_bytes_until_nul" , since = "1.69.0" )] 165 impl fmt::Display for FromBytesUntilNulError { 166 fn fmt( & self , f: &mut fmt:: Formatter < '_ >) -> fmt:: Result { 167 write! ( f , "data provided does not contain a nul" ) 168 } 169 } 170 171 /// 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" )] 174 impl fmt::Debug for CStr { 175 fn fmt( & self , f: &mut fmt:: Formatter < '_ >) -> fmt:: Result { 176 fmt::Debug:: fmt ( crate ::bstr:: ByteStr :: from_bytes ( self . to_bytes ()), f ) 177 } 178 } 179 180 #[stable(feature = "cstr_default" , since = "1.10.0" )] 181 #[rustc_const_unstable(feature = "const_default" , issue = "143894" )] 182 const impl Default for & CStr { 183 #[inline] 184 fn default() -> Self { 185 c"" 186 } 187 } 188 189 impl 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

The rest of this page is on the live site.