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: *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();
54 my_c_string.with_ref(|c_buffer| {
55 unsafe { puts(c_buffer); }
58 // Don't save off the allocation of 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.
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 *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: *libc::c_char, owns_buffer: bool) -> CString {
122 CString { buf: buf, owns_buffer_: owns_buffer }
125 /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
127 /// The original object is destructed after this method is called, and if
128 /// the underlying pointer was previously allocated, care must be taken to
129 /// ensure that it is deallocated properly.
130 pub unsafe fn unwrap(self) -> *libc::c_char {
131 let mut c_str = self;
132 c_str.owns_buffer_ = false;
136 /// Calls a closure with a reference to the underlying `*libc::c_char`.
140 /// Fails if the CString is null.
141 pub fn with_ref<T>(&self, f: |*libc::c_char| -> T) -> T {
142 if self.buf.is_null() { fail!("CString is null!"); }
146 /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
150 /// Fails if the CString is null.
151 pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T {
152 if self.buf.is_null() { fail!("CString is null!"); }
153 f(self.buf as *mut libc::c_char)
156 /// Returns true if the CString is a null.
157 pub fn is_null(&self) -> bool {
161 /// Returns true if the CString is not null.
162 pub fn is_not_null(&self) -> bool {
163 self.buf.is_not_null()
166 /// Returns whether or not the `CString` owns the buffer.
167 pub fn owns_buffer(&self) -> bool {
171 /// Converts the CString into a `&[u8]` without copying.
172 /// Includes the terminating NUL byte.
176 /// Fails if the CString is null.
178 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
179 if self.buf.is_null() { fail!("CString is null!"); }
181 mem::transmute(Slice { data: self.buf, len: self.len() + 1 })
185 /// Converts the CString into a `&[u8]` without copying.
186 /// Does not include the terminating NUL byte.
190 /// Fails if the CString is null.
192 pub fn as_bytes_no_nul<'a>(&'a self) -> &'a [u8] {
193 if self.buf.is_null() { fail!("CString is null!"); }
195 mem::transmute(Slice { data: self.buf, len: self.len() })
199 /// Converts the CString into a `&str` without copying.
200 /// Returns None if the CString is not UTF-8.
204 /// Fails if the CString is null.
206 pub fn as_str<'a>(&'a self) -> Option<&'a str> {
207 let buf = self.as_bytes_no_nul();
211 /// Return a CString iterator.
215 /// Fails if the CString is null.
216 pub fn iter<'a>(&'a self) -> CChars<'a> {
217 if self.buf.is_null() { fail!("CString is null!"); }
220 marker: marker::ContravariantLifetime,
225 impl Drop for CString {
227 if self.owns_buffer_ {
229 libc::free(self.buf as *mut libc::c_void)
235 impl Collection for CString {
236 /// Return the number of bytes in the CString (not including the NUL terminator).
240 /// Fails if the CString is null.
242 fn len(&self) -> uint {
243 if self.buf.is_null() { fail!("CString is null!"); }
244 let mut cur = self.buf;
256 /// A generic trait for converting a value to a CString.
258 /// Copy the receiver into a CString.
262 /// Fails the task if the receiver has an interior null.
263 fn to_c_str(&self) -> CString;
265 /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
266 unsafe fn to_c_str_unchecked(&self) -> CString;
268 /// Work with a temporary CString constructed from the receiver.
269 /// The provided `*libc::c_char` will be freed immediately upon return.
274 /// extern crate libc;
277 /// let s = "PATH".with_c_str(|path| unsafe {
278 /// libc::getenv(path)
285 /// Fails the task if the receiver has an interior null.
287 fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
288 self.to_c_str().with_ref(f)
291 /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
293 unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
294 self.to_c_str_unchecked().with_ref(f)
298 // FIXME (#12938): Until DST lands, we cannot decompose &str into &
299 // and str, so we cannot usefully take ToCStr arguments by reference
300 // (without forcing an additional & around &str). So we are instead
301 // temporarily adding an instance for ~str and String, so that we can
302 // take ToCStr as owned. When DST lands, the string instances should
303 // be revisted, and arguments bound by ToCStr should be passed by
306 impl<'a> ToCStr for &'a str {
308 fn to_c_str(&self) -> CString {
309 self.as_bytes().to_c_str()
313 unsafe fn to_c_str_unchecked(&self) -> CString {
314 self.as_bytes().to_c_str_unchecked()
318 fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
319 self.as_bytes().with_c_str(f)
323 unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
324 self.as_bytes().with_c_str_unchecked(f)
328 impl ToCStr for String {
330 fn to_c_str(&self) -> CString {
331 self.as_bytes().to_c_str()
335 unsafe fn to_c_str_unchecked(&self) -> CString {
336 self.as_bytes().to_c_str_unchecked()
340 fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
341 self.as_bytes().with_c_str(f)
345 unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
346 self.as_bytes().with_c_str_unchecked(f)
350 // The length of the stack allocated buffer for `vec.with_c_str()`
351 static BUF_LEN: uint = 128;
353 impl<'a> ToCStr for &'a [u8] {
354 fn to_c_str(&self) -> CString {
355 let mut cs = unsafe { self.to_c_str_unchecked() };
356 cs.with_mut_ref(|buf| check_for_null(*self, buf));
360 unsafe fn to_c_str_unchecked(&self) -> CString {
361 let self_len = self.len();
362 let buf = malloc_raw(self_len + 1);
364 ptr::copy_memory(buf, self.as_ptr(), self_len);
365 *buf.offset(self_len as int) = 0;
367 CString::new(buf as *libc::c_char, true)
370 fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
371 unsafe { with_c_str(*self, true, f) }
374 unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
375 with_c_str(*self, false, f)
379 // Unsafe function that handles possibly copying the &[u8] into a stack array.
380 unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T {
381 if v.len() < BUF_LEN {
382 let mut buf: [u8, .. BUF_LEN] = mem::uninitialized();
383 slice::bytes::copy_memory(buf, v);
386 let buf = buf.as_mut_ptr();
388 check_for_null(v, buf as *mut libc::c_char);
391 f(buf as *libc::c_char)
393 v.to_c_str().with_ref(f)
395 v.to_c_str_unchecked().with_ref(f)
400 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
401 for i in range(0, v.len()) {
403 let p = buf.offset(i as int);
409 /// External iterator for a CString's bytes.
411 /// Use with the `std::iter` module.
412 pub struct CChars<'a> {
414 marker: marker::ContravariantLifetime<'a>,
417 impl<'a> Iterator<libc::c_char> for CChars<'a> {
418 fn next(&mut self) -> Option<libc::c_char> {
419 let ch = unsafe { *self.ptr };
423 self.ptr = unsafe { self.ptr.offset(1) };
429 /// Parses a C "multistring", eg windows env values or
430 /// the req->ptr result in a uv_fs_readdir() call.
432 /// Optionally, a `count` can be passed in, limiting the
433 /// parsing to only being done `count`-times.
435 /// The specified closure is invoked with each string that
436 /// is found, and the number of strings found is returned.
437 pub unsafe fn from_c_multistring(buf: *libc::c_char,
439 f: |&CString|) -> uint {
441 let mut curr_ptr: uint = buf as uint;
443 let (limited_count, limit) = match count {
444 Some(limit) => (true, limit),
447 while ((limited_count && ctr < limit) || !limited_count)
448 && *(curr_ptr as *libc::c_char) != 0 as libc::c_char {
449 let cstr = CString::new(curr_ptr as *libc::c_char, false);
451 curr_ptr += cstr.len() + 1;
467 fn test_str_multistring_parsing() {
469 let input = b"zero\0one\0\0";
470 let ptr = input.as_ptr();
471 let expected = ["zero", "one"];
472 let mut it = expected.iter();
473 let result = from_c_multistring(ptr as *libc::c_char, None, |c| {
474 let cbytes = c.as_bytes_no_nul();
475 assert_eq!(cbytes, it.next().unwrap().as_bytes());
477 assert_eq!(result, 2);
478 assert!(it.next().is_none());
483 fn test_str_to_c_str() {
484 "".to_c_str().with_ref(|buf| {
486 assert_eq!(*buf.offset(0), 0);
490 "hello".to_c_str().with_ref(|buf| {
492 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
493 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
494 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
495 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
496 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
497 assert_eq!(*buf.offset(5), 0);
503 fn test_vec_to_c_str() {
505 b.to_c_str().with_ref(|buf| {
507 assert_eq!(*buf.offset(0), 0);
511 let _ = b"hello".to_c_str().with_ref(|buf| {
513 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
514 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
515 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
516 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
517 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
518 assert_eq!(*buf.offset(5), 0);
522 let _ = b"foo\xFF".to_c_str().with_ref(|buf| {
524 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
525 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
526 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
527 assert_eq!(*buf.offset(3), 0xff as i8);
528 assert_eq!(*buf.offset(4), 0);
535 let c_str = unsafe { CString::new(ptr::null(), false) };
536 assert!(c_str.is_null());
537 assert!(!c_str.is_not_null());
542 let c_str = "hello".to_c_str();
543 unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
548 let c_str = "hello".to_c_str();
549 let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
550 assert!(!c_str.is_null());
551 assert!(c_str.is_not_null());
557 fn test_with_ref_empty_fail() {
558 let c_str = unsafe { CString::new(ptr::null(), false) };
559 c_str.with_ref(|_| ());
564 let c_str = "".to_c_str();
565 let mut iter = c_str.iter();
566 assert_eq!(iter.next(), None);
568 let c_str = "hello".to_c_str();
569 let mut iter = c_str.iter();
570 assert_eq!(iter.next(), Some('h' as libc::c_char));
571 assert_eq!(iter.next(), Some('e' as libc::c_char));
572 assert_eq!(iter.next(), Some('l' as libc::c_char));
573 assert_eq!(iter.next(), Some('l' as libc::c_char));
574 assert_eq!(iter.next(), Some('o' as libc::c_char));
575 assert_eq!(iter.next(), None);
579 fn test_to_c_str_fail() {
580 assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
584 fn test_to_c_str_unchecked() {
586 "he\x00llo".to_c_str_unchecked().with_ref(|buf| {
587 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
588 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
589 assert_eq!(*buf.offset(2), 0);
590 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
591 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
592 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
593 assert_eq!(*buf.offset(6), 0);
600 let c_str = "hello".to_c_str();
601 assert_eq!(c_str.as_bytes(), b"hello\0");
602 let c_str = "".to_c_str();
603 assert_eq!(c_str.as_bytes(), b"\0");
604 let c_str = b"foo\xFF".to_c_str();
605 assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
609 fn test_as_bytes_no_nul() {
610 let c_str = "hello".to_c_str();
611 assert_eq!(c_str.as_bytes_no_nul(), b"hello");
612 let c_str = "".to_c_str();
614 assert_eq!(c_str.as_bytes_no_nul(), exp);
615 let c_str = b"foo\xFF".to_c_str();
616 assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
621 fn test_as_bytes_fail() {
622 let c_str = unsafe { CString::new(ptr::null(), false) };
628 fn test_as_bytes_no_nul_fail() {
629 let c_str = unsafe { CString::new(ptr::null(), false) };
630 c_str.as_bytes_no_nul();
635 let c_str = "hello".to_c_str();
636 assert_eq!(c_str.as_str(), Some("hello"));
637 let c_str = "".to_c_str();
638 assert_eq!(c_str.as_str(), Some(""));
639 let c_str = b"foo\xFF".to_c_str();
640 assert_eq!(c_str.as_str(), None);
645 fn test_as_str_fail() {
646 let c_str = unsafe { CString::new(ptr::null(), false) };
653 let c_str = unsafe { CString::new(ptr::null(), false) };
659 fn test_iter_fail() {
660 let c_str = unsafe { CString::new(ptr::null(), false) };
666 let a = "hello".to_c_str();
672 fn test_clone_noleak() {
673 fn foo(f: |c: &CString|) {
674 let s = "test".to_string();
675 let c = s.to_c_str();
676 // give the closure a non-owned CString
677 let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } );
679 // muck with the buffer for later printing
680 c_.with_mut_ref(|c| unsafe { *c = 'X' as libc::c_char } );
683 let mut c_: Option<CString> = None;
685 c_ = Some(c.clone());
687 // force a copy, reading the memory
688 c.as_bytes().to_owned();
690 let c_ = c_.unwrap();
691 // force a copy, reading the memory
692 c_.as_bytes().to_owned();
696 fn test_clone_eq_null() {
697 let x = unsafe { CString::new(ptr::null(), false) };
710 fn check(s: &str, c_str: *libc::c_char) {
711 let s_buf = s.as_ptr();
712 for i in range(0, s.len()) {
715 *s_buf.offset(i as int) as libc::c_char,
716 *c_str.offset(i as int));
721 static s_short: &'static str = "Mary";
722 static s_medium: &'static str = "Mary had a little lamb";
723 static s_long: &'static str = "\
724 Mary had a little lamb, Little lamb
725 Mary had a little lamb, Little lamb
726 Mary had a little lamb, Little lamb
727 Mary had a little lamb, Little lamb
728 Mary had a little lamb, Little lamb
729 Mary had a little lamb, Little lamb";
731 fn bench_to_str(b: &mut Bencher, s: &str) {
733 let c_str = s.to_c_str();
734 c_str.with_ref(|c_str_buf| check(s, c_str_buf))
739 fn bench_to_c_str_short(b: &mut Bencher) {
740 bench_to_str(b, s_short)
744 fn bench_to_c_str_medium(b: &mut Bencher) {
745 bench_to_str(b, s_medium)
749 fn bench_to_c_str_long(b: &mut Bencher) {
750 bench_to_str(b, s_long)
753 fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
755 let c_str = unsafe { s.to_c_str_unchecked() };
756 c_str.with_ref(|c_str_buf| check(s, c_str_buf))
761 fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
762 bench_to_c_str_unchecked(b, s_short)
766 fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
767 bench_to_c_str_unchecked(b, s_medium)
771 fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
772 bench_to_c_str_unchecked(b, s_long)
775 fn bench_with_c_str(b: &mut Bencher, s: &str) {
777 s.with_c_str(|c_str_buf| check(s, c_str_buf))
782 fn bench_with_c_str_short(b: &mut Bencher) {
783 bench_with_c_str(b, s_short)
787 fn bench_with_c_str_medium(b: &mut Bencher) {
788 bench_with_c_str(b, s_medium)
792 fn bench_with_c_str_long(b: &mut Bencher) {
793 bench_with_c_str(b, s_long)
796 fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
799 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
805 fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
806 bench_with_c_str_unchecked(b, s_short)
810 fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
811 bench_with_c_str_unchecked(b, s_medium)
815 fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
816 bench_with_c_str_unchecked(b, s_long)