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.
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.
13 C-string manipulation and management
15 This modules provides the basic methods for creating and manipulating
16 null-terminated strings for use with FFI calls (back to C). Most C APIs require
17 that the string being passed to them is null-terminated, and by default rust's
18 string types are *not* null terminated.
20 The other problem with translating Rust strings to C strings is that Rust
21 strings can validly contain a null-byte in the middle of the string (0 is a
22 valid unicode codepoint). This means that not all Rust strings can actually be
23 translated to C strings.
25 # Creation of a C string
27 A C string is managed through the `CString` type defined in this module. It
28 "owns" the internal buffer of characters and will automatically deallocate the
29 buffer when the string is dropped. The `ToCStr` trait is implemented for `&str`
30 and `&[u8]`, but the conversions can fail due to some of the limitations
33 This also means that currently whenever a C string is created, an allocation
34 must be performed to place the data elsewhere (the lifetime of the C string is
35 not tied to the lifetime of the original string/data buffer). If C strings are
36 heavily used in applications, then caching may be advisable to prevent
37 unnecessary amounts of allocations.
39 An example of creating and using a C string would be:
45 fn puts(s: *const libc::c_char);
49 let my_string = "Hello, world!";
51 // Allocate the C string with an explicit local that owns the string. The
52 // `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope.
53 let my_c_string = my_string.to_c_str();
55 puts(my_c_string.as_ptr());
58 // Don't save/return the pointer to the C string, the `c_buffer` will be
59 // deallocated when this block returns!
60 my_string.with_c_str(|c_buffer| {
61 unsafe { puts(c_buffer); }
70 use alloc::libc_heap::malloc_raw;
71 use collections::string::String;
72 use core::kinds::marker;
80 /// The representation of a C String.
82 /// This structure wraps a `*libc::c_char`, and will automatically free the
83 /// memory it is pointing to when it goes out of scope.
85 buf: *const libc::c_char,
89 impl Clone for CString {
90 /// Clone this CString into a new, uniquely owned CString. For safety
91 /// reasons, this is always a deep clone, rather than the usual shallow
93 fn clone(&self) -> CString {
94 if self.buf.is_null() {
95 CString { buf: self.buf, owns_buffer_: self.owns_buffer_ }
97 let len = self.len() + 1;
98 let buf = unsafe { malloc_raw(len) } as *mut libc::c_char;
99 unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); }
100 CString { buf: buf as *const libc::c_char, owns_buffer_: true }
105 impl PartialEq for CString {
106 fn eq(&self, other: &CString) -> bool {
107 if self.buf as uint == other.buf as uint {
109 } else if self.buf.is_null() || other.buf.is_null() {
113 libc::strcmp(self.buf, other.buf) == 0
120 /// Create a C String from a pointer.
121 pub unsafe fn new(buf: *const libc::c_char, owns_buffer: bool) -> CString {
122 CString { buf: buf, owns_buffer_: owns_buffer }
125 /// Return a pointer to the NUL-terminated string data.
127 /// `.as_ptr` returns an internal pointer into the `CString`, and
128 /// may be invalidated when the `CString` falls out of scope (the
129 /// destructor will run, freeing the allocation if there is
133 /// let foo = "some string";
136 /// let x = foo.to_c_str();
137 /// let p = x.as_ptr();
139 /// // wrong (the CString will be freed, invalidating `p`)
140 /// let p = foo.to_c_str().as_ptr();
145 /// Fails if the CString is null.
150 /// extern crate libc;
153 /// let c_str = "foo bar".to_c_str();
155 /// libc::puts(c_str.as_ptr());
159 pub fn as_ptr(&self) -> *const libc::c_char {
160 if self.buf.is_null() { fail!("CString is null!"); }
165 /// Return a mutable pointer to the NUL-terminated string data.
167 /// `.as_mut_ptr` returns an internal pointer into the `CString`, and
168 /// may be invalidated when the `CString` falls out of scope (the
169 /// destructor will run, freeing the allocation if there is
173 /// let foo = "some string";
176 /// let mut x = foo.to_c_str();
177 /// let p = x.as_mut_ptr();
179 /// // wrong (the CString will be freed, invalidating `p`)
180 /// let p = foo.to_c_str().as_mut_ptr();
185 /// Fails if the CString is null.
186 pub fn as_mut_ptr(&mut self) -> *mut libc::c_char {
187 if self.buf.is_null() { fail!("CString is null!") }
192 /// Calls a closure with a reference to the underlying `*libc::c_char`.
196 /// Fails if the CString is null.
197 #[deprecated="use `.as_ptr()`"]
198 pub fn with_ref<T>(&self, f: |*const libc::c_char| -> T) -> T {
199 if self.buf.is_null() { fail!("CString is null!"); }
203 /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
207 /// Fails if the CString is null.
208 #[deprecated="use `.as_mut_ptr()`"]
209 pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T {
210 if self.buf.is_null() { fail!("CString is null!"); }
211 f(self.buf as *mut libc::c_char)
214 /// Returns true if the CString is a null.
215 pub fn is_null(&self) -> bool {
219 /// Returns true if the CString is not null.
220 pub fn is_not_null(&self) -> bool {
221 self.buf.is_not_null()
224 /// Returns whether or not the `CString` owns the buffer.
225 pub fn owns_buffer(&self) -> bool {
229 /// Converts the CString into a `&[u8]` without copying.
230 /// Includes the terminating NUL byte.
234 /// Fails if the CString is null.
236 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
237 if self.buf.is_null() { fail!("CString is null!"); }
239 mem::transmute(Slice { data: self.buf, len: self.len() + 1 })
243 /// Converts the CString into a `&[u8]` without copying.
244 /// Does not include the terminating NUL byte.
248 /// Fails if the CString is null.
250 pub fn as_bytes_no_nul<'a>(&'a self) -> &'a [u8] {
251 if self.buf.is_null() { fail!("CString is null!"); }
253 mem::transmute(Slice { data: self.buf, len: self.len() })
257 /// Converts the CString into a `&str` without copying.
258 /// Returns None if the CString is not UTF-8.
262 /// Fails if the CString is null.
264 pub fn as_str<'a>(&'a self) -> Option<&'a str> {
265 let buf = self.as_bytes_no_nul();
269 /// Return a CString iterator.
273 /// Fails if the CString is null.
274 pub fn iter<'a>(&'a self) -> CChars<'a> {
275 if self.buf.is_null() { fail!("CString is null!"); }
278 marker: marker::ContravariantLifetime,
282 /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
284 /// Any ownership of the buffer by the `CString` wrapper is
285 /// forgotten, meaning that the backing allocation of this
286 /// `CString` is not automatically freed if it owns the
287 /// allocation. In this case, a user of `.unwrap()` should ensure
288 /// the allocation is freed, to avoid leaking memory.
290 /// Prefer `.as_ptr()` when just retrieving a pointer to the
291 /// string data, as that does not relinquish ownership.
292 pub unsafe fn unwrap(mut self) -> *const libc::c_char {
293 self.owns_buffer_ = false;
299 impl Drop for CString {
301 if self.owns_buffer_ {
303 libc::free(self.buf as *mut libc::c_void)
309 impl Collection for CString {
310 /// Return the number of bytes in the CString (not including the NUL terminator).
314 /// Fails if the CString is null.
316 fn len(&self) -> uint {
317 if self.buf.is_null() { fail!("CString is null!"); }
318 let mut cur = self.buf;
330 /// A generic trait for converting a value to a CString.
332 /// Copy the receiver into a CString.
336 /// Fails the task if the receiver has an interior null.
337 fn to_c_str(&self) -> CString;
339 /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
340 unsafe fn to_c_str_unchecked(&self) -> CString;
342 /// Work with a temporary CString constructed from the receiver.
343 /// The provided `*libc::c_char` will be freed immediately upon return.
348 /// extern crate libc;
351 /// let s = "PATH".with_c_str(|path| unsafe {
352 /// libc::getenv(path)
359 /// Fails the task if the receiver has an interior null.
361 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
362 let c_str = self.to_c_str();
366 /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
368 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
369 let c_str = self.to_c_str_unchecked();
374 // FIXME (#12938): Until DST lands, we cannot decompose &str into &
375 // and str, so we cannot usefully take ToCStr arguments by reference
376 // (without forcing an additional & around &str). So we are instead
377 // temporarily adding an instance for ~str and String, so that we can
378 // take ToCStr as owned. When DST lands, the string instances should
379 // be revisited, and arguments bound by ToCStr should be passed by
382 impl<'a> ToCStr for &'a str {
384 fn to_c_str(&self) -> CString {
385 self.as_bytes().to_c_str()
389 unsafe fn to_c_str_unchecked(&self) -> CString {
390 self.as_bytes().to_c_str_unchecked()
394 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
395 self.as_bytes().with_c_str(f)
399 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
400 self.as_bytes().with_c_str_unchecked(f)
404 impl ToCStr for String {
406 fn to_c_str(&self) -> CString {
407 self.as_bytes().to_c_str()
411 unsafe fn to_c_str_unchecked(&self) -> CString {
412 self.as_bytes().to_c_str_unchecked()
416 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
417 self.as_bytes().with_c_str(f)
421 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
422 self.as_bytes().with_c_str_unchecked(f)
426 // The length of the stack allocated buffer for `vec.with_c_str()`
427 static BUF_LEN: uint = 128;
429 impl<'a> ToCStr for &'a [u8] {
430 fn to_c_str(&self) -> CString {
431 let mut cs = unsafe { self.to_c_str_unchecked() };
432 check_for_null(*self, cs.as_mut_ptr());
436 unsafe fn to_c_str_unchecked(&self) -> CString {
437 let self_len = self.len();
438 let buf = malloc_raw(self_len + 1);
440 ptr::copy_memory(buf, self.as_ptr(), self_len);
441 *buf.offset(self_len as int) = 0;
443 CString::new(buf as *const libc::c_char, true)
446 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
447 unsafe { with_c_str(*self, true, f) }
450 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
451 with_c_str(*self, false, f)
455 // Unsafe function that handles possibly copying the &[u8] into a stack array.
456 unsafe fn with_c_str<T>(v: &[u8], checked: bool,
457 f: |*const libc::c_char| -> T) -> T {
458 let c_str = if v.len() < BUF_LEN {
459 let mut buf: [u8, .. BUF_LEN] = mem::uninitialized();
460 slice::bytes::copy_memory(buf, v);
463 let buf = buf.as_mut_ptr();
465 check_for_null(v, buf as *mut libc::c_char);
468 return f(buf as *const libc::c_char)
472 v.to_c_str_unchecked()
479 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
480 for i in range(0, v.len()) {
482 let p = buf.offset(i as int);
488 /// External iterator for a CString's bytes.
490 /// Use with the `std::iter` module.
491 pub struct CChars<'a> {
492 ptr: *const libc::c_char,
493 marker: marker::ContravariantLifetime<'a>,
496 impl<'a> Iterator<libc::c_char> for CChars<'a> {
497 fn next(&mut self) -> Option<libc::c_char> {
498 let ch = unsafe { *self.ptr };
502 self.ptr = unsafe { self.ptr.offset(1) };
508 /// Parses a C "multistring", eg windows env values or
509 /// the req->ptr result in a uv_fs_readdir() call.
511 /// Optionally, a `count` can be passed in, limiting the
512 /// parsing to only being done `count`-times.
514 /// The specified closure is invoked with each string that
515 /// is found, and the number of strings found is returned.
516 pub unsafe fn from_c_multistring(buf: *const libc::c_char,
518 f: |&CString|) -> uint {
520 let mut curr_ptr: uint = buf as uint;
522 let (limited_count, limit) = match count {
523 Some(limit) => (true, limit),
526 while ((limited_count && ctr < limit) || !limited_count)
527 && *(curr_ptr as *const libc::c_char) != 0 as libc::c_char {
528 let cstr = CString::new(curr_ptr as *const libc::c_char, false);
530 curr_ptr += cstr.len() + 1;
546 fn test_str_multistring_parsing() {
548 let input = b"zero\0one\0\0";
549 let ptr = input.as_ptr();
550 let expected = ["zero", "one"];
551 let mut it = expected.iter();
552 let result = from_c_multistring(ptr as *const libc::c_char, None, |c| {
553 let cbytes = c.as_bytes_no_nul();
554 assert_eq!(cbytes, it.next().unwrap().as_bytes());
556 assert_eq!(result, 2);
557 assert!(it.next().is_none());
562 fn test_str_to_c_str() {
563 let c_str = "".to_c_str();
565 assert_eq!(*c_str.as_ptr().offset(0), 0);
568 let c_str = "hello".to_c_str();
569 let buf = c_str.as_ptr();
571 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
572 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
573 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
574 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
575 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
576 assert_eq!(*buf.offset(5), 0);
581 fn test_vec_to_c_str() {
583 let c_str = b.to_c_str();
585 assert_eq!(*c_str.as_ptr().offset(0), 0);
588 let c_str = b"hello".to_c_str();
589 let buf = c_str.as_ptr();
591 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
592 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
593 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
594 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
595 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
596 assert_eq!(*buf.offset(5), 0);
599 let c_str = b"foo\xFF".to_c_str();
600 let buf = c_str.as_ptr();
602 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
603 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
604 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
605 assert_eq!(*buf.offset(3), 0xffu8 as i8);
606 assert_eq!(*buf.offset(4), 0);
612 let c_str = unsafe { CString::new(ptr::null(), false) };
613 assert!(c_str.is_null());
614 assert!(!c_str.is_not_null());
619 let c_str = "hello".to_c_str();
620 unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
625 let c_str = "hello".to_c_str();
626 let len = unsafe { libc::strlen(c_str.as_ptr()) };
627 assert!(!c_str.is_null());
628 assert!(c_str.is_not_null());
633 fn test_as_ptr_empty_fail() {
634 let c_str = unsafe { CString::new(ptr::null(), false) };
640 let c_str = "".to_c_str();
641 let mut iter = c_str.iter();
642 assert_eq!(iter.next(), None);
644 let c_str = "hello".to_c_str();
645 let mut iter = c_str.iter();
646 assert_eq!(iter.next(), Some('h' as libc::c_char));
647 assert_eq!(iter.next(), Some('e' as libc::c_char));
648 assert_eq!(iter.next(), Some('l' as libc::c_char));
649 assert_eq!(iter.next(), Some('l' as libc::c_char));
650 assert_eq!(iter.next(), Some('o' as libc::c_char));
651 assert_eq!(iter.next(), None);
655 fn test_to_c_str_fail() {
656 assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
660 fn test_to_c_str_unchecked() {
662 let c_string = "he\x00llo".to_c_str_unchecked();
663 let buf = c_string.as_ptr();
664 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
665 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
666 assert_eq!(*buf.offset(2), 0);
667 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
668 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
669 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
670 assert_eq!(*buf.offset(6), 0);
676 let c_str = "hello".to_c_str();
677 assert_eq!(c_str.as_bytes(), b"hello\0");
678 let c_str = "".to_c_str();
679 assert_eq!(c_str.as_bytes(), b"\0");
680 let c_str = b"foo\xFF".to_c_str();
681 assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
685 fn test_as_bytes_no_nul() {
686 let c_str = "hello".to_c_str();
687 assert_eq!(c_str.as_bytes_no_nul(), b"hello");
688 let c_str = "".to_c_str();
690 assert_eq!(c_str.as_bytes_no_nul(), exp);
691 let c_str = b"foo\xFF".to_c_str();
692 assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
697 fn test_as_bytes_fail() {
698 let c_str = unsafe { CString::new(ptr::null(), false) };
704 fn test_as_bytes_no_nul_fail() {
705 let c_str = unsafe { CString::new(ptr::null(), false) };
706 c_str.as_bytes_no_nul();
711 let c_str = "hello".to_c_str();
712 assert_eq!(c_str.as_str(), Some("hello"));
713 let c_str = "".to_c_str();
714 assert_eq!(c_str.as_str(), Some(""));
715 let c_str = b"foo\xFF".to_c_str();
716 assert_eq!(c_str.as_str(), None);
721 fn test_as_str_fail() {
722 let c_str = unsafe { CString::new(ptr::null(), false) };
729 let c_str = unsafe { CString::new(ptr::null(), false) };
735 fn test_iter_fail() {
736 let c_str = unsafe { CString::new(ptr::null(), false) };
742 let a = "hello".to_c_str();
748 fn test_clone_noleak() {
749 fn foo(f: |c: &CString|) {
750 let s = "test".to_string();
751 let c = s.to_c_str();
752 // give the closure a non-owned CString
753 let mut c_ = unsafe { CString::new(c.as_ptr(), false) };
755 // muck with the buffer for later printing
756 unsafe { *c_.as_mut_ptr() = 'X' as libc::c_char }
759 let mut c_: Option<CString> = None;
761 c_ = Some(c.clone());
763 // force a copy, reading the memory
764 c.as_bytes().to_owned();
766 let c_ = c_.unwrap();
767 // force a copy, reading the memory
768 c_.as_bytes().to_owned();
772 fn test_clone_eq_null() {
773 let x = unsafe { CString::new(ptr::null(), false) };
786 fn check(s: &str, c_str: *const libc::c_char) {
787 let s_buf = s.as_ptr();
788 for i in range(0, s.len()) {
791 *s_buf.offset(i as int) as libc::c_char,
792 *c_str.offset(i as int));
797 static s_short: &'static str = "Mary";
798 static s_medium: &'static str = "Mary had a little lamb";
799 static s_long: &'static str = "\
800 Mary had a little lamb, Little lamb
801 Mary had a little lamb, Little lamb
802 Mary had a little lamb, Little lamb
803 Mary had a little lamb, Little lamb
804 Mary had a little lamb, Little lamb
805 Mary had a little lamb, Little lamb";
807 fn bench_to_str(b: &mut Bencher, s: &str) {
809 let c_str = s.to_c_str();
810 check(s, c_str.as_ptr());
815 fn bench_to_c_str_short(b: &mut Bencher) {
816 bench_to_str(b, s_short)
820 fn bench_to_c_str_medium(b: &mut Bencher) {
821 bench_to_str(b, s_medium)
825 fn bench_to_c_str_long(b: &mut Bencher) {
826 bench_to_str(b, s_long)
829 fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
831 let c_str = unsafe { s.to_c_str_unchecked() };
832 check(s, c_str.as_ptr())
837 fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
838 bench_to_c_str_unchecked(b, s_short)
842 fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
843 bench_to_c_str_unchecked(b, s_medium)
847 fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
848 bench_to_c_str_unchecked(b, s_long)
851 fn bench_with_c_str(b: &mut Bencher, s: &str) {
853 s.with_c_str(|c_str_buf| check(s, c_str_buf))
858 fn bench_with_c_str_short(b: &mut Bencher) {
859 bench_with_c_str(b, s_short)
863 fn bench_with_c_str_medium(b: &mut Bencher) {
864 bench_with_c_str(b, s_medium)
868 fn bench_with_c_str_long(b: &mut Bencher) {
869 bench_with_c_str(b, s_long)
872 fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
875 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
881 fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
882 bench_with_c_str_unchecked(b, s_short)
886 fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
887 bench_with_c_str_unchecked(b, s_medium)
891 fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
892 bench_with_c_str_unchecked(b, s_long)