]> git.proxmox.com Git - rustc.git/blob - src/libstd/ffi/c_str.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / libstd / ffi / c_str.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use ascii;
12 use borrow::{Cow, ToOwned, Borrow};
13 use boxed::Box;
14 use convert::{Into, From};
15 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
16 use error::Error;
17 use fmt::{self, Write};
18 use io;
19 use iter::Iterator;
20 use libc;
21 use mem;
22 use memchr;
23 use ops;
24 use option::Option::{self, Some, None};
25 use os::raw::c_char;
26 use result::Result::{self, Ok, Err};
27 use slice;
28 use str::{self, Utf8Error};
29 use string::String;
30 use vec::Vec;
31
32 /// A type representing an owned C-compatible string
33 ///
34 /// This type serves the primary purpose of being able to safely generate a
35 /// C-compatible string from a Rust byte slice or vector. An instance of this
36 /// type is a static guarantee that the underlying bytes contain no interior 0
37 /// bytes and the final byte is 0.
38 ///
39 /// A `CString` is created from either a byte slice or a byte vector. After
40 /// being created, a `CString` predominately inherits all of its methods from
41 /// the `Deref` implementation to `[c_char]`. Note that the underlying array
42 /// is represented as an array of `c_char` as opposed to `u8`. A `u8` slice
43 /// can be obtained with the `as_bytes` method. Slices produced from a `CString`
44 /// do *not* contain the trailing nul terminator unless otherwise specified.
45 ///
46 /// # Examples
47 ///
48 /// ```no_run
49 /// # fn main() {
50 /// use std::ffi::CString;
51 /// use std::os::raw::c_char;
52 ///
53 /// extern {
54 /// fn my_printer(s: *const c_char);
55 /// }
56 ///
57 /// let c_to_print = CString::new("Hello, world!").unwrap();
58 /// unsafe {
59 /// my_printer(c_to_print.as_ptr());
60 /// }
61 /// # }
62 /// ```
63 ///
64 /// # Safety
65 ///
66 /// `CString` is intended for working with traditional C-style strings
67 /// (a sequence of non-null bytes terminated by a single null byte); the
68 /// primary use case for these kinds of strings is interoperating with C-like
69 /// code. Often you will need to transfer ownership to/from that external
70 /// code. It is strongly recommended that you thoroughly read through the
71 /// documentation of `CString` before use, as improper ownership management
72 /// of `CString` instances can lead to invalid memory accesses, memory leaks,
73 /// and other memory errors.
74
75 #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct CString {
78 inner: Box<[u8]>,
79 }
80
81 /// Representation of a borrowed C string.
82 ///
83 /// This dynamically sized type is only safely constructed via a borrowed
84 /// version of an instance of `CString`. This type can be constructed from a raw
85 /// C string as well and represents a C string borrowed from another location.
86 ///
87 /// Note that this structure is **not** `repr(C)` and is not recommended to be
88 /// placed in the signatures of FFI functions. Instead safe wrappers of FFI
89 /// functions may leverage the unsafe `from_ptr` constructor to provide a safe
90 /// interface to other consumers.
91 ///
92 /// # Examples
93 ///
94 /// Inspecting a foreign C string
95 ///
96 /// ```no_run
97 /// use std::ffi::CStr;
98 /// use std::os::raw::c_char;
99 ///
100 /// extern { fn my_string() -> *const c_char; }
101 ///
102 /// fn main() {
103 /// unsafe {
104 /// let slice = CStr::from_ptr(my_string());
105 /// println!("string length: {}", slice.to_bytes().len());
106 /// }
107 /// }
108 /// ```
109 ///
110 /// Passing a Rust-originating C string
111 ///
112 /// ```no_run
113 /// use std::ffi::{CString, CStr};
114 /// use std::os::raw::c_char;
115 ///
116 /// fn work(data: &CStr) {
117 /// extern { fn work_with(data: *const c_char); }
118 ///
119 /// unsafe { work_with(data.as_ptr()) }
120 /// }
121 ///
122 /// fn main() {
123 /// let s = CString::new("data data data data").unwrap();
124 /// work(&s);
125 /// }
126 /// ```
127 ///
128 /// Converting a foreign C string into a Rust `String`
129 ///
130 /// ```no_run
131 /// use std::ffi::CStr;
132 /// use std::os::raw::c_char;
133 ///
134 /// extern { fn my_string() -> *const c_char; }
135 ///
136 /// fn my_string_safe() -> String {
137 /// unsafe {
138 /// CStr::from_ptr(my_string()).to_string_lossy().into_owned()
139 /// }
140 /// }
141 ///
142 /// fn main() {
143 /// println!("string: {}", my_string_safe());
144 /// }
145 /// ```
146 #[derive(Hash)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct CStr {
149 // FIXME: this should not be represented with a DST slice but rather with
150 // just a raw `c_char` along with some form of marker to make
151 // this an unsized type. Essentially `sizeof(&CStr)` should be the
152 // same as `sizeof(&c_char)` but `CStr` should be an unsized type.
153 inner: [c_char]
154 }
155
156 /// An error returned from `CString::new` to indicate that a nul byte was found
157 /// in the vector provided.
158 #[derive(Clone, PartialEq, Debug)]
159 #[stable(feature = "rust1", since = "1.0.0")]
160 pub struct NulError(usize, Vec<u8>);
161
162 /// An error returned from `CString::into_string` to indicate that a UTF-8 error
163 /// was encountered during the conversion.
164 #[derive(Clone, PartialEq, Debug)]
165 #[stable(feature = "cstring_into", since = "1.7.0")]
166 pub struct IntoStringError {
167 inner: CString,
168 error: Utf8Error,
169 }
170
171 impl CString {
172 /// Creates a new C-compatible string from a container of bytes.
173 ///
174 /// This method will consume the provided data and use the underlying bytes
175 /// to construct a new string, ensuring that there is a trailing 0 byte.
176 ///
177 /// # Examples
178 ///
179 /// ```no_run
180 /// use std::ffi::CString;
181 /// use std::os::raw::c_char;
182 ///
183 /// extern { fn puts(s: *const c_char); }
184 ///
185 /// fn main() {
186 /// let to_print = CString::new("Hello!").unwrap();
187 /// unsafe {
188 /// puts(to_print.as_ptr());
189 /// }
190 /// }
191 /// ```
192 ///
193 /// # Errors
194 ///
195 /// This function will return an error if the bytes yielded contain an
196 /// internal 0 byte. The error returned will contain the bytes as well as
197 /// the position of the nul byte.
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
200 Self::_new(t.into())
201 }
202
203 fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
204 match memchr::memchr(0, &bytes) {
205 Some(i) => Err(NulError(i, bytes)),
206 None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
207 }
208 }
209
210 /// Creates a C-compatible string from a byte vector without checking for
211 /// interior 0 bytes.
212 ///
213 /// This method is equivalent to `new` except that no runtime assertion
214 /// is made that `v` contains no 0 bytes, and it requires an actual
215 /// byte vector, not anything that can be converted to one with Into.
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
218 v.push(0);
219 CString { inner: v.into_boxed_slice() }
220 }
221
222 /// Retakes ownership of a `CString` that was transferred to C.
223 ///
224 /// This should only ever be called with a pointer that was earlier
225 /// obtained by calling `into_raw` on a `CString`. Additionally, the length
226 /// of the string will be recalculated from the pointer.
227 #[stable(feature = "cstr_memory", since = "1.4.0")]
228 pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
229 let len = libc::strlen(ptr) + 1; // Including the NUL byte
230 let slice = slice::from_raw_parts(ptr, len as usize);
231 CString { inner: mem::transmute(slice) }
232 }
233
234 /// Transfers ownership of the string to a C caller.
235 ///
236 /// The pointer must be returned to Rust and reconstituted using
237 /// `from_raw` to be properly deallocated. Specifically, one
238 /// should *not* use the standard C `free` function to deallocate
239 /// this string.
240 ///
241 /// Failure to call `from_raw` will lead to a memory leak.
242 #[stable(feature = "cstr_memory", since = "1.4.0")]
243 pub fn into_raw(self) -> *mut c_char {
244 Box::into_raw(self.inner) as *mut c_char
245 }
246
247 /// Converts the `CString` into a `String` if it contains valid Unicode data.
248 ///
249 /// On failure, ownership of the original `CString` is returned.
250 #[stable(feature = "cstring_into", since = "1.7.0")]
251 pub fn into_string(self) -> Result<String, IntoStringError> {
252 String::from_utf8(self.into_bytes())
253 .map_err(|e| IntoStringError {
254 error: e.utf8_error(),
255 inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
256 })
257 }
258
259 /// Returns the underlying byte buffer.
260 ///
261 /// The returned buffer does **not** contain the trailing nul separator and
262 /// it is guaranteed to not have any interior nul bytes.
263 #[stable(feature = "cstring_into", since = "1.7.0")]
264 pub fn into_bytes(self) -> Vec<u8> {
265 let mut vec = self.inner.into_vec();
266 let _nul = vec.pop();
267 debug_assert_eq!(_nul, Some(0u8));
268 vec
269 }
270
271 /// Equivalent to the `into_bytes` function except that the returned vector
272 /// includes the trailing nul byte.
273 #[stable(feature = "cstring_into", since = "1.7.0")]
274 pub fn into_bytes_with_nul(self) -> Vec<u8> {
275 self.inner.into_vec()
276 }
277
278 /// Returns the contents of this `CString` as a slice of bytes.
279 ///
280 /// The returned slice does **not** contain the trailing nul separator and
281 /// it is guaranteed to not have any interior nul bytes.
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn as_bytes(&self) -> &[u8] {
284 &self.inner[..self.inner.len() - 1]
285 }
286
287 /// Equivalent to the `as_bytes` function except that the returned slice
288 /// includes the trailing nul byte.
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn as_bytes_with_nul(&self) -> &[u8] {
291 &self.inner
292 }
293 }
294
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl ops::Deref for CString {
297 type Target = CStr;
298
299 fn deref(&self) -> &CStr {
300 unsafe { mem::transmute(self.as_bytes_with_nul()) }
301 }
302 }
303
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl fmt::Debug for CString {
306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307 fmt::Debug::fmt(&**self, f)
308 }
309 }
310
311 #[stable(feature = "cstring_into", since = "1.7.0")]
312 impl From<CString> for Vec<u8> {
313 fn from(s: CString) -> Vec<u8> {
314 s.into_bytes()
315 }
316 }
317
318 #[stable(feature = "cstr_debug", since = "1.3.0")]
319 impl fmt::Debug for CStr {
320 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
321 write!(f, "\"")?;
322 for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
323 f.write_char(byte as char)?;
324 }
325 write!(f, "\"")
326 }
327 }
328
329 #[stable(feature = "cstr_borrow", since = "1.3.0")]
330 impl Borrow<CStr> for CString {
331 fn borrow(&self) -> &CStr { self }
332 }
333
334 impl NulError {
335 /// Returns the position of the nul byte in the slice that was provided to
336 /// `CString::new`.
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn nul_position(&self) -> usize { self.0 }
339
340 /// Consumes this error, returning the underlying vector of bytes which
341 /// generated the error in the first place.
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub fn into_vec(self) -> Vec<u8> { self.1 }
344 }
345
346 #[stable(feature = "rust1", since = "1.0.0")]
347 impl Error for NulError {
348 fn description(&self) -> &str { "nul byte found in data" }
349 }
350
351 #[stable(feature = "rust1", since = "1.0.0")]
352 impl fmt::Display for NulError {
353 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
354 write!(f, "nul byte found in provided data at position: {}", self.0)
355 }
356 }
357
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl From<NulError> for io::Error {
360 fn from(_: NulError) -> io::Error {
361 io::Error::new(io::ErrorKind::InvalidInput,
362 "data provided contains a nul byte")
363 }
364 }
365
366 impl IntoStringError {
367 /// Consumes this error, returning original `CString` which generated the
368 /// error.
369 #[stable(feature = "cstring_into", since = "1.7.0")]
370 pub fn into_cstring(self) -> CString {
371 self.inner
372 }
373
374 /// Access the underlying UTF-8 error that was the cause of this error.
375 #[stable(feature = "cstring_into", since = "1.7.0")]
376 pub fn utf8_error(&self) -> Utf8Error {
377 self.error
378 }
379 }
380
381 #[stable(feature = "cstring_into", since = "1.7.0")]
382 impl Error for IntoStringError {
383 fn description(&self) -> &str {
384 "C string contained non-utf8 bytes"
385 }
386
387 fn cause(&self) -> Option<&Error> {
388 Some(&self.error)
389 }
390 }
391
392 #[stable(feature = "cstring_into", since = "1.7.0")]
393 impl fmt::Display for IntoStringError {
394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
395 self.description().fmt(f)
396 }
397 }
398
399 impl CStr {
400 /// Casts a raw C string to a safe C string wrapper.
401 ///
402 /// This function will cast the provided `ptr` to the `CStr` wrapper which
403 /// allows inspection and interoperation of non-owned C strings. This method
404 /// is unsafe for a number of reasons:
405 ///
406 /// * There is no guarantee to the validity of `ptr`
407 /// * The returned lifetime is not guaranteed to be the actual lifetime of
408 /// `ptr`
409 /// * There is no guarantee that the memory pointed to by `ptr` contains a
410 /// valid nul terminator byte at the end of the string.
411 ///
412 /// > **Note**: This operation is intended to be a 0-cost cast but it is
413 /// > currently implemented with an up-front calculation of the length of
414 /// > the string. This is not guaranteed to always be the case.
415 ///
416 /// # Examples
417 ///
418 /// ```no_run
419 /// # fn main() {
420 /// use std::ffi::CStr;
421 /// use std::os::raw::c_char;
422 ///
423 /// extern {
424 /// fn my_string() -> *const c_char;
425 /// }
426 ///
427 /// unsafe {
428 /// let slice = CStr::from_ptr(my_string());
429 /// println!("string returned: {}", slice.to_str().unwrap());
430 /// }
431 /// # }
432 /// ```
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
435 let len = libc::strlen(ptr);
436 mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
437 }
438
439 /// Creates a C string wrapper from a byte slice.
440 ///
441 /// This function will cast the provided `bytes` to a `CStr` wrapper after
442 /// ensuring that it is null terminated and does not contain any interior
443 /// nul bytes.
444 ///
445 /// # Examples
446 ///
447 /// ```
448 /// # #![feature(cstr_from_bytes)]
449 /// use std::ffi::CStr;
450 ///
451 /// # fn main() {
452 /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
453 /// assert!(cstr.is_some());
454 /// # }
455 /// ```
456 #[unstable(feature = "cstr_from_bytes", reason = "recently added", issue = "31190")]
457 pub fn from_bytes_with_nul(bytes: &[u8]) -> Option<&CStr> {
458 if bytes.is_empty() || memchr::memchr(0, &bytes) != Some(bytes.len() - 1) {
459 None
460 } else {
461 Some(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
462 }
463 }
464
465 /// Unsafely creates a C string wrapper from a byte slice.
466 ///
467 /// This function will cast the provided `bytes` to a `CStr` wrapper without
468 /// performing any sanity checks. The provided slice must be null terminated
469 /// and not contain any interior nul bytes.
470 ///
471 /// # Examples
472 ///
473 /// ```
474 /// # #![feature(cstr_from_bytes)]
475 /// use std::ffi::{CStr, CString};
476 ///
477 /// # fn main() {
478 /// unsafe {
479 /// let cstring = CString::new("hello").unwrap();
480 /// let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
481 /// assert_eq!(cstr, &*cstring);
482 /// }
483 /// # }
484 /// ```
485 #[unstable(feature = "cstr_from_bytes", reason = "recently added", issue = "31190")]
486 pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
487 mem::transmute(bytes)
488 }
489
490 /// Returns the inner pointer to this C string.
491 ///
492 /// The returned pointer will be valid for as long as `self` is and points
493 /// to a contiguous region of memory terminated with a 0 byte to represent
494 /// the end of the string.
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn as_ptr(&self) -> *const c_char {
497 self.inner.as_ptr()
498 }
499
500 /// Converts this C string to a byte slice.
501 ///
502 /// This function will calculate the length of this string (which normally
503 /// requires a linear amount of work to be done) and then return the
504 /// resulting slice of `u8` elements.
505 ///
506 /// The returned slice will **not** contain the trailing nul that this C
507 /// string has.
508 ///
509 /// > **Note**: This method is currently implemented as a 0-cost cast, but
510 /// > it is planned to alter its definition in the future to perform the
511 /// > length calculation whenever this method is called.
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn to_bytes(&self) -> &[u8] {
514 let bytes = self.to_bytes_with_nul();
515 &bytes[..bytes.len() - 1]
516 }
517
518 /// Converts this C string to a byte slice containing the trailing 0 byte.
519 ///
520 /// This function is the equivalent of `to_bytes` except that it will retain
521 /// the trailing nul instead of chopping it off.
522 ///
523 /// > **Note**: This method is currently implemented as a 0-cost cast, but
524 /// > it is planned to alter its definition in the future to perform the
525 /// > length calculation whenever this method is called.
526 #[stable(feature = "rust1", since = "1.0.0")]
527 pub fn to_bytes_with_nul(&self) -> &[u8] {
528 unsafe { mem::transmute(&self.inner) }
529 }
530
531 /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
532 ///
533 /// This function will calculate the length of this string and check for
534 /// UTF-8 validity, and then return the `&str` if it's valid.
535 ///
536 /// > **Note**: This method is currently implemented to check for validity
537 /// > after a 0-cost cast, but it is planned to alter its definition in the
538 /// > future to perform the length calculation in addition to the UTF-8
539 /// > check whenever this method is called.
540 #[stable(feature = "cstr_to_str", since = "1.4.0")]
541 pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
542 // NB: When CStr is changed to perform the length check in .to_bytes()
543 // instead of in from_ptr(), it may be worth considering if this should
544 // be rewritten to do the UTF-8 check inline with the length calculation
545 // instead of doing it afterwards.
546 str::from_utf8(self.to_bytes())
547 }
548
549 /// Converts a `CStr` into a `Cow<str>`.
550 ///
551 /// This function will calculate the length of this string (which normally
552 /// requires a linear amount of work to be done) and then return the
553 /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
554 /// with `U+FFFD REPLACEMENT CHARACTER`.
555 ///
556 /// > **Note**: This method is currently implemented to check for validity
557 /// > after a 0-cost cast, but it is planned to alter its definition in the
558 /// > future to perform the length calculation in addition to the UTF-8
559 /// > check whenever this method is called.
560 #[stable(feature = "cstr_to_str", since = "1.4.0")]
561 pub fn to_string_lossy(&self) -> Cow<str> {
562 String::from_utf8_lossy(self.to_bytes())
563 }
564 }
565
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl PartialEq for CStr {
568 fn eq(&self, other: &CStr) -> bool {
569 self.to_bytes().eq(other.to_bytes())
570 }
571 }
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl Eq for CStr {}
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl PartialOrd for CStr {
576 fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
577 self.to_bytes().partial_cmp(&other.to_bytes())
578 }
579 }
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl Ord for CStr {
582 fn cmp(&self, other: &CStr) -> Ordering {
583 self.to_bytes().cmp(&other.to_bytes())
584 }
585 }
586
587 #[stable(feature = "cstr_borrow", since = "1.3.0")]
588 impl ToOwned for CStr {
589 type Owned = CString;
590
591 fn to_owned(&self) -> CString {
592 unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
593 }
594 }
595
596 #[stable(feature = "cstring_asref", since = "1.7.0")]
597 impl<'a> From<&'a CStr> for CString {
598 fn from(s: &'a CStr) -> CString {
599 s.to_owned()
600 }
601 }
602
603 #[stable(feature = "cstring_asref", since = "1.7.0")]
604 impl ops::Index<ops::RangeFull> for CString {
605 type Output = CStr;
606
607 #[inline]
608 fn index(&self, _index: ops::RangeFull) -> &CStr {
609 self
610 }
611 }
612
613 #[stable(feature = "cstring_asref", since = "1.7.0")]
614 impl AsRef<CStr> for CStr {
615 fn as_ref(&self) -> &CStr {
616 self
617 }
618 }
619
620 #[stable(feature = "cstring_asref", since = "1.7.0")]
621 impl AsRef<CStr> for CString {
622 fn as_ref(&self) -> &CStr {
623 self
624 }
625 }
626
627 #[cfg(test)]
628 mod tests {
629 use prelude::v1::*;
630 use super::*;
631 use os::raw::c_char;
632 use borrow::Cow::{Borrowed, Owned};
633 use hash::{SipHasher, Hash, Hasher};
634
635 #[test]
636 fn c_to_rust() {
637 let data = b"123\0";
638 let ptr = data.as_ptr() as *const c_char;
639 unsafe {
640 assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
641 assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
642 }
643 }
644
645 #[test]
646 fn simple() {
647 let s = CString::new("1234").unwrap();
648 assert_eq!(s.as_bytes(), b"1234");
649 assert_eq!(s.as_bytes_with_nul(), b"1234\0");
650 }
651
652 #[test]
653 fn build_with_zero1() {
654 assert!(CString::new(&b"\0"[..]).is_err());
655 }
656 #[test]
657 fn build_with_zero2() {
658 assert!(CString::new(vec![0]).is_err());
659 }
660
661 #[test]
662 fn build_with_zero3() {
663 unsafe {
664 let s = CString::from_vec_unchecked(vec![0]);
665 assert_eq!(s.as_bytes(), b"\0");
666 }
667 }
668
669 #[test]
670 fn formatted() {
671 let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
672 assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
673 }
674
675 #[test]
676 fn borrowed() {
677 unsafe {
678 let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
679 assert_eq!(s.to_bytes(), b"12");
680 assert_eq!(s.to_bytes_with_nul(), b"12\0");
681 }
682 }
683
684 #[test]
685 fn to_str() {
686 let data = b"123\xE2\x80\xA6\0";
687 let ptr = data.as_ptr() as *const c_char;
688 unsafe {
689 assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
690 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
691 }
692 let data = b"123\xE2\0";
693 let ptr = data.as_ptr() as *const c_char;
694 unsafe {
695 assert!(CStr::from_ptr(ptr).to_str().is_err());
696 assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
697 }
698 }
699
700 #[test]
701 fn to_owned() {
702 let data = b"123\0";
703 let ptr = data.as_ptr() as *const c_char;
704
705 let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
706 assert_eq!(owned.as_bytes_with_nul(), data);
707 }
708
709 #[test]
710 fn equal_hash() {
711 let data = b"123\xE2\xFA\xA6\0";
712 let ptr = data.as_ptr() as *const c_char;
713 let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
714
715 let mut s = SipHasher::new_with_keys(0, 0);
716 cstr.hash(&mut s);
717 let cstr_hash = s.finish();
718 let mut s = SipHasher::new_with_keys(0, 0);
719 CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
720 let cstring_hash = s.finish();
721
722 assert_eq!(cstr_hash, cstring_hash);
723 }
724
725 #[test]
726 fn from_bytes_with_nul() {
727 let data = b"123\0";
728 let cstr = CStr::from_bytes_with_nul(data);
729 assert_eq!(cstr.map(CStr::to_bytes), Some(&b"123"[..]));
730 assert_eq!(cstr.map(CStr::to_bytes_with_nul), Some(&b"123\0"[..]));
731
732 unsafe {
733 let cstr_unchecked = CStr::from_bytes_with_nul_unchecked(data);
734 assert_eq!(cstr, Some(cstr_unchecked));
735 }
736 }
737
738 #[test]
739 fn from_bytes_with_nul_unterminated() {
740 let data = b"123";
741 let cstr = CStr::from_bytes_with_nul(data);
742 assert!(cstr.is_none());
743 }
744
745 #[test]
746 fn from_bytes_with_nul_interior() {
747 let data = b"1\023\0";
748 let cstr = CStr::from_bytes_with_nul(data);
749 assert!(cstr.is_none());
750 }
751 }