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