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;
138 impl<'self> ToCStr for &'self str {
140 fn to_c_str(&self) -> CString {
141 self.as_bytes().to_c_str()
145 unsafe fn to_c_str_unchecked(&self) -> CString {
146 self.as_bytes().to_c_str_unchecked()
150 impl<'self> ToCStr for &'self [u8] {
151 fn to_c_str(&self) -> CString {
152 let mut cs = unsafe { self.to_c_str_unchecked() };
153 do cs.with_mut_ref |buf| {
154 for i in range(0, self.len()) {
156 let p = buf.offset_inbounds(i as int);
158 match null_byte::cond.raise(self.to_owned()) {
160 ReplaceWith(c) => *p = c
169 unsafe fn to_c_str_unchecked(&self) -> CString {
170 do self.as_imm_buf |self_buf, self_len| {
171 let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8;
173 fail!("failed to allocate memory!");
176 ptr::copy_memory(buf, self_buf, self_len);
177 *ptr::mut_offset(buf, self_len as int) = 0;
179 CString::new(buf as *libc::c_char, true)
184 /// External iterator for a CString's bytes.
186 /// Use with the `std::iterator` module.
187 pub struct CStringIterator<'self> {
188 priv ptr: *libc::c_char,
189 priv lifetime: &'self libc::c_char, // FIXME: #5922
192 impl<'self> Iterator<libc::c_char> for CStringIterator<'self> {
193 fn next(&mut self) -> Option<libc::c_char> {
194 let ch = unsafe { *self.ptr };
198 self.ptr = ptr::offset(self.ptr, 1);
209 use option::{Some, None};
213 do "".to_c_str().with_ref |buf| {
215 assert_eq!(*ptr::offset(buf, 0), 0);
219 do "hello".to_c_str().with_ref |buf| {
221 assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
222 assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
223 assert_eq!(*ptr::offset(buf, 2), 'l' as libc::c_char);
224 assert_eq!(*ptr::offset(buf, 3), 'l' as libc::c_char);
225 assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
226 assert_eq!(*ptr::offset(buf, 5), 0);
233 let c_str = unsafe { CString::new(ptr::null(), false) };
234 assert!(c_str.is_null());
235 assert!(!c_str.is_not_null());
240 let c_str = "hello".to_c_str();
241 unsafe { libc::free(c_str.unwrap() as *libc::c_void) }
246 let c_str = "hello".to_c_str();
247 let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
248 assert!(!c_str.is_null());
249 assert!(c_str.is_not_null());
255 #[ignore(cfg(windows))]
256 fn test_with_ref_empty_fail() {
257 let c_str = unsafe { CString::new(ptr::null(), false) };
258 c_str.with_ref(|_| ());
263 let c_str = "".to_c_str();
264 let mut iter = c_str.iter();
265 assert_eq!(iter.next(), None);
267 let c_str = "hello".to_c_str();
268 let mut iter = c_str.iter();
269 assert_eq!(iter.next(), Some('h' as libc::c_char));
270 assert_eq!(iter.next(), Some('e' as libc::c_char));
271 assert_eq!(iter.next(), Some('l' as libc::c_char));
272 assert_eq!(iter.next(), Some('l' as libc::c_char));
273 assert_eq!(iter.next(), Some('o' as libc::c_char));
274 assert_eq!(iter.next(), None);
278 #[ignore(cfg(windows))]
279 fn test_to_c_str_fail() {
280 use c_str::null_byte::cond;
282 let mut error_happened = false;
284 assert_eq!(err, bytes!("he", 0, "llo").to_owned())
285 error_happened = true;
288 "he\x00llo".to_c_str()
290 assert!(error_happened);
293 ReplaceWith('?' as libc::c_char)
294 }).inside(|| "he\x00llo".to_c_str()).with_ref |buf| {
296 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
297 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
298 assert_eq!(*buf.offset(2), '?' as libc::c_char);
299 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
300 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
301 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
302 assert_eq!(*buf.offset(6), 0);
308 fn test_to_c_str_unchecked() {
310 do "he\x00llo".to_c_str_unchecked().with_ref |buf| {
311 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
312 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
313 assert_eq!(*buf.offset(2), 0);
314 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
315 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
316 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
317 assert_eq!(*buf.offset(6), 0);