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.
12 use iter::{Iterator, range};
15 use option::{Option, Some, None};
20 use vec::{ImmutableVector, CopyableVector};
21 use container::Container;
23 /// Resolution options for the `null_byte` condition
24 pub enum NullByteResolution {
25 /// Truncate at the null byte
27 /// Use a replacement byte
28 ReplaceWith(libc::c_char)
32 // This should be &[u8] but there's a lifetime issue (#5370).
33 // NOTE: this super::NullByteResolution should be NullByteResolution
34 // Change this next time the snapshot is updated.
35 pub null_byte: (~[u8]) -> super::NullByteResolution;
38 /// The representation of a C String.
40 /// This structure wraps a `*libc::c_char`, and will automatically free the
41 /// memory it is pointing to when it goes out of scope.
43 priv buf: *libc::c_char,
44 priv owns_buffer_: bool,
48 /// Create a C String from a pointer.
49 pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString {
50 CString { buf: buf, owns_buffer_: owns_buffer }
53 /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
54 /// Any ownership of the buffer by the `CString` wrapper is forgotten.
55 pub unsafe fn unwrap(self) -> *libc::c_char {
57 c_str.owns_buffer_ = false;
61 /// Calls a closure with a reference to the underlying `*libc::c_char`.
65 /// Fails if the CString is null.
66 pub fn with_ref<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
67 if self.buf.is_null() { fail!("CString is null!"); }
71 /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
75 /// Fails if the CString is null.
76 pub fn with_mut_ref<T>(&mut self, f: &fn(*mut libc::c_char) -> T) -> T {
77 if self.buf.is_null() { fail!("CString is null!"); }
78 f(unsafe { cast::transmute_mut_unsafe(self.buf) })
81 /// Returns true if the CString is a null.
82 pub fn is_null(&self) -> bool {
86 /// Returns true if the CString is not null.
87 pub fn is_not_null(&self) -> bool {
88 self.buf.is_not_null()
91 /// Returns whether or not the `CString` owns the buffer.
92 pub fn owns_buffer(&self) -> bool {
96 /// Converts the CString into a `&[u8]` without copying.
100 /// Fails if the CString is null.
102 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
103 if self.buf.is_null() { fail!("CString is null!"); }
105 let len = ptr::position(self.buf, |c| *c == 0);
106 cast::transmute((self.buf, len + 1))
110 /// Converts the CString into a `&str` without copying.
111 /// Returns None if the CString is not UTF-8 or is null.
113 pub fn as_str<'a>(&'a self) -> Option<&'a str> {
114 if self.buf.is_null() { return None; }
115 let buf = self.as_bytes();
116 let buf = buf.slice_to(buf.len()-1); // chop off the trailing NUL
117 str::from_utf8_slice_opt(buf)
120 /// Return a CString iterator.
121 pub fn iter<'a>(&'a self) -> CStringIterator<'a> {
124 lifetime: unsafe { cast::transmute(self.buf) },
129 impl Drop for CString {
131 #[fixed_stack_segment]; #[inline(never)];
132 if self.owns_buffer_ {
134 libc::free(self.buf as *libc::c_void)
140 /// A generic trait for converting a value to a CString.
142 /// Copy the receiver into a CString.
146 /// Raises the `null_byte` condition if the receiver has an interior null.
147 fn to_c_str(&self) -> CString;
149 /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
150 unsafe fn to_c_str_unchecked(&self) -> CString;
152 /// Work with a temporary CString constructed from the receiver.
153 /// The provided `*libc::c_char` will be freed immediately upon return.
158 /// let s = "PATH".with_c_str(|path| libc::getenv(path))
163 /// Raises the `null_byte` condition if the receiver has an interior null.
165 fn with_c_str<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
166 self.to_c_str().with_ref(f)
169 /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
171 unsafe fn with_c_str_unchecked<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
172 self.to_c_str_unchecked().with_ref(f)
176 impl<'self> ToCStr for &'self str {
178 fn to_c_str(&self) -> CString {
179 self.as_bytes().to_c_str()
183 unsafe fn to_c_str_unchecked(&self) -> CString {
184 self.as_bytes().to_c_str_unchecked()
188 impl<'self> ToCStr for &'self [u8] {
189 fn to_c_str(&self) -> CString {
190 #[fixed_stack_segment]; #[inline(never)];
191 let mut cs = unsafe { self.to_c_str_unchecked() };
192 do cs.with_mut_ref |buf| {
193 for i in range(0, self.len()) {
195 let p = buf.offset(i as int);
197 match null_byte::cond.raise(self.to_owned()) {
199 ReplaceWith(c) => *p = c
208 unsafe fn to_c_str_unchecked(&self) -> CString {
209 #[fixed_stack_segment]; #[inline(never)];
210 do self.as_imm_buf |self_buf, self_len| {
211 let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8;
213 fail!("failed to allocate memory!");
216 ptr::copy_memory(buf, self_buf, self_len);
217 *ptr::mut_offset(buf, self_len as int) = 0;
219 CString::new(buf as *libc::c_char, true)
224 /// External iterator for a CString's bytes.
226 /// Use with the `std::iterator` module.
227 pub struct CStringIterator<'self> {
228 priv ptr: *libc::c_char,
229 priv lifetime: &'self libc::c_char, // FIXME: #5922
232 impl<'self> Iterator<libc::c_char> for CStringIterator<'self> {
233 fn next(&mut self) -> Option<libc::c_char> {
234 let ch = unsafe { *self.ptr };
238 self.ptr = unsafe { ptr::offset(self.ptr, 1) };
249 use option::{Some, None};
252 fn test_str_to_c_str() {
253 do "".to_c_str().with_ref |buf| {
255 assert_eq!(*ptr::offset(buf, 0), 0);
259 do "hello".to_c_str().with_ref |buf| {
261 assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
262 assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
263 assert_eq!(*ptr::offset(buf, 2), 'l' as libc::c_char);
264 assert_eq!(*ptr::offset(buf, 3), 'l' as libc::c_char);
265 assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
266 assert_eq!(*ptr::offset(buf, 5), 0);
272 fn test_vec_to_c_str() {
274 do b.to_c_str().with_ref |buf| {
276 assert_eq!(*ptr::offset(buf, 0), 0);
280 do bytes!("hello").to_c_str().with_ref |buf| {
282 assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
283 assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
284 assert_eq!(*ptr::offset(buf, 2), 'l' as libc::c_char);
285 assert_eq!(*ptr::offset(buf, 3), 'l' as libc::c_char);
286 assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
287 assert_eq!(*ptr::offset(buf, 5), 0);
291 do bytes!("foo", 0xff).to_c_str().with_ref |buf| {
293 assert_eq!(*ptr::offset(buf, 0), 'f' as libc::c_char);
294 assert_eq!(*ptr::offset(buf, 1), 'o' as libc::c_char);
295 assert_eq!(*ptr::offset(buf, 2), 'o' as libc::c_char);
296 assert_eq!(*ptr::offset(buf, 3), 0xff);
297 assert_eq!(*ptr::offset(buf, 4), 0);
304 let c_str = unsafe { CString::new(ptr::null(), false) };
305 assert!(c_str.is_null());
306 assert!(!c_str.is_not_null());
311 #[fixed_stack_segment]; #[inline(never)];
313 let c_str = "hello".to_c_str();
314 unsafe { libc::free(c_str.unwrap() as *libc::c_void) }
319 #[fixed_stack_segment]; #[inline(never)];
321 let c_str = "hello".to_c_str();
322 let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
323 assert!(!c_str.is_null());
324 assert!(c_str.is_not_null());
330 fn test_with_ref_empty_fail() {
331 let c_str = unsafe { CString::new(ptr::null(), false) };
332 c_str.with_ref(|_| ());
337 let c_str = "".to_c_str();
338 let mut iter = c_str.iter();
339 assert_eq!(iter.next(), None);
341 let c_str = "hello".to_c_str();
342 let mut iter = c_str.iter();
343 assert_eq!(iter.next(), Some('h' as libc::c_char));
344 assert_eq!(iter.next(), Some('e' as libc::c_char));
345 assert_eq!(iter.next(), Some('l' as libc::c_char));
346 assert_eq!(iter.next(), Some('l' as libc::c_char));
347 assert_eq!(iter.next(), Some('o' as libc::c_char));
348 assert_eq!(iter.next(), None);
352 fn test_to_c_str_fail() {
353 use c_str::null_byte::cond;
355 let mut error_happened = false;
357 assert_eq!(err, bytes!("he", 0, "llo").to_owned())
358 error_happened = true;
361 "he\x00llo".to_c_str()
363 assert!(error_happened);
366 ReplaceWith('?' as libc::c_char)
367 }).inside(|| "he\x00llo".to_c_str()).with_ref |buf| {
369 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
370 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
371 assert_eq!(*buf.offset(2), '?' as libc::c_char);
372 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
373 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
374 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
375 assert_eq!(*buf.offset(6), 0);
381 fn test_to_c_str_unchecked() {
383 do "he\x00llo".to_c_str_unchecked().with_ref |buf| {
384 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
385 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
386 assert_eq!(*buf.offset(2), 0);
387 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
388 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
389 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
390 assert_eq!(*buf.offset(6), 0);
397 let c_str = "hello".to_c_str();
398 assert_eq!(c_str.as_bytes(), bytes!("hello", 0));
399 let c_str = "".to_c_str();
400 assert_eq!(c_str.as_bytes(), bytes!(0));
401 let c_str = bytes!("foo", 0xff).to_c_str();
402 assert_eq!(c_str.as_bytes(), bytes!("foo", 0xff, 0));
407 fn test_as_bytes_fail() {
408 let c_str = unsafe { CString::new(ptr::null(), false) };
414 let c_str = "hello".to_c_str();
415 assert_eq!(c_str.as_str(), Some("hello"));
416 let c_str = "".to_c_str();
417 assert_eq!(c_str.as_str(), Some(""));
418 let c_str = bytes!("foo", 0xff).to_c_str();
419 assert_eq!(c_str.as_str(), None);
420 let c_str = unsafe { CString::new(ptr::null(), false) };
421 assert_eq!(c_str.as_str(), None);