|
8 | 8 | // option. This file may not be copied, modified, or distributed |
9 | 9 | // except according to those terms. |
10 | 10 |
|
11 | | -use borrow::{Cow, ToOwned}; |
| 11 | +use borrow::{Cow, ToOwned, Borrow}; |
12 | 12 | use boxed::Box; |
13 | 13 | use clone::Clone; |
14 | 14 | use convert::{Into, From}; |
@@ -272,6 +272,11 @@ impl fmt::Debug for CString { |
272 | 272 | } |
273 | 273 | } |
274 | 274 |
|
| 275 | +#[stable(feature = "cstr_borrow", since = "1.3.0")] |
| 276 | +impl Borrow<CStr> for CString { |
| 277 | + fn borrow(&self) -> &CStr { self } |
| 278 | +} |
| 279 | + |
275 | 280 | impl NulError { |
276 | 281 | /// Returns the position of the nul byte in the slice that was provided to |
277 | 282 | /// `CString::new`. |
@@ -444,6 +449,15 @@ impl Ord for CStr { |
444 | 449 | } |
445 | 450 | } |
446 | 451 |
|
| 452 | +#[stable(feature = "cstr_borrow", since = "1.3.0")] |
| 453 | +impl ToOwned for CStr { |
| 454 | + type Owned = CString; |
| 455 | + |
| 456 | + fn to_owned(&self) -> CString { |
| 457 | + unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) } |
| 458 | + } |
| 459 | +} |
| 460 | + |
447 | 461 | #[cfg(test)] |
448 | 462 | mod tests { |
449 | 463 | use prelude::v1::*; |
@@ -515,4 +529,28 @@ mod tests { |
515 | 529 | assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}"))); |
516 | 530 | } |
517 | 531 | } |
| 532 | + |
| 533 | + #[test] |
| 534 | + fn to_owned() { |
| 535 | + let data = b"123\0"; |
| 536 | + let ptr = data.as_ptr() as *const libc::c_char; |
| 537 | + |
| 538 | + let owned = unsafe { CStr::from_ptr(ptr).to_owned() }; |
| 539 | + assert_eq!(owned.as_bytes_with_nul(), data); |
| 540 | + } |
| 541 | + |
| 542 | + #[test] |
| 543 | + fn equal_hash() { |
| 544 | + use hash; |
| 545 | + |
| 546 | + let data = b"123\xE2\xFA\xA6\0"; |
| 547 | + let ptr = data.as_ptr() as *const libc::c_char; |
| 548 | + let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) }; |
| 549 | + |
| 550 | + let cstr_hash = hash::hash::<_, hash::SipHasher>(&cstr); |
| 551 | + let cstring_hash = |
| 552 | + hash::hash::<_, hash::SipHasher>(&CString::new(&data[..data.len() - 1]).unwrap()); |
| 553 | + |
| 554 | + assert_eq!(cstr_hash, cstring_hash); |
| 555 | + } |
518 | 556 | } |
0 commit comments