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