]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/c_str.rs
CStr impl stability
[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 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
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     #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
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     #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
252     pub fn into_bytes(self) -> Vec<u8> {
253         // FIXME: Once this method becomes stable, add an `impl Into<Vec<u8>> for CString`
254         let mut vec = self.inner.into_vec();
255         let _nul = vec.pop();
256         debug_assert_eq!(_nul, Some(0u8));
257         vec
258     }
259
260     /// Equivalent to the `into_bytes` function except that the returned vector
261     /// includes the trailing nul byte.
262     #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
263     pub fn into_bytes_with_nul(self) -> Vec<u8> {
264         self.inner.into_vec()
265     }
266
267     /// Returns the contents of this `CString` as a slice of bytes.
268     ///
269     /// The returned slice does **not** contain the trailing nul separator and
270     /// it is guaranteed to not have any interior nul bytes.
271     #[stable(feature = "rust1", since = "1.0.0")]
272     pub fn as_bytes(&self) -> &[u8] {
273         &self.inner[..self.inner.len() - 1]
274     }
275
276     /// Equivalent to the `as_bytes` function except that the returned slice
277     /// includes the trailing nul byte.
278     #[stable(feature = "rust1", since = "1.0.0")]
279     pub fn as_bytes_with_nul(&self) -> &[u8] {
280         &self.inner
281     }
282 }
283
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl ops::Deref for CString {
286     type Target = CStr;
287
288     fn deref(&self) -> &CStr {
289         unsafe { mem::transmute(self.as_bytes_with_nul()) }
290     }
291 }
292
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl fmt::Debug for CString {
295     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
296         fmt::Debug::fmt(&**self, f)
297     }
298 }
299
300 #[stable(feature = "cstr_debug", since = "1.3.0")]
301 impl fmt::Debug for CStr {
302     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
303         try!(write!(f, "\""));
304         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
305             try!(f.write_char(byte as char));
306         }
307         write!(f, "\"")
308     }
309 }
310
311 #[stable(feature = "cstr_borrow", since = "1.3.0")]
312 impl Borrow<CStr> for CString {
313     fn borrow(&self) -> &CStr { self }
314 }
315
316 impl NulError {
317     /// Returns the position of the nul byte in the slice that was provided to
318     /// `CString::new`.
319     #[stable(feature = "rust1", since = "1.0.0")]
320     pub fn nul_position(&self) -> usize { self.0 }
321
322     /// Consumes this error, returning the underlying vector of bytes which
323     /// generated the error in the first place.
324     #[stable(feature = "rust1", since = "1.0.0")]
325     pub fn into_vec(self) -> Vec<u8> { self.1 }
326 }
327
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl Error for NulError {
330     fn description(&self) -> &str { "nul byte found in data" }
331 }
332
333 #[stable(feature = "rust1", since = "1.0.0")]
334 impl fmt::Display for NulError {
335     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
336         write!(f, "nul byte found in provided data at position: {}", self.0)
337     }
338 }
339
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl From<NulError> for io::Error {
342     fn from(_: NulError) -> io::Error {
343         io::Error::new(io::ErrorKind::InvalidInput,
344                        "data provided contains a nul byte")
345     }
346 }
347
348 impl IntoStringError {
349     /// Consumes this error, returning original `CString` which generated the
350     /// error.
351     #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
352     pub fn into_cstring(self) -> CString {
353         self.inner
354     }
355
356     /// Access the underlying UTF-8 error that was the cause of this error.
357     #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
358     pub fn utf8_error(&self) -> Utf8Error {
359         self.error
360     }
361 }
362
363 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
364 impl Error for IntoStringError {
365     fn description(&self) -> &str {
366         Error::description(&self.error)
367     }
368 }
369
370 #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
371 impl fmt::Display for IntoStringError {
372     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
373         fmt::Display::fmt(&self.error, f)
374     }
375 }
376
377 impl CStr {
378     /// Casts a raw C string to a safe C string wrapper.
379     ///
380     /// This function will cast the provided `ptr` to the `CStr` wrapper which
381     /// allows inspection and interoperation of non-owned C strings. This method
382     /// is unsafe for a number of reasons:
383     ///
384     /// * There is no guarantee to the validity of `ptr`
385     /// * The returned lifetime is not guaranteed to be the actual lifetime of
386     ///   `ptr`
387     /// * There is no guarantee that the memory pointed to by `ptr` contains a
388     ///   valid nul terminator byte at the end of the string.
389     ///
390     /// > **Note**: This operation is intended to be a 0-cost cast but it is
391     /// > currently implemented with an up-front calculation of the length of
392     /// > the string. This is not guaranteed to always be the case.
393     ///
394     /// # Examples
395     ///
396     /// ```no_run
397     /// # fn main() {
398     /// use std::ffi::CStr;
399     /// use std::os::raw::c_char;
400     /// use std::str;
401     ///
402     /// extern {
403     ///     fn my_string() -> *const c_char;
404     /// }
405     ///
406     /// unsafe {
407     ///     let slice = CStr::from_ptr(my_string());
408     ///     println!("string returned: {}",
409     ///              str::from_utf8(slice.to_bytes()).unwrap());
410     /// }
411     /// # }
412     /// ```
413     #[stable(feature = "rust1", since = "1.0.0")]
414     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
415         let len = libc::strlen(ptr);
416         mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
417     }
418
419     /// Returns the inner pointer to this C string.
420     ///
421     /// The returned pointer will be valid for as long as `self` is and points
422     /// to a contiguous region of memory terminated with a 0 byte to represent
423     /// the end of the string.
424     #[stable(feature = "rust1", since = "1.0.0")]
425     pub fn as_ptr(&self) -> *const c_char {
426         self.inner.as_ptr()
427     }
428
429     /// Converts this C string to a byte slice.
430     ///
431     /// This function will calculate the length of this string (which normally
432     /// requires a linear amount of work to be done) and then return the
433     /// resulting slice of `u8` elements.
434     ///
435     /// The returned slice will **not** contain the trailing nul that this C
436     /// string has.
437     ///
438     /// > **Note**: This method is currently implemented as a 0-cost cast, but
439     /// > it is planned to alter its definition in the future to perform the
440     /// > length calculation whenever this method is called.
441     #[stable(feature = "rust1", since = "1.0.0")]
442     pub fn to_bytes(&self) -> &[u8] {
443         let bytes = self.to_bytes_with_nul();
444         &bytes[..bytes.len() - 1]
445     }
446
447     /// Converts this C string to a byte slice containing the trailing 0 byte.
448     ///
449     /// This function is the equivalent of `to_bytes` except that it will retain
450     /// the trailing nul instead of chopping it off.
451     ///
452     /// > **Note**: This method is currently implemented as a 0-cost cast, but
453     /// > it is planned to alter its definition in the future to perform the
454     /// > length calculation whenever this method is called.
455     #[stable(feature = "rust1", since = "1.0.0")]
456     pub fn to_bytes_with_nul(&self) -> &[u8] {
457         unsafe { mem::transmute(&self.inner) }
458     }
459
460     /// Yields a `&str` slice if the `CStr` contains valid UTF-8.
461     ///
462     /// This function will calculate the length of this string and check for
463     /// UTF-8 validity, and then return the `&str` if it's valid.
464     ///
465     /// > **Note**: This method is currently implemented to check for validity
466     /// > after a 0-cost cast, but it is planned to alter its definition in the
467     /// > future to perform the length calculation in addition to the UTF-8
468     /// > check whenever this method is called.
469     #[stable(feature = "cstr_to_str", since = "1.4.0")]
470     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
471         // NB: When CStr is changed to perform the length check in .to_bytes()
472         // instead of in from_ptr(), it may be worth considering if this should
473         // be rewritten to do the UTF-8 check inline with the length calculation
474         // instead of doing it afterwards.
475         str::from_utf8(self.to_bytes())
476     }
477
478     /// Converts a `CStr` into a `Cow<str>`.
479     ///
480     /// This function will calculate the length of this string (which normally
481     /// requires a linear amount of work to be done) and then return the
482     /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences
483     /// with `U+FFFD REPLACEMENT CHARACTER`.
484     ///
485     /// > **Note**: This method is currently implemented to check for validity
486     /// > after a 0-cost cast, but it is planned to alter its definition in the
487     /// > future to perform the length calculation in addition to the UTF-8
488     /// > check whenever this method is called.
489     #[stable(feature = "cstr_to_str", since = "1.4.0")]
490     pub fn to_string_lossy(&self) -> Cow<str> {
491         String::from_utf8_lossy(self.to_bytes())
492     }
493 }
494
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl PartialEq for CStr {
497     fn eq(&self, other: &CStr) -> bool {
498         self.to_bytes().eq(other.to_bytes())
499     }
500 }
501 #[stable(feature = "rust1", since = "1.0.0")]
502 impl Eq for CStr {}
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl PartialOrd for CStr {
505     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
506         self.to_bytes().partial_cmp(&other.to_bytes())
507     }
508 }
509 #[stable(feature = "rust1", since = "1.0.0")]
510 impl Ord for CStr {
511     fn cmp(&self, other: &CStr) -> Ordering {
512         self.to_bytes().cmp(&other.to_bytes())
513     }
514 }
515
516 #[stable(feature = "cstr_borrow", since = "1.3.0")]
517 impl ToOwned for CStr {
518     type Owned = CString;
519
520     fn to_owned(&self) -> CString {
521         unsafe { CString::from_vec_unchecked(self.to_bytes().to_vec()) }
522     }
523 }
524
525 #[stable(feature = "cstring_asref", since = "1.7.0")]
526 impl<'a> From<&'a CStr> for CString {
527     fn from(s: &'a CStr) -> CString {
528         s.to_owned()
529     }
530 }
531
532 #[stable(feature = "cstring_asref", since = "1.7.0")]
533 impl ops::Index<ops::RangeFull> for CString {
534     type Output = CStr;
535
536     #[inline]
537     fn index(&self, _index: ops::RangeFull) -> &CStr {
538         self
539     }
540 }
541
542 #[stable(feature = "cstring_asref", since = "1.7.0")]
543 impl AsRef<CStr> for CStr {
544     fn as_ref(&self) -> &CStr {
545         self
546     }
547 }
548
549 #[stable(feature = "cstring_asref", since = "1.7.0")]
550 impl AsRef<CStr> for CString {
551     fn as_ref(&self) -> &CStr {
552         self
553     }
554 }
555
556 #[cfg(test)]
557 mod tests {
558     use prelude::v1::*;
559     use super::*;
560     use os::raw::c_char;
561     use borrow::Cow::{Borrowed, Owned};
562     use hash::{SipHasher, Hash, Hasher};
563
564     #[test]
565     fn c_to_rust() {
566         let data = b"123\0";
567         let ptr = data.as_ptr() as *const c_char;
568         unsafe {
569             assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
570             assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
571         }
572     }
573
574     #[test]
575     fn simple() {
576         let s = CString::new("1234").unwrap();
577         assert_eq!(s.as_bytes(), b"1234");
578         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
579     }
580
581     #[test]
582     fn build_with_zero1() {
583         assert!(CString::new(&b"\0"[..]).is_err());
584     }
585     #[test]
586     fn build_with_zero2() {
587         assert!(CString::new(vec![0]).is_err());
588     }
589
590     #[test]
591     fn build_with_zero3() {
592         unsafe {
593             let s = CString::from_vec_unchecked(vec![0]);
594             assert_eq!(s.as_bytes(), b"\0");
595         }
596     }
597
598     #[test]
599     fn formatted() {
600         let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
601         assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
602     }
603
604     #[test]
605     fn borrowed() {
606         unsafe {
607             let s = CStr::from_ptr(b"12\0".as_ptr() as *const _);
608             assert_eq!(s.to_bytes(), b"12");
609             assert_eq!(s.to_bytes_with_nul(), b"12\0");
610         }
611     }
612
613     #[test]
614     fn to_str() {
615         let data = b"123\xE2\x80\xA6\0";
616         let ptr = data.as_ptr() as *const c_char;
617         unsafe {
618             assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
619             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
620         }
621         let data = b"123\xE2\0";
622         let ptr = data.as_ptr() as *const c_char;
623         unsafe {
624             assert!(CStr::from_ptr(ptr).to_str().is_err());
625             assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
626         }
627     }
628
629     #[test]
630     fn to_owned() {
631         let data = b"123\0";
632         let ptr = data.as_ptr() as *const c_char;
633
634         let owned = unsafe { CStr::from_ptr(ptr).to_owned() };
635         assert_eq!(owned.as_bytes_with_nul(), data);
636     }
637
638     #[test]
639     fn equal_hash() {
640         let data = b"123\xE2\xFA\xA6\0";
641         let ptr = data.as_ptr() as *const c_char;
642         let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };
643
644         let mut s = SipHasher::new_with_keys(0, 0);
645         cstr.hash(&mut s);
646         let cstr_hash = s.finish();
647         let mut s = SipHasher::new_with_keys(0, 0);
648         CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
649         let cstring_hash = s.finish();
650
651         assert_eq!(cstr_hash, cstring_hash);
652     }
653 }