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();
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.
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 /// 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) -> *const 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: |*const 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: |*const 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: |*const 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: |*const libc::c_char| -> T) -> T {
319 self.as_bytes().with_c_str(f)
323 unsafe fn with_c_str_unchecked<T>(&self, f: |*const 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: |*const libc::c_char| -> T) -> T {
341 self.as_bytes().with_c_str(f)
345 unsafe fn with_c_str_unchecked<T>(&self, f: |*const 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 *const libc::c_char, true)
370 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
371 unsafe { with_c_str(*self, true, f) }
374 unsafe fn with_c_str_unchecked<T>(&self, f: |*const 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,
381 f: |*const libc::c_char| -> T) -> T {
382 if v.len() < BUF_LEN {
383 let mut buf: [u8, .. BUF_LEN] = mem::uninitialized();
384 slice::bytes::copy_memory(buf, v);
387 let buf = buf.as_mut_ptr();
389 check_for_null(v, buf as *mut libc::c_char);
392 f(buf as *const libc::c_char)
394 v.to_c_str().with_ref(f)
396 v.to_c_str_unchecked().with_ref(f)
401 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
402 for i in range(0, v.len()) {
404 let p = buf.offset(i as int);
410 /// External iterator for a CString's bytes.
412 /// Use with the `std::iter` module.
413 pub struct CChars<'a> {
414 ptr: *const libc::c_char,
415 marker: marker::ContravariantLifetime<'a>,
418 impl<'a> Iterator<libc::c_char> for CChars<'a> {
419 fn next(&mut self) -> Option<libc::c_char> {
420 let ch = unsafe { *self.ptr };
424 self.ptr = unsafe { self.ptr.offset(1) };
430 /// Parses a C "multistring", eg windows env values or
431 /// the req->ptr result in a uv_fs_readdir() call.
433 /// Optionally, a `count` can be passed in, limiting the
434 /// parsing to only being done `count`-times.
436 /// The specified closure is invoked with each string that
437 /// is found, and the number of strings found is returned.
438 pub unsafe fn from_c_multistring(buf: *const libc::c_char,
440 f: |&CString|) -> uint {
442 let mut curr_ptr: uint = buf as uint;
444 let (limited_count, limit) = match count {
445 Some(limit) => (true, limit),
448 while ((limited_count && ctr < limit) || !limited_count)
449 && *(curr_ptr as *const libc::c_char) != 0 as libc::c_char {
450 let cstr = CString::new(curr_ptr as *const libc::c_char, false);
452 curr_ptr += cstr.len() + 1;
468 fn test_str_multistring_parsing() {
470 let input = b"zero\0one\0\0";
471 let ptr = input.as_ptr();
472 let expected = ["zero", "one"];
473 let mut it = expected.iter();
474 let result = from_c_multistring(ptr as *const libc::c_char, None, |c| {
475 let cbytes = c.as_bytes_no_nul();
476 assert_eq!(cbytes, it.next().unwrap().as_bytes());
478 assert_eq!(result, 2);
479 assert!(it.next().is_none());
484 fn test_str_to_c_str() {
485 "".to_c_str().with_ref(|buf| {
487 assert_eq!(*buf.offset(0), 0);
491 "hello".to_c_str().with_ref(|buf| {
493 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
494 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
495 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
496 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
497 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
498 assert_eq!(*buf.offset(5), 0);
504 fn test_vec_to_c_str() {
506 b.to_c_str().with_ref(|buf| {
508 assert_eq!(*buf.offset(0), 0);
512 let _ = b"hello".to_c_str().with_ref(|buf| {
514 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
515 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
516 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
517 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
518 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
519 assert_eq!(*buf.offset(5), 0);
523 let _ = b"foo\xFF".to_c_str().with_ref(|buf| {
525 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
526 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
527 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
528 assert_eq!(*buf.offset(3), 0xff as i8);
529 assert_eq!(*buf.offset(4), 0);
536 let c_str = unsafe { CString::new(ptr::null(), false) };
537 assert!(c_str.is_null());
538 assert!(!c_str.is_not_null());
543 let c_str = "hello".to_c_str();
544 unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
549 let c_str = "hello".to_c_str();
550 let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
551 assert!(!c_str.is_null());
552 assert!(c_str.is_not_null());
558 fn test_with_ref_empty_fail() {
559 let c_str = unsafe { CString::new(ptr::null(), false) };
560 c_str.with_ref(|_| ());
565 let c_str = "".to_c_str();
566 let mut iter = c_str.iter();
567 assert_eq!(iter.next(), None);
569 let c_str = "hello".to_c_str();
570 let mut iter = c_str.iter();
571 assert_eq!(iter.next(), Some('h' as libc::c_char));
572 assert_eq!(iter.next(), Some('e' as libc::c_char));
573 assert_eq!(iter.next(), Some('l' as libc::c_char));
574 assert_eq!(iter.next(), Some('l' as libc::c_char));
575 assert_eq!(iter.next(), Some('o' as libc::c_char));
576 assert_eq!(iter.next(), None);
580 fn test_to_c_str_fail() {
581 assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
585 fn test_to_c_str_unchecked() {
587 "he\x00llo".to_c_str_unchecked().with_ref(|buf| {
588 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
589 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
590 assert_eq!(*buf.offset(2), 0);
591 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
592 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
593 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
594 assert_eq!(*buf.offset(6), 0);
601 let c_str = "hello".to_c_str();
602 assert_eq!(c_str.as_bytes(), b"hello\0");
603 let c_str = "".to_c_str();
604 assert_eq!(c_str.as_bytes(), b"\0");
605 let c_str = b"foo\xFF".to_c_str();
606 assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
610 fn test_as_bytes_no_nul() {
611 let c_str = "hello".to_c_str();
612 assert_eq!(c_str.as_bytes_no_nul(), b"hello");
613 let c_str = "".to_c_str();
615 assert_eq!(c_str.as_bytes_no_nul(), exp);
616 let c_str = b"foo\xFF".to_c_str();
617 assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
622 fn test_as_bytes_fail() {
623 let c_str = unsafe { CString::new(ptr::null(), false) };
629 fn test_as_bytes_no_nul_fail() {
630 let c_str = unsafe { CString::new(ptr::null(), false) };
631 c_str.as_bytes_no_nul();
636 let c_str = "hello".to_c_str();
637 assert_eq!(c_str.as_str(), Some("hello"));
638 let c_str = "".to_c_str();
639 assert_eq!(c_str.as_str(), Some(""));
640 let c_str = b"foo\xFF".to_c_str();
641 assert_eq!(c_str.as_str(), None);
646 fn test_as_str_fail() {
647 let c_str = unsafe { CString::new(ptr::null(), false) };
654 let c_str = unsafe { CString::new(ptr::null(), false) };
660 fn test_iter_fail() {
661 let c_str = unsafe { CString::new(ptr::null(), false) };
667 let a = "hello".to_c_str();
673 fn test_clone_noleak() {
674 fn foo(f: |c: &CString|) {
675 let s = "test".to_string();
676 let c = s.to_c_str();
677 // give the closure a non-owned CString
678 let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } );
680 // muck with the buffer for later printing
681 c_.with_mut_ref(|c| unsafe { *c = 'X' as libc::c_char } );
684 let mut c_: Option<CString> = None;
686 c_ = Some(c.clone());
688 // force a copy, reading the memory
689 c.as_bytes().to_owned();
691 let c_ = c_.unwrap();
692 // force a copy, reading the memory
693 c_.as_bytes().to_owned();
697 fn test_clone_eq_null() {
698 let x = unsafe { CString::new(ptr::null(), false) };
711 fn check(s: &str, c_str: *const libc::c_char) {
712 let s_buf = s.as_ptr();
713 for i in range(0, s.len()) {
716 *s_buf.offset(i as int) as libc::c_char,
717 *c_str.offset(i as int));
722 static s_short: &'static str = "Mary";
723 static s_medium: &'static str = "Mary had a little lamb";
724 static s_long: &'static str = "\
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
730 Mary had a little lamb, Little lamb";
732 fn bench_to_str(b: &mut Bencher, s: &str) {
734 let c_str = s.to_c_str();
735 c_str.with_ref(|c_str_buf| check(s, c_str_buf))
740 fn bench_to_c_str_short(b: &mut Bencher) {
741 bench_to_str(b, s_short)
745 fn bench_to_c_str_medium(b: &mut Bencher) {
746 bench_to_str(b, s_medium)
750 fn bench_to_c_str_long(b: &mut Bencher) {
751 bench_to_str(b, s_long)
754 fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
756 let c_str = unsafe { s.to_c_str_unchecked() };
757 c_str.with_ref(|c_str_buf| check(s, c_str_buf))
762 fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
763 bench_to_c_str_unchecked(b, s_short)
767 fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
768 bench_to_c_str_unchecked(b, s_medium)
772 fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
773 bench_to_c_str_unchecked(b, s_long)
776 fn bench_with_c_str(b: &mut Bencher, s: &str) {
778 s.with_c_str(|c_str_buf| check(s, c_str_buf))
783 fn bench_with_c_str_short(b: &mut Bencher) {
784 bench_with_c_str(b, s_short)
788 fn bench_with_c_str_medium(b: &mut Bencher) {
789 bench_with_c_str(b, s_medium)
793 fn bench_with_c_str_long(b: &mut Bencher) {
794 bench_with_c_str(b, s_long)
797 fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
800 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
806 fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
807 bench_with_c_str_unchecked(b, s_short)
811 fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
812 bench_with_c_str_unchecked(b, s_medium)
816 fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
817 bench_with_c_str_unchecked(b, s_long)