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