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 /// 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 /// Return a pointer to the NUL-terminated string data.
138 /// `.as_ptr` returns an internal pointer into the `CString`, and
139 /// may be invalidated when the `CString` falls out of scope (the
140 /// destructor will run, freeing the allocation if there is
144 /// let foo = "some string";
147 /// let x = foo.to_c_str();
148 /// let p = x.as_ptr();
150 /// // wrong (the CString will be freed, invalidating `p`)
151 /// let p = foo.to_c_str().as_ptr();
156 /// Fails if the CString is null.
161 /// extern crate libc;
164 /// let c_str = "foo bar".to_c_str();
166 /// libc::puts(c_str.as_ptr());
170 pub fn as_ptr(&self) -> *const libc::c_char {
171 if self.buf.is_null() { fail!("CString is null!"); }
176 /// Return a mutable pointer to the NUL-terminated string data.
178 /// `.as_mut_ptr` returns an internal pointer into the `CString`, and
179 /// may be invalidated when the `CString` falls out of scope (the
180 /// destructor will run, freeing the allocation if there is
184 /// let foo = "some string";
187 /// let mut x = foo.to_c_str();
188 /// let p = x.as_mut_ptr();
190 /// // wrong (the CString will be freed, invalidating `p`)
191 /// let p = foo.to_c_str().as_mut_ptr();
196 /// Fails if the CString is null.
197 pub fn as_mut_ptr(&mut self) -> *mut libc::c_char {
198 if self.buf.is_null() { fail!("CString is null!") }
203 /// Calls a closure with a reference to the underlying `*libc::c_char`.
207 /// Fails if the CString is null.
208 #[deprecated="use `.as_ptr()`"]
209 pub fn with_ref<T>(&self, f: |*const libc::c_char| -> T) -> T {
210 if self.buf.is_null() { fail!("CString is null!"); }
214 /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
218 /// Fails if the CString is null.
219 #[deprecated="use `.as_mut_ptr()`"]
220 pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T {
221 if self.buf.is_null() { fail!("CString is null!"); }
222 f(self.buf as *mut libc::c_char)
225 /// Returns true if the CString is a null.
226 pub fn is_null(&self) -> bool {
230 /// Returns true if the CString is not null.
231 pub fn is_not_null(&self) -> bool {
232 self.buf.is_not_null()
235 /// Returns whether or not the `CString` owns the buffer.
236 pub fn owns_buffer(&self) -> bool {
240 /// Converts the CString into a `&[u8]` without copying.
241 /// Includes the terminating NUL byte.
245 /// Fails if the CString is null.
247 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
248 if self.buf.is_null() { fail!("CString is null!"); }
250 mem::transmute(Slice { data: self.buf, len: self.len() + 1 })
254 /// Converts the CString into a `&[u8]` without copying.
255 /// Does not include the terminating NUL byte.
259 /// Fails if the CString is null.
261 pub fn as_bytes_no_nul<'a>(&'a self) -> &'a [u8] {
262 if self.buf.is_null() { fail!("CString is null!"); }
264 mem::transmute(Slice { data: self.buf, len: self.len() })
268 /// Converts the CString into a `&str` without copying.
269 /// Returns None if the CString is not UTF-8.
273 /// Fails if the CString is null.
275 pub fn as_str<'a>(&'a self) -> Option<&'a str> {
276 let buf = self.as_bytes_no_nul();
280 /// Return a CString iterator.
284 /// Fails if the CString is null.
285 pub fn iter<'a>(&'a self) -> CChars<'a> {
286 if self.buf.is_null() { fail!("CString is null!"); }
289 marker: marker::ContravariantLifetime,
294 impl Drop for CString {
296 if self.owns_buffer_ {
298 libc::free(self.buf as *mut libc::c_void)
304 impl Collection for CString {
305 /// Return the number of bytes in the CString (not including the NUL terminator).
309 /// Fails if the CString is null.
311 fn len(&self) -> uint {
312 if self.buf.is_null() { fail!("CString is null!"); }
313 let mut cur = self.buf;
325 /// A generic trait for converting a value to a CString.
327 /// Copy the receiver into a CString.
331 /// Fails the task if the receiver has an interior null.
332 fn to_c_str(&self) -> CString;
334 /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
335 unsafe fn to_c_str_unchecked(&self) -> CString;
337 /// Work with a temporary CString constructed from the receiver.
338 /// The provided `*libc::c_char` will be freed immediately upon return.
343 /// extern crate libc;
346 /// let s = "PATH".with_c_str(|path| unsafe {
347 /// libc::getenv(path)
354 /// Fails the task if the receiver has an interior null.
356 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
357 let c_str = self.to_c_str();
361 /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
363 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
364 let c_str = self.to_c_str_unchecked();
369 // FIXME (#12938): Until DST lands, we cannot decompose &str into &
370 // and str, so we cannot usefully take ToCStr arguments by reference
371 // (without forcing an additional & around &str). So we are instead
372 // temporarily adding an instance for ~str and String, so that we can
373 // take ToCStr as owned. When DST lands, the string instances should
374 // be revisted, and arguments bound by ToCStr should be passed by
377 impl<'a> ToCStr for &'a str {
379 fn to_c_str(&self) -> CString {
380 self.as_bytes().to_c_str()
384 unsafe fn to_c_str_unchecked(&self) -> CString {
385 self.as_bytes().to_c_str_unchecked()
389 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
390 self.as_bytes().with_c_str(f)
394 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
395 self.as_bytes().with_c_str_unchecked(f)
399 impl ToCStr for String {
401 fn to_c_str(&self) -> CString {
402 self.as_bytes().to_c_str()
406 unsafe fn to_c_str_unchecked(&self) -> CString {
407 self.as_bytes().to_c_str_unchecked()
411 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
412 self.as_bytes().with_c_str(f)
416 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
417 self.as_bytes().with_c_str_unchecked(f)
421 // The length of the stack allocated buffer for `vec.with_c_str()`
422 static BUF_LEN: uint = 128;
424 impl<'a> ToCStr for &'a [u8] {
425 fn to_c_str(&self) -> CString {
426 let mut cs = unsafe { self.to_c_str_unchecked() };
427 check_for_null(*self, cs.as_mut_ptr());
431 unsafe fn to_c_str_unchecked(&self) -> CString {
432 let self_len = self.len();
433 let buf = malloc_raw(self_len + 1);
435 ptr::copy_memory(buf, self.as_ptr(), self_len);
436 *buf.offset(self_len as int) = 0;
438 CString::new(buf as *const libc::c_char, true)
441 fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T {
442 unsafe { with_c_str(*self, true, f) }
445 unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T {
446 with_c_str(*self, false, f)
450 // Unsafe function that handles possibly copying the &[u8] into a stack array.
451 unsafe fn with_c_str<T>(v: &[u8], checked: bool,
452 f: |*const libc::c_char| -> T) -> T {
453 let c_str = if v.len() < BUF_LEN {
454 let mut buf: [u8, .. BUF_LEN] = mem::uninitialized();
455 slice::bytes::copy_memory(buf, v);
458 let buf = buf.as_mut_ptr();
460 check_for_null(v, buf as *mut libc::c_char);
463 return f(buf as *const libc::c_char)
467 v.to_c_str_unchecked()
474 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
475 for i in range(0, v.len()) {
477 let p = buf.offset(i as int);
483 /// External iterator for a CString's bytes.
485 /// Use with the `std::iter` module.
486 pub struct CChars<'a> {
487 ptr: *const libc::c_char,
488 marker: marker::ContravariantLifetime<'a>,
491 impl<'a> Iterator<libc::c_char> for CChars<'a> {
492 fn next(&mut self) -> Option<libc::c_char> {
493 let ch = unsafe { *self.ptr };
497 self.ptr = unsafe { self.ptr.offset(1) };
503 /// Parses a C "multistring", eg windows env values or
504 /// the req->ptr result in a uv_fs_readdir() call.
506 /// Optionally, a `count` can be passed in, limiting the
507 /// parsing to only being done `count`-times.
509 /// The specified closure is invoked with each string that
510 /// is found, and the number of strings found is returned.
511 pub unsafe fn from_c_multistring(buf: *const libc::c_char,
513 f: |&CString|) -> uint {
515 let mut curr_ptr: uint = buf as uint;
517 let (limited_count, limit) = match count {
518 Some(limit) => (true, limit),
521 while ((limited_count && ctr < limit) || !limited_count)
522 && *(curr_ptr as *const libc::c_char) != 0 as libc::c_char {
523 let cstr = CString::new(curr_ptr as *const libc::c_char, false);
525 curr_ptr += cstr.len() + 1;
541 fn test_str_multistring_parsing() {
543 let input = b"zero\0one\0\0";
544 let ptr = input.as_ptr();
545 let expected = ["zero", "one"];
546 let mut it = expected.iter();
547 let result = from_c_multistring(ptr as *const libc::c_char, None, |c| {
548 let cbytes = c.as_bytes_no_nul();
549 assert_eq!(cbytes, it.next().unwrap().as_bytes());
551 assert_eq!(result, 2);
552 assert!(it.next().is_none());
557 fn test_str_to_c_str() {
558 let c_str = "".to_c_str();
560 assert_eq!(*c_str.as_ptr().offset(0), 0);
563 let c_str = "hello".to_c_str();
564 let buf = c_str.as_ptr();
566 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
567 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
568 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
569 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
570 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
571 assert_eq!(*buf.offset(5), 0);
576 fn test_vec_to_c_str() {
578 let c_str = b.to_c_str();
580 assert_eq!(*c_str.as_ptr().offset(0), 0);
583 let c_str = b"hello".to_c_str();
584 let buf = c_str.as_ptr();
586 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
587 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
588 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
589 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
590 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
591 assert_eq!(*buf.offset(5), 0);
594 let c_str = b"foo\xFF".to_c_str();
595 let buf = c_str.as_ptr();
597 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
598 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
599 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
600 assert_eq!(*buf.offset(3), 0xffu8 as i8);
601 assert_eq!(*buf.offset(4), 0);
607 let c_str = unsafe { CString::new(ptr::null(), false) };
608 assert!(c_str.is_null());
609 assert!(!c_str.is_not_null());
614 let c_str = "hello".to_c_str();
615 unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
620 let c_str = "hello".to_c_str();
621 let len = unsafe { libc::strlen(c_str.as_ptr()) };
622 assert!(!c_str.is_null());
623 assert!(c_str.is_not_null());
628 fn test_as_ptr_empty_fail() {
629 let c_str = unsafe { CString::new(ptr::null(), false) };
635 let c_str = "".to_c_str();
636 let mut iter = c_str.iter();
637 assert_eq!(iter.next(), None);
639 let c_str = "hello".to_c_str();
640 let mut iter = c_str.iter();
641 assert_eq!(iter.next(), Some('h' as libc::c_char));
642 assert_eq!(iter.next(), Some('e' as libc::c_char));
643 assert_eq!(iter.next(), Some('l' as libc::c_char));
644 assert_eq!(iter.next(), Some('l' as libc::c_char));
645 assert_eq!(iter.next(), Some('o' as libc::c_char));
646 assert_eq!(iter.next(), None);
650 fn test_to_c_str_fail() {
651 assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
655 fn test_to_c_str_unchecked() {
657 let c_string = "he\x00llo".to_c_str_unchecked();
658 let buf = c_string.as_ptr();
659 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
660 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
661 assert_eq!(*buf.offset(2), 0);
662 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
663 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
664 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
665 assert_eq!(*buf.offset(6), 0);
671 let c_str = "hello".to_c_str();
672 assert_eq!(c_str.as_bytes(), b"hello\0");
673 let c_str = "".to_c_str();
674 assert_eq!(c_str.as_bytes(), b"\0");
675 let c_str = b"foo\xFF".to_c_str();
676 assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
680 fn test_as_bytes_no_nul() {
681 let c_str = "hello".to_c_str();
682 assert_eq!(c_str.as_bytes_no_nul(), b"hello");
683 let c_str = "".to_c_str();
685 assert_eq!(c_str.as_bytes_no_nul(), exp);
686 let c_str = b"foo\xFF".to_c_str();
687 assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
692 fn test_as_bytes_fail() {
693 let c_str = unsafe { CString::new(ptr::null(), false) };
699 fn test_as_bytes_no_nul_fail() {
700 let c_str = unsafe { CString::new(ptr::null(), false) };
701 c_str.as_bytes_no_nul();
706 let c_str = "hello".to_c_str();
707 assert_eq!(c_str.as_str(), Some("hello"));
708 let c_str = "".to_c_str();
709 assert_eq!(c_str.as_str(), Some(""));
710 let c_str = b"foo\xFF".to_c_str();
711 assert_eq!(c_str.as_str(), None);
716 fn test_as_str_fail() {
717 let c_str = unsafe { CString::new(ptr::null(), false) };
724 let c_str = unsafe { CString::new(ptr::null(), false) };
730 fn test_iter_fail() {
731 let c_str = unsafe { CString::new(ptr::null(), false) };
737 let a = "hello".to_c_str();
743 fn test_clone_noleak() {
744 fn foo(f: |c: &CString|) {
745 let s = "test".to_string();
746 let c = s.to_c_str();
747 // give the closure a non-owned CString
748 let mut c_ = unsafe { CString::new(c.as_ptr(), false) };
750 // muck with the buffer for later printing
751 unsafe { *c_.as_mut_ptr() = 'X' as libc::c_char }
754 let mut c_: Option<CString> = None;
756 c_ = Some(c.clone());
758 // force a copy, reading the memory
759 c.as_bytes().to_owned();
761 let c_ = c_.unwrap();
762 // force a copy, reading the memory
763 c_.as_bytes().to_owned();
767 fn test_clone_eq_null() {
768 let x = unsafe { CString::new(ptr::null(), false) };
781 fn check(s: &str, c_str: *const libc::c_char) {
782 let s_buf = s.as_ptr();
783 for i in range(0, s.len()) {
786 *s_buf.offset(i as int) as libc::c_char,
787 *c_str.offset(i as int));
792 static s_short: &'static str = "Mary";
793 static s_medium: &'static str = "Mary had a little lamb";
794 static s_long: &'static str = "\
795 Mary had a little lamb, Little lamb
796 Mary had a little lamb, Little lamb
797 Mary had a little lamb, Little lamb
798 Mary had a little lamb, Little lamb
799 Mary had a little lamb, Little lamb
800 Mary had a little lamb, Little lamb";
802 fn bench_to_str(b: &mut Bencher, s: &str) {
804 let c_str = s.to_c_str();
805 check(s, c_str.as_ptr());
810 fn bench_to_c_str_short(b: &mut Bencher) {
811 bench_to_str(b, s_short)
815 fn bench_to_c_str_medium(b: &mut Bencher) {
816 bench_to_str(b, s_medium)
820 fn bench_to_c_str_long(b: &mut Bencher) {
821 bench_to_str(b, s_long)
824 fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
826 let c_str = unsafe { s.to_c_str_unchecked() };
827 check(s, c_str.as_ptr())
832 fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
833 bench_to_c_str_unchecked(b, s_short)
837 fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
838 bench_to_c_str_unchecked(b, s_medium)
842 fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
843 bench_to_c_str_unchecked(b, s_long)
846 fn bench_with_c_str(b: &mut Bencher, s: &str) {
848 s.with_c_str(|c_str_buf| check(s, c_str_buf))
853 fn bench_with_c_str_short(b: &mut Bencher) {
854 bench_with_c_str(b, s_short)
858 fn bench_with_c_str_medium(b: &mut Bencher) {
859 bench_with_c_str(b, s_medium)
863 fn bench_with_c_str_long(b: &mut Bencher) {
864 bench_with_c_str(b, s_long)
867 fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
870 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
876 fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
877 bench_with_c_str_unchecked(b, s_short)
881 fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
882 bench_with_c_str_unchecked(b, s_medium)
886 fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
887 bench_with_c_str_unchecked(b, s_long)