]> git.lizzy.rs Git - rust.git/blob - src/libstd/c_str.rs
5c77aa4a65aa32f364163f329bd0c3b5a3639c82
[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
138 impl<'self> ToCStr for &'self str {
139     #[inline]
140     fn to_c_str(&self) -> CString {
141         self.as_bytes().to_c_str()
142     }
143
144     #[inline]
145     unsafe fn to_c_str_unchecked(&self) -> CString {
146         self.as_bytes().to_c_str_unchecked()
147     }
148 }
149
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()) {
155                 unsafe {
156                     let p = buf.offset_inbounds(i as int);
157                     if *p == 0 {
158                         match null_byte::cond.raise(self.to_owned()) {
159                             Truncate => break,
160                             ReplaceWith(c) => *p = c
161                         }
162                     }
163                 }
164             }
165         }
166         cs
167     }
168
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;
172             if buf.is_null() {
173                 fail!("failed to allocate memory!");
174             }
175
176             ptr::copy_memory(buf, self_buf, self_len);
177             *ptr::mut_offset(buf, self_len as int) = 0;
178
179             CString::new(buf as *libc::c_char, true)
180         }
181     }
182 }
183
184 /// External iterator for a CString's bytes.
185 ///
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
190 }
191
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 };
195         if ch == 0 {
196             None
197         } else {
198             self.ptr = ptr::offset(self.ptr, 1);
199             Some(ch)
200         }
201     }
202 }
203
204 #[cfg(test)]
205 mod tests {
206     use super::*;
207     use libc;
208     use ptr;
209     use option::{Some, None};
210
211     #[test]
212     fn test_to_c_str() {
213         do "".to_c_str().with_ref |buf| {
214             unsafe {
215                 assert_eq!(*ptr::offset(buf, 0), 0);
216             }
217         }
218
219         do "hello".to_c_str().with_ref |buf| {
220             unsafe {
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);
227             }
228         }
229     }
230
231     #[test]
232     fn test_is_null() {
233         let c_str = unsafe { CString::new(ptr::null(), false) };
234         assert!(c_str.is_null());
235         assert!(!c_str.is_not_null());
236     }
237
238     #[test]
239     fn test_unwrap() {
240         let c_str = "hello".to_c_str();
241         unsafe { libc::free(c_str.unwrap() as *libc::c_void) }
242     }
243
244     #[test]
245     fn test_with_ref() {
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());
250         assert_eq!(len, 5);
251     }
252
253     #[test]
254     #[should_fail]
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(|_| ());
259     }
260
261     #[test]
262     fn test_iterator() {
263         let c_str = "".to_c_str();
264         let mut iter = c_str.iter();
265         assert_eq!(iter.next(), None);
266
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);
275     }
276
277     #[test]
278     #[ignore(cfg(windows))]
279     fn test_to_c_str_fail() {
280         use c_str::null_byte::cond;
281
282         let mut error_happened = false;
283         do cond.trap(|err| {
284             assert_eq!(err, bytes!("he", 0, "llo").to_owned())
285             error_happened = true;
286             Truncate
287         }).inside {
288             "he\x00llo".to_c_str()
289         };
290         assert!(error_happened);
291
292         do cond.trap(|_| {
293             ReplaceWith('?' as libc::c_char)
294         }).inside(|| "he\x00llo".to_c_str()).with_ref |buf| {
295             unsafe {
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);
303             }
304         }
305     }
306
307     #[test]
308     fn test_to_c_str_unchecked() {
309         unsafe {
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);
318             }
319         }
320     }
321 }