]> git.lizzy.rs Git - rust.git/blob - src/libstd/c_str.rs
Add ToCStr method .with_c_str()
[rust.git] / src / libstd / c_str.rs
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.
4 //
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.
10
11 use cast;
12 use iterator::{Iterator,range};
13 use libc;
14 use ops::Drop;
15 use option::{Option, Some, None};
16 use ptr::RawPtr;
17 use ptr;
18 use str::StrSlice;
19 use vec::{ImmutableVector,CopyableVector};
20 use container::Container;
21
22 /// Resolution options for the `null_byte` condition
23 pub enum NullByteResolution {
24     /// Truncate at the null byte
25     Truncate,
26     /// Use a replacement byte
27     ReplaceWith(libc::c_char)
28 }
29
30 condition! {
31     // this should be &[u8] but there's a lifetime issue
32     null_byte: (~[u8]) -> super::NullByteResolution;
33 }
34
35 /// The representation of a C String.
36 ///
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.
39 pub struct CString {
40     priv buf: *libc::c_char,
41     priv owns_buffer_: bool,
42 }
43
44 impl CString {
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 }
48     }
49
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 {
53         let mut c_str = self;
54         c_str.owns_buffer_ = false;
55         c_str.buf
56     }
57
58     /// Calls a closure with a reference to the underlying `*libc::c_char`.
59     ///
60     /// # Failure
61     ///
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!"); }
65         f(self.buf)
66     }
67
68     /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
69     ///
70     /// # Failure
71     ///
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) })
76     }
77
78     /// Returns true if the CString is a null.
79     pub fn is_null(&self) -> bool {
80         self.buf.is_null()
81     }
82
83     /// Returns true if the CString is not null.
84     pub fn is_not_null(&self) -> bool {
85         self.buf.is_not_null()
86     }
87
88     /// Returns whether or not the `CString` owns the buffer.
89     pub fn owns_buffer(&self) -> bool {
90         self.owns_buffer_
91     }
92
93     /// Converts the CString into a `&[u8]` without copying.
94     ///
95     /// # Failure
96     ///
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!"); }
100         unsafe {
101             let len = libc::strlen(self.buf) as uint;
102             cast::transmute((self.buf, len + 1))
103         }
104     }
105
106     /// Return a CString iterator.
107     fn iter<'a>(&'a self) -> CStringIterator<'a> {
108         CStringIterator {
109             ptr: self.buf,
110             lifetime: unsafe { cast::transmute(self.buf) },
111         }
112     }
113 }
114
115 impl Drop for CString {
116     fn drop(&self) {
117         if self.owns_buffer_ {
118             unsafe {
119                 libc::free(self.buf as *libc::c_void)
120             }
121         }
122     }
123 }
124
125 /// A generic trait for converting a value to a CString.
126 pub trait ToCStr {
127     /// Copy the receiver into a CString.
128     ///
129     /// # Failure
130     ///
131     /// Raises the `null_byte` condition if the receiver has an interior null.
132     fn to_c_str(&self) -> CString;
133
134     /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
135     unsafe fn to_c_str_unchecked(&self) -> CString;
136
137     /// Work with a temporary CString constructed from the receiver.
138     /// The provided `*libc::c_char` will be freed immediately upon return.
139     ///
140     /// # Example
141     ///
142     /// ~~~ {.rust}
143     /// let s = "PATH".with_c_str(|path| libc::getenv(path))
144     /// ~~~
145     ///
146     /// # Failure
147     ///
148     /// Raises the `null_byte` condition if the receiver has an interior null.
149     #[inline]
150     fn with_c_str<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
151         self.to_c_str().with_ref(f)
152     }
153
154     /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
155     #[inline]
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)
158     }
159 }
160
161 impl<'self> ToCStr for &'self str {
162     #[inline]
163     fn to_c_str(&self) -> CString {
164         self.as_bytes().to_c_str()
165     }
166
167     #[inline]
168     unsafe fn to_c_str_unchecked(&self) -> CString {
169         self.as_bytes().to_c_str_unchecked()
170     }
171 }
172
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()) {
178                 unsafe {
179                     let p = buf.offset_inbounds(i as int);
180                     if *p == 0 {
181                         match null_byte::cond.raise(self.to_owned()) {
182                             Truncate => break,
183                             ReplaceWith(c) => *p = c
184                         }
185                     }
186                 }
187             }
188         }
189         cs
190     }
191
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;
195             if buf.is_null() {
196                 fail!("failed to allocate memory!");
197             }
198
199             ptr::copy_memory(buf, self_buf, self_len);
200             *ptr::mut_offset(buf, self_len as int) = 0;
201
202             CString::new(buf as *libc::c_char, true)
203         }
204     }
205 }
206
207 /// External iterator for a CString's bytes.
208 ///
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
213 }
214
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 };
218         if ch == 0 {
219             None
220         } else {
221             self.ptr = ptr::offset(self.ptr, 1);
222             Some(ch)
223         }
224     }
225 }
226
227 #[cfg(test)]
228 mod tests {
229     use super::*;
230     use libc;
231     use ptr;
232     use option::{Some, None};
233
234     #[test]
235     fn test_to_c_str() {
236         do "".to_c_str().with_ref |buf| {
237             unsafe {
238                 assert_eq!(*ptr::offset(buf, 0), 0);
239             }
240         }
241
242         do "hello".to_c_str().with_ref |buf| {
243             unsafe {
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);
250             }
251         }
252     }
253
254     #[test]
255     fn test_is_null() {
256         let c_str = unsafe { CString::new(ptr::null(), false) };
257         assert!(c_str.is_null());
258         assert!(!c_str.is_not_null());
259     }
260
261     #[test]
262     fn test_unwrap() {
263         let c_str = "hello".to_c_str();
264         unsafe { libc::free(c_str.unwrap() as *libc::c_void) }
265     }
266
267     #[test]
268     fn test_with_ref() {
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());
273         assert_eq!(len, 5);
274     }
275
276     #[test]
277     #[should_fail]
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(|_| ());
282     }
283
284     #[test]
285     fn test_iterator() {
286         let c_str = "".to_c_str();
287         let mut iter = c_str.iter();
288         assert_eq!(iter.next(), None);
289
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);
298     }
299
300     #[test]
301     #[ignore(cfg(windows))]
302     fn test_to_c_str_fail() {
303         use c_str::null_byte::cond;
304
305         let mut error_happened = false;
306         do cond.trap(|err| {
307             assert_eq!(err, bytes!("he", 0, "llo").to_owned())
308             error_happened = true;
309             Truncate
310         }).inside {
311             "he\x00llo".to_c_str()
312         };
313         assert!(error_happened);
314
315         do cond.trap(|_| {
316             ReplaceWith('?' as libc::c_char)
317         }).inside(|| "he\x00llo".to_c_str()).with_ref |buf| {
318             unsafe {
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);
326             }
327         }
328     }
329
330     #[test]
331     fn test_to_c_str_unchecked() {
332         unsafe {
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);
341             }
342         }
343     }
344 }