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 iterator::{Iterator,range};
15 use option::{Option, Some, None};
19 use vec::{ImmutableVector,CopyableVector};
20 use container::Container;
22 /// Resolution options for the `null_byte` condition
23 pub enum NullByteResolution {
24 /// Truncate at the null byte
26 /// Use a replacement byte
27 ReplaceWith(libc::c_char)
31 // this should be &[u8] but there's a lifetime issue
32 null_byte: (~[u8]) -> super::NullByteResolution;
35 /// The representation of a C String.
37 /// This structure wraps a `*libc::c_char`, and will automatically free the
38 /// memory it is pointing to when it goes out of scope.
40 priv buf: *libc::c_char,
41 priv owns_buffer_: bool,
45 /// Create a C String from a pointer.
46 pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString {
47 CString { buf: buf, owns_buffer_: owns_buffer }
50 /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
51 /// Any ownership of the buffer by the `CString` wrapper is forgotten.
52 pub unsafe fn unwrap(self) -> *libc::c_char {
54 c_str.owns_buffer_ = false;
58 /// Calls a closure with a reference to the underlying `*libc::c_char`.
62 /// Fails if the CString is null.
63 pub fn with_ref<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
64 if self.buf.is_null() { fail!("CString is null!"); }
68 /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
72 /// Fails if the CString is null.
73 pub fn with_mut_ref<T>(&mut self, f: &fn(*mut libc::c_char) -> T) -> T {
74 if self.buf.is_null() { fail!("CString is null!"); }
75 f(unsafe { cast::transmute_mut_unsafe(self.buf) })
78 /// Returns true if the CString is a null.
79 pub fn is_null(&self) -> bool {
83 /// Returns true if the CString is not null.
84 pub fn is_not_null(&self) -> bool {
85 self.buf.is_not_null()
88 /// Returns whether or not the `CString` owns the buffer.
89 pub fn owns_buffer(&self) -> bool {
93 /// Converts the CString into a `&[u8]` without copying.
97 /// Fails if the CString is null.
98 pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
99 if self.buf.is_null() { fail!("CString is null!"); }
101 let len = libc::strlen(self.buf) as uint;
102 cast::transmute((self.buf, len + 1))
106 /// Return a CString iterator.
107 fn iter<'a>(&'a self) -> CStringIterator<'a> {
110 lifetime: unsafe { cast::transmute(self.buf) },
115 impl Drop for CString {
117 if self.owns_buffer_ {
119 libc::free(self.buf as *libc::c_void)
125 /// A generic trait for converting a value to a CString.
127 /// Copy the receiver into a CString.
131 /// Raises the `null_byte` condition if the receiver has an interior null.
132 fn to_c_str(&self) -> CString;
134 /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
135 unsafe fn to_c_str_unchecked(&self) -> CString;
137 /// Work with a temporary CString constructed from the receiver.
138 /// The provided `*libc::c_char` will be freed immediately upon return.
143 /// let s = "PATH".with_c_str(|path| libc::getenv(path))
148 /// Raises the `null_byte` condition if the receiver has an interior null.
150 fn with_c_str<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
151 self.to_c_str().with_ref(f)
154 /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
156 unsafe fn with_c_str_unchecked<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
157 self.to_c_str_unchecked().with_ref(f)
161 impl<'self> ToCStr for &'self str {
163 fn to_c_str(&self) -> CString {
164 self.as_bytes().to_c_str()
168 unsafe fn to_c_str_unchecked(&self) -> CString {
169 self.as_bytes().to_c_str_unchecked()
173 impl<'self> ToCStr for &'self [u8] {
174 fn to_c_str(&self) -> CString {
175 let mut cs = unsafe { self.to_c_str_unchecked() };
176 do cs.with_mut_ref |buf| {
177 for i in range(0, self.len()) {
179 let p = buf.offset_inbounds(i as int);
181 match null_byte::cond.raise(self.to_owned()) {
183 ReplaceWith(c) => *p = c
192 unsafe fn to_c_str_unchecked(&self) -> CString {
193 do self.as_imm_buf |self_buf, self_len| {
194 let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8;
196 fail!("failed to allocate memory!");
199 ptr::copy_memory(buf, self_buf, self_len);
200 *ptr::mut_offset(buf, self_len as int) = 0;
202 CString::new(buf as *libc::c_char, true)
207 /// External iterator for a CString's bytes.
209 /// Use with the `std::iterator` module.
210 pub struct CStringIterator<'self> {
211 priv ptr: *libc::c_char,
212 priv lifetime: &'self libc::c_char, // FIXME: #5922
215 impl<'self> Iterator<libc::c_char> for CStringIterator<'self> {
216 fn next(&mut self) -> Option<libc::c_char> {
217 let ch = unsafe { *self.ptr };
221 self.ptr = ptr::offset(self.ptr, 1);
232 use option::{Some, None};
236 do "".to_c_str().with_ref |buf| {
238 assert_eq!(*ptr::offset(buf, 0), 0);
242 do "hello".to_c_str().with_ref |buf| {
244 assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
245 assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
246 assert_eq!(*ptr::offset(buf, 2), 'l' as libc::c_char);
247 assert_eq!(*ptr::offset(buf, 3), 'l' as libc::c_char);
248 assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
249 assert_eq!(*ptr::offset(buf, 5), 0);
256 let c_str = unsafe { CString::new(ptr::null(), false) };
257 assert!(c_str.is_null());
258 assert!(!c_str.is_not_null());
263 let c_str = "hello".to_c_str();
264 unsafe { libc::free(c_str.unwrap() as *libc::c_void) }
269 let c_str = "hello".to_c_str();
270 let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
271 assert!(!c_str.is_null());
272 assert!(c_str.is_not_null());
278 #[ignore(cfg(windows))]
279 fn test_with_ref_empty_fail() {
280 let c_str = unsafe { CString::new(ptr::null(), false) };
281 c_str.with_ref(|_| ());
286 let c_str = "".to_c_str();
287 let mut iter = c_str.iter();
288 assert_eq!(iter.next(), None);
290 let c_str = "hello".to_c_str();
291 let mut iter = c_str.iter();
292 assert_eq!(iter.next(), Some('h' as libc::c_char));
293 assert_eq!(iter.next(), Some('e' as libc::c_char));
294 assert_eq!(iter.next(), Some('l' as libc::c_char));
295 assert_eq!(iter.next(), Some('l' as libc::c_char));
296 assert_eq!(iter.next(), Some('o' as libc::c_char));
297 assert_eq!(iter.next(), None);
301 #[ignore(cfg(windows))]
302 fn test_to_c_str_fail() {
303 use c_str::null_byte::cond;
305 let mut error_happened = false;
307 assert_eq!(err, bytes!("he", 0, "llo").to_owned())
308 error_happened = true;
311 "he\x00llo".to_c_str()
313 assert!(error_happened);
316 ReplaceWith('?' as libc::c_char)
317 }).inside(|| "he\x00llo".to_c_str()).with_ref |buf| {
319 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
320 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
321 assert_eq!(*buf.offset(2), '?' as libc::c_char);
322 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
323 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
324 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
325 assert_eq!(*buf.offset(6), 0);
331 fn test_to_c_str_unchecked() {
333 do "he\x00llo".to_c_str_unchecked().with_ref |buf| {
334 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
335 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
336 assert_eq!(*buf.offset(2), 0);
337 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
338 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
339 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
340 assert_eq!(*buf.offset(6), 0);