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.
11 //! C-string manipulation and management
13 //! This modules provides the basic methods for creating and manipulating
14 //! null-terminated strings for use with FFI calls (back to C). Most C APIs require
15 //! that the string being passed to them is null-terminated, and by default rust's
16 //! string types are *not* null terminated.
18 //! The other problem with translating Rust strings to C strings is that Rust
19 //! strings can validly contain a null-byte in the middle of the string (0 is a
20 //! valid Unicode codepoint). This means that not all Rust strings can actually be
21 //! translated to C strings.
23 //! # Creation of a C string
25 //! A C string is managed through the `CString` type defined in this module. It
26 //! "owns" the internal buffer of characters and will automatically deallocate the
27 //! buffer when the string is dropped. The `ToCStr` trait is implemented for `&str`
28 //! and `&[u8]`, but the conversions can fail due to some of the limitations
31 //! This also means that currently whenever a C string is created, an allocation
32 //! must be performed to place the data elsewhere (the lifetime of the C string is
33 //! not tied to the lifetime of the original string/data buffer). If C strings are
34 //! heavily used in applications, then caching may be advisable to prevent
35 //! unnecessary amounts of allocations.
37 //! Be carefull to remember that the memory is managed by C allocator API and not
38 //! by Rust allocator API.
39 //! That means that the CString pointers should be freed with C allocator API
40 //! if you intend to do that on your own, as the behaviour if you free them with
41 //! Rust's allocator API is not well defined
43 //! An example of creating and using a C string would be:
46 //! extern crate libc;
48 //! use std::c_str::ToCStr;
51 //! fn puts(s: *const libc::c_char);
55 //! let my_string = "Hello, world!";
57 //! // Allocate the C string with an explicit local that owns the string. The
58 //! // `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope.
59 //! let my_c_string = my_string.to_c_str();
61 //! puts(my_c_string.as_ptr());
64 //! // Don't save/return the pointer to the C string, the `c_buffer` will be
65 //! // deallocated when this block returns!
66 //! my_string.with_c_str(|c_buffer| {
67 //! unsafe { puts(c_buffer); }
80 use slice::{self, IntSliceExt};
83 use core::kinds::marker;
85 /// The representation of a C String.
87 /// This structure wraps a `*libc::c_char`, and will automatically free the
88 /// memory it is pointing to when it goes out of scope.
89 #[allow(missing_copy_implementations)]
91 buf: *const libc::c_char,
95 unsafe impl Send for CString { }
96 unsafe impl Sync for CString { }
98 impl Clone for CString {
99 /// Clone this CString into a new, uniquely owned CString. For safety
100 /// reasons, this is always a deep clone with the memory allocated
101 /// with C's allocator API, rather than the usual shallow clone.
102 fn clone(&self) -> CString {
103 let len = self.len() + 1;
104 let buf = unsafe { libc::malloc(len as libc::size_t) } as *mut libc::c_char;
105 if buf.is_null() { ::alloc::oom() }
106 unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); }
107 CString { buf: buf as *const libc::c_char, owns_buffer_: true }
111 impl PartialEq for CString {
112 fn eq(&self, other: &CString) -> bool {
113 // Check if the two strings share the same buffer
114 if self.buf as uint == other.buf as uint {
118 libc::strcmp(self.buf, other.buf) == 0
124 impl PartialOrd for CString {
126 fn partial_cmp(&self, other: &CString) -> Option<Ordering> {
127 self.as_bytes().partial_cmp(other.as_bytes())
131 impl Eq for CString {}
133 impl<S: hash::Writer> hash::Hash<S> for CString {
135 fn hash(&self, state: &mut S) {
136 self.as_bytes().hash(state)
141 /// Create a C String from a pointer, with memory managed by C's allocator
142 /// API, so avoid calling it with a pointer to memory managed by Rust's
143 /// allocator API, as the behaviour would not be well defined.
147 /// Panics if `buf` is null
148 pub unsafe fn new(buf: *const libc::c_char, owns_buffer: bool) -> CString {
149 assert!(!buf.is_null());
150 CString { buf: buf, owns_buffer_: owns_buffer }
153 /// Return a pointer to the NUL-terminated string data.
155 /// `.as_ptr` returns an internal pointer into the `CString`, and
156 /// may be invalidated when the `CString` falls out of scope (the
157 /// destructor will run, freeing the allocation if there is
161 /// use std::c_str::ToCStr;
163 /// let foo = "some string";
166 /// let x = foo.to_c_str();
167 /// let p = x.as_ptr();
169 /// // wrong (the CString will be freed, invalidating `p`)
170 /// let p = foo.to_c_str().as_ptr();
176 /// extern crate libc;
178 /// use std::c_str::ToCStr;
181 /// let c_str = "foo bar".to_c_str();
183 /// libc::puts(c_str.as_ptr());
187 pub fn as_ptr(&self) -> *const libc::c_char {
191 /// Return a mutable pointer to the NUL-terminated string data.
193 /// `.as_mut_ptr` returns an internal pointer into the `CString`, and
194 /// may be invalidated when the `CString` falls out of scope (the
195 /// destructor will run, freeing the allocation if there is
199 /// use std::c_str::ToCStr;
201 /// let foo = "some string";
204 /// let mut x = foo.to_c_str();
205 /// let p = x.as_mut_ptr();
207 /// // wrong (the CString will be freed, invalidating `p`)
208 /// let p = foo.to_c_str().as_mut_ptr();
210 pub fn as_mut_ptr(&mut self) -> *mut libc::c_char {
214 /// Returns whether or not the `CString` owns the buffer.
215 pub fn owns_buffer(&self) -> bool {
219 /// Converts the CString into a `&[u8]` without copying.
220 /// Includes the terminating NUL byte.
222 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
224 slice::from_raw_buf(&self.buf, self.len() + 1).as_unsigned()
228 /// Converts the CString into a `&[u8]` without copying.
229 /// Does not include the terminating NUL byte.
231 pub fn as_bytes_no_nul<'a>(&'a self) -> &'a [u8] {
233 slice::from_raw_buf(&self.buf, self.len()).as_unsigned()
237 /// Converts the CString into a `&str` without copying.
238 /// Returns None if the CString is not UTF-8.
240 pub fn as_str<'a>(&'a self) -> Option<&'a str> {
241 let buf = self.as_bytes_no_nul();
242 str::from_utf8(buf).ok()
245 /// Return a CString iterator.
246 pub fn iter<'a>(&'a self) -> CChars<'a> {
249 marker: marker::ContravariantLifetime,
253 /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
255 /// Any ownership of the buffer by the `CString` wrapper is
256 /// forgotten, meaning that the backing allocation of this
257 /// `CString` is not automatically freed if it owns the
258 /// allocation. In this case, a user of `.unwrap()` should ensure
259 /// the allocation is freed, to avoid leaking memory. You should
260 /// use libc's memory allocator in this case.
262 /// Prefer `.as_ptr()` when just retrieving a pointer to the
263 /// string data, as that does not relinquish ownership.
264 pub unsafe fn into_inner(mut self) -> *const libc::c_char {
265 self.owns_buffer_ = false;
269 /// Return the number of bytes in the CString (not including the NUL
272 pub fn len(&self) -> uint {
273 unsafe { libc::strlen(self.buf) as uint }
276 /// Returns if there are no bytes in this string
278 pub fn is_empty(&self) -> bool { self.len() == 0 }
281 impl Drop for CString {
283 if self.owns_buffer_ {
285 libc::free(self.buf as *mut libc::c_void)
291 impl fmt::Show for CString {
292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293 String::from_utf8_lossy(self.as_bytes_no_nul()).fmt(f)
297 /// A generic trait for converting a value to a CString.
298 pub trait ToCStr for Sized? {
299 /// Copy the receiver into a CString.
303 /// Panics the task if the receiver has an interior null.
304 fn to_c_str(&self) -> CString;
306 /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
307 unsafe fn to_c_str_unchecked(&self) -> CString;
309 /// Work with a temporary CString constructed from the receiver.
310 /// The provided `*libc::c_char` will be freed immediately upon return.
315 /// extern crate libc;
317 /// use std::c_str::ToCStr;
320 /// let s = "PATH".with_c_str(|path| unsafe {
321 /// libc::getenv(path)
328 /// Panics the task if the receiver has an interior null.
330 fn with_c_str<T, F>(&self, f: F) -> T where
331 F: FnOnce(*const libc::c_char) -> T,
333 let c_str = self.to_c_str();
337 /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
339 unsafe fn with_c_str_unchecked<T, F>(&self, f: F) -> T where
340 F: FnOnce(*const libc::c_char) -> T,
342 let c_str = self.to_c_str_unchecked();
347 impl ToCStr for str {
349 fn to_c_str(&self) -> CString {
350 self.as_bytes().to_c_str()
354 unsafe fn to_c_str_unchecked(&self) -> CString {
355 self.as_bytes().to_c_str_unchecked()
359 fn with_c_str<T, F>(&self, f: F) -> T where
360 F: FnOnce(*const libc::c_char) -> T,
362 self.as_bytes().with_c_str(f)
366 unsafe fn with_c_str_unchecked<T, F>(&self, f: F) -> T where
367 F: FnOnce(*const libc::c_char) -> T,
369 self.as_bytes().with_c_str_unchecked(f)
373 impl ToCStr for String {
375 fn to_c_str(&self) -> CString {
376 self.as_bytes().to_c_str()
380 unsafe fn to_c_str_unchecked(&self) -> CString {
381 self.as_bytes().to_c_str_unchecked()
385 fn with_c_str<T, F>(&self, f: F) -> T where
386 F: FnOnce(*const libc::c_char) -> T,
388 self.as_bytes().with_c_str(f)
392 unsafe fn with_c_str_unchecked<T, F>(&self, f: F) -> T where
393 F: FnOnce(*const libc::c_char) -> T,
395 self.as_bytes().with_c_str_unchecked(f)
399 // The length of the stack allocated buffer for `vec.with_c_str()`
400 const BUF_LEN: uint = 128;
402 impl ToCStr for [u8] {
403 fn to_c_str(&self) -> CString {
404 let mut cs = unsafe { self.to_c_str_unchecked() };
405 check_for_null(self, cs.as_mut_ptr());
409 unsafe fn to_c_str_unchecked(&self) -> CString {
410 let self_len = self.len();
411 let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8;
412 if buf.is_null() { ::alloc::oom() }
414 ptr::copy_memory(buf, self.as_ptr(), self_len);
415 *buf.offset(self_len as int) = 0;
417 CString::new(buf as *const libc::c_char, true)
420 fn with_c_str<T, F>(&self, f: F) -> T where
421 F: FnOnce(*const libc::c_char) -> T,
423 unsafe { with_c_str(self, true, f) }
426 unsafe fn with_c_str_unchecked<T, F>(&self, f: F) -> T where
427 F: FnOnce(*const libc::c_char) -> T,
429 with_c_str(self, false, f)
433 impl<'a, Sized? T: ToCStr> ToCStr for &'a T {
435 fn to_c_str(&self) -> CString {
440 unsafe fn to_c_str_unchecked(&self) -> CString {
441 (**self).to_c_str_unchecked()
445 fn with_c_str<T, F>(&self, f: F) -> T where
446 F: FnOnce(*const libc::c_char) -> T,
448 (**self).with_c_str(f)
452 unsafe fn with_c_str_unchecked<T, F>(&self, f: F) -> T where
453 F: FnOnce(*const libc::c_char) -> T,
455 (**self).with_c_str_unchecked(f)
459 // Unsafe function that handles possibly copying the &[u8] into a stack array.
460 unsafe fn with_c_str<T, F>(v: &[u8], checked: bool, f: F) -> T where
461 F: FnOnce(*const libc::c_char) -> T,
463 let c_str = if v.len() < BUF_LEN {
464 let mut buf: [u8; BUF_LEN] = mem::uninitialized();
465 slice::bytes::copy_memory(&mut buf, v);
468 let buf = buf.as_mut_ptr();
470 check_for_null(v, buf as *mut libc::c_char);
473 return f(buf as *const libc::c_char)
477 v.to_c_str_unchecked()
484 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
485 for i in range(0, v.len()) {
487 let p = buf.offset(i as int);
493 /// External iterator for a CString's bytes.
495 /// Use with the `std::iter` module.
496 #[allow(raw_pointer_deriving)]
498 pub struct CChars<'a> {
499 ptr: *const libc::c_char,
500 marker: marker::ContravariantLifetime<'a>,
503 impl<'a> Iterator for CChars<'a> {
504 type Item = libc::c_char;
506 fn next(&mut self) -> Option<libc::c_char> {
507 let ch = unsafe { *self.ptr };
511 self.ptr = unsafe { self.ptr.offset(1) };
517 /// Parses a C "multistring", eg windows env values or
518 /// the req->ptr result in a uv_fs_readdir() call.
520 /// Optionally, a `count` can be passed in, limiting the
521 /// parsing to only being done `count`-times.
523 /// The specified closure is invoked with each string that
524 /// is found, and the number of strings found is returned.
525 pub unsafe fn from_c_multistring<F>(buf: *const libc::c_char,
532 let mut curr_ptr: uint = buf as uint;
534 let (limited_count, limit) = match count {
535 Some(limit) => (true, limit),
538 while ((limited_count && ctr < limit) || !limited_count)
539 && *(curr_ptr as *const libc::c_char) != 0 as libc::c_char {
540 let cstr = CString::new(curr_ptr as *const libc::c_char, false);
542 curr_ptr += cstr.len() + 1;
557 fn test_str_multistring_parsing() {
559 let input = b"zero\0one\0\0";
560 let ptr = input.as_ptr();
561 let expected = ["zero", "one"];
562 let mut it = expected.iter();
563 let result = from_c_multistring(ptr as *const libc::c_char, None, |c| {
564 let cbytes = c.as_bytes_no_nul();
565 assert_eq!(cbytes, it.next().unwrap().as_bytes());
567 assert_eq!(result, 2);
568 assert!(it.next().is_none());
573 fn test_str_to_c_str() {
574 let c_str = "".to_c_str();
576 assert_eq!(*c_str.as_ptr().offset(0), 0);
579 let c_str = "hello".to_c_str();
580 let buf = c_str.as_ptr();
582 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
583 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
584 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
585 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
586 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
587 assert_eq!(*buf.offset(5), 0);
592 fn test_vec_to_c_str() {
594 let c_str = b.to_c_str();
596 assert_eq!(*c_str.as_ptr().offset(0), 0);
599 let c_str = b"hello".to_c_str();
600 let buf = c_str.as_ptr();
602 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
603 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
604 assert_eq!(*buf.offset(2), 'l' as libc::c_char);
605 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
606 assert_eq!(*buf.offset(4), 'o' as libc::c_char);
607 assert_eq!(*buf.offset(5), 0);
610 let c_str = b"foo\xFF".to_c_str();
611 let buf = c_str.as_ptr();
613 assert_eq!(*buf.offset(0), 'f' as libc::c_char);
614 assert_eq!(*buf.offset(1), 'o' as libc::c_char);
615 assert_eq!(*buf.offset(2), 'o' as libc::c_char);
616 assert_eq!(*buf.offset(3), 0xffu8 as libc::c_char);
617 assert_eq!(*buf.offset(4), 0);
623 let c_str = "hello".to_c_str();
624 unsafe { libc::free(c_str.into_inner() as *mut libc::c_void) }
629 let c_str = "hello".to_c_str();
630 let len = unsafe { libc::strlen(c_str.as_ptr()) };
636 let c_str = "".to_c_str();
637 let mut iter = c_str.iter();
638 assert_eq!(iter.next(), None);
640 let c_str = "hello".to_c_str();
641 let mut iter = c_str.iter();
642 assert_eq!(iter.next(), Some('h' as libc::c_char));
643 assert_eq!(iter.next(), Some('e' as libc::c_char));
644 assert_eq!(iter.next(), Some('l' as libc::c_char));
645 assert_eq!(iter.next(), Some('l' as libc::c_char));
646 assert_eq!(iter.next(), Some('o' as libc::c_char));
647 assert_eq!(iter.next(), None);
651 fn test_to_c_str_fail() {
652 assert!(Thread::spawn(move|| { "he\x00llo".to_c_str() }).join().is_err());
656 fn test_to_c_str_unchecked() {
658 let c_string = "he\x00llo".to_c_str_unchecked();
659 let buf = c_string.as_ptr();
660 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
661 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
662 assert_eq!(*buf.offset(2), 0);
663 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
664 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
665 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
666 assert_eq!(*buf.offset(6), 0);
672 let c_str = "hello".to_c_str();
673 assert_eq!(c_str.as_bytes(), b"hello\0");
674 let c_str = "".to_c_str();
675 assert_eq!(c_str.as_bytes(), b"\0");
676 let c_str = b"foo\xFF".to_c_str();
677 assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
681 fn test_as_bytes_no_nul() {
682 let c_str = "hello".to_c_str();
683 assert_eq!(c_str.as_bytes_no_nul(), b"hello");
684 let c_str = "".to_c_str();
685 let exp: &[u8] = &[];
686 assert_eq!(c_str.as_bytes_no_nul(), exp);
687 let c_str = b"foo\xFF".to_c_str();
688 assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
693 let c_str = "hello".to_c_str();
694 assert_eq!(c_str.as_str(), Some("hello"));
695 let c_str = "".to_c_str();
696 assert_eq!(c_str.as_str(), Some(""));
697 let c_str = b"foo\xFF".to_c_str();
698 assert_eq!(c_str.as_str(), None);
704 let _c_str = unsafe { CString::new(ptr::null(), false) };
709 let a = "hello".to_c_str();
715 fn test_clone_noleak() {
716 fn foo<F>(f: F) where F: FnOnce(&CString) {
717 let s = "test".to_string();
718 let c = s.to_c_str();
719 // give the closure a non-owned CString
720 let mut c_ = unsafe { CString::new(c.as_ptr(), false) };
722 // muck with the buffer for later printing
723 unsafe { *c_.as_mut_ptr() = 'X' as libc::c_char }
726 let mut c_: Option<CString> = None;
728 c_ = Some(c.clone());
730 // force a copy, reading the memory
731 c.as_bytes().to_vec();
733 let c_ = c_.unwrap();
734 // force a copy, reading the memory
735 c_.as_bytes().to_vec();
744 use self::test::Bencher;
749 fn check(s: &str, c_str: *const libc::c_char) {
750 let s_buf = s.as_ptr();
751 for i in range(0, s.len()) {
754 *s_buf.offset(i as int) as libc::c_char,
755 *c_str.offset(i as int));
760 static S_SHORT: &'static str = "Mary";
761 static S_MEDIUM: &'static str = "Mary had a little lamb";
762 static S_LONG: &'static str = "\
763 Mary had a little lamb, Little lamb
764 Mary had a little lamb, Little lamb
765 Mary had a little lamb, Little lamb
766 Mary had a little lamb, Little lamb
767 Mary had a little lamb, Little lamb
768 Mary had a little lamb, Little lamb";
770 fn bench_to_string(b: &mut Bencher, s: &str) {
772 let c_str = s.to_c_str();
773 check(s, c_str.as_ptr());
778 fn bench_to_c_str_short(b: &mut Bencher) {
779 bench_to_string(b, S_SHORT)
783 fn bench_to_c_str_medium(b: &mut Bencher) {
784 bench_to_string(b, S_MEDIUM)
788 fn bench_to_c_str_long(b: &mut Bencher) {
789 bench_to_string(b, S_LONG)
792 fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
794 let c_str = unsafe { s.to_c_str_unchecked() };
795 check(s, c_str.as_ptr())
800 fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
801 bench_to_c_str_unchecked(b, S_SHORT)
805 fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
806 bench_to_c_str_unchecked(b, S_MEDIUM)
810 fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
811 bench_to_c_str_unchecked(b, S_LONG)
814 fn bench_with_c_str(b: &mut Bencher, s: &str) {
816 s.with_c_str(|c_str_buf| check(s, c_str_buf))
821 fn bench_with_c_str_short(b: &mut Bencher) {
822 bench_with_c_str(b, S_SHORT)
826 fn bench_with_c_str_medium(b: &mut Bencher) {
827 bench_with_c_str(b, S_MEDIUM)
831 fn bench_with_c_str_long(b: &mut Bencher) {
832 bench_with_c_str(b, S_LONG)
835 fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
838 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
844 fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
845 bench_with_c_str_unchecked(b, S_SHORT)
849 fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
850 bench_with_c_str_unchecked(b, S_MEDIUM)
854 fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
855 bench_with_c_str_unchecked(b, S_LONG)