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