]> git.lizzy.rs Git - rust.git/blob - src/libstd/c_str.rs
a2842efbf8a04dbeabd32582fdc131f4ed4fd071
[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 iter::{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;
19 use str::StrSlice;
20 use vec::{ImmutableVector, CopyableVector};
21 use container::Container;
22
23 /// Resolution options for the `null_byte` condition
24 pub enum NullByteResolution {
25     /// Truncate at the null byte
26     Truncate,
27     /// Use a replacement byte
28     ReplaceWith(libc::c_char)
29 }
30
31 condition! {
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;
36 }
37
38 /// The representation of a C String.
39 ///
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.
42 pub struct CString {
43     priv buf: *libc::c_char,
44     priv owns_buffer_: bool,
45 }
46
47 impl CString {
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 }
51     }
52
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 {
56         let mut c_str = self;
57         c_str.owns_buffer_ = false;
58         c_str.buf
59     }
60
61     /// Calls a closure with a reference to the underlying `*libc::c_char`.
62     ///
63     /// # Failure
64     ///
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!"); }
68         f(self.buf)
69     }
70
71     /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
72     ///
73     /// # Failure
74     ///
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) })
79     }
80
81     /// Returns true if the CString is a null.
82     pub fn is_null(&self) -> bool {
83         self.buf.is_null()
84     }
85
86     /// Returns true if the CString is not null.
87     pub fn is_not_null(&self) -> bool {
88         self.buf.is_not_null()
89     }
90
91     /// Returns whether or not the `CString` owns the buffer.
92     pub fn owns_buffer(&self) -> bool {
93         self.owns_buffer_
94     }
95
96     /// Converts the CString into a `&[u8]` without copying.
97     ///
98     /// # Failure
99     ///
100     /// Fails if the CString is null.
101     #[inline]
102     pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
103         if self.buf.is_null() { fail!("CString is null!"); }
104         unsafe {
105             let len = ptr::position(self.buf, |c| *c == 0);
106             cast::transmute((self.buf, len + 1))
107         }
108     }
109
110     /// Converts the CString into a `&str` without copying.
111     /// Returns None if the CString is not UTF-8 or is null.
112     #[inline]
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)
118     }
119
120     /// Return a CString iterator.
121     pub fn iter<'a>(&'a self) -> CStringIterator<'a> {
122         CStringIterator {
123             ptr: self.buf,
124             lifetime: unsafe { cast::transmute(self.buf) },
125         }
126     }
127 }
128
129 impl Drop for CString {
130     fn drop(&self) {
131         #[fixed_stack_segment]; #[inline(never)];
132         if self.owns_buffer_ {
133             unsafe {
134                 libc::free(self.buf as *libc::c_void)
135             }
136         }
137     }
138 }
139
140 /// A generic trait for converting a value to a CString.
141 pub trait ToCStr {
142     /// Copy the receiver into a CString.
143     ///
144     /// # Failure
145     ///
146     /// Raises the `null_byte` condition if the receiver has an interior null.
147     fn to_c_str(&self) -> CString;
148
149     /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
150     unsafe fn to_c_str_unchecked(&self) -> CString;
151
152     /// Work with a temporary CString constructed from the receiver.
153     /// The provided `*libc::c_char` will be freed immediately upon return.
154     ///
155     /// # Example
156     ///
157     /// ~~~ {.rust}
158     /// let s = "PATH".with_c_str(|path| libc::getenv(path))
159     /// ~~~
160     ///
161     /// # Failure
162     ///
163     /// Raises the `null_byte` condition if the receiver has an interior null.
164     #[inline]
165     fn with_c_str<T>(&self, f: &fn(*libc::c_char) -> T) -> T {
166         self.to_c_str().with_ref(f)
167     }
168
169     /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
170     #[inline]
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)
173     }
174 }
175
176 impl<'self> ToCStr for &'self str {
177     #[inline]
178     fn to_c_str(&self) -> CString {
179         self.as_bytes().to_c_str()
180     }
181
182     #[inline]
183     unsafe fn to_c_str_unchecked(&self) -> CString {
184         self.as_bytes().to_c_str_unchecked()
185     }
186 }
187
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()) {
194                 unsafe {
195                     let p = buf.offset(i as int);
196                     if *p == 0 {
197                         match null_byte::cond.raise(self.to_owned()) {
198                             Truncate => break,
199                             ReplaceWith(c) => *p = c
200                         }
201                     }
202                 }
203             }
204         }
205         cs
206     }
207
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;
212             if buf.is_null() {
213                 fail!("failed to allocate memory!");
214             }
215
216             ptr::copy_memory(buf, self_buf, self_len);
217             *ptr::mut_offset(buf, self_len as int) = 0;
218
219             CString::new(buf as *libc::c_char, true)
220         }
221     }
222 }
223
224 /// External iterator for a CString's bytes.
225 ///
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
230 }
231
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 };
235         if ch == 0 {
236             None
237         } else {
238             self.ptr = unsafe { ptr::offset(self.ptr, 1) };
239             Some(ch)
240         }
241     }
242 }
243
244 #[cfg(test)]
245 mod tests {
246     use super::*;
247     use libc;
248     use ptr;
249     use option::{Some, None};
250
251     #[test]
252     fn test_str_to_c_str() {
253         do "".to_c_str().with_ref |buf| {
254             unsafe {
255                 assert_eq!(*ptr::offset(buf, 0), 0);
256             }
257         }
258
259         do "hello".to_c_str().with_ref |buf| {
260             unsafe {
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);
267             }
268         }
269     }
270
271     #[test]
272     fn test_vec_to_c_str() {
273         let b: &[u8] = [];
274         do b.to_c_str().with_ref |buf| {
275             unsafe {
276                 assert_eq!(*ptr::offset(buf, 0), 0);
277             }
278         }
279
280         do bytes!("hello").to_c_str().with_ref |buf| {
281             unsafe {
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);
288             }
289         }
290
291         do bytes!("foo", 0xff).to_c_str().with_ref |buf| {
292             unsafe {
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);
298             }
299         }
300     }
301
302     #[test]
303     fn test_is_null() {
304         let c_str = unsafe { CString::new(ptr::null(), false) };
305         assert!(c_str.is_null());
306         assert!(!c_str.is_not_null());
307     }
308
309     #[test]
310     fn test_unwrap() {
311         #[fixed_stack_segment]; #[inline(never)];
312
313         let c_str = "hello".to_c_str();
314         unsafe { libc::free(c_str.unwrap() as *libc::c_void) }
315     }
316
317     #[test]
318     fn test_with_ref() {
319         #[fixed_stack_segment]; #[inline(never)];
320
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());
325         assert_eq!(len, 5);
326     }
327
328     #[test]
329     #[should_fail]
330     fn test_with_ref_empty_fail() {
331         let c_str = unsafe { CString::new(ptr::null(), false) };
332         c_str.with_ref(|_| ());
333     }
334
335     #[test]
336     fn test_iterator() {
337         let c_str = "".to_c_str();
338         let mut iter = c_str.iter();
339         assert_eq!(iter.next(), None);
340
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);
349     }
350
351     #[test]
352     fn test_to_c_str_fail() {
353         use c_str::null_byte::cond;
354
355         let mut error_happened = false;
356         do cond.trap(|err| {
357             assert_eq!(err, bytes!("he", 0, "llo").to_owned())
358             error_happened = true;
359             Truncate
360         }).inside {
361             "he\x00llo".to_c_str()
362         };
363         assert!(error_happened);
364
365         do cond.trap(|_| {
366             ReplaceWith('?' as libc::c_char)
367         }).inside(|| "he\x00llo".to_c_str()).with_ref |buf| {
368             unsafe {
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);
376             }
377         }
378     }
379
380     #[test]
381     fn test_to_c_str_unchecked() {
382         unsafe {
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);
391             }
392         }
393     }
394
395     #[test]
396     fn test_as_bytes() {
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));
403     }
404
405     #[test]
406     #[should_fail]
407     fn test_as_bytes_fail() {
408         let c_str = unsafe { CString::new(ptr::null(), false) };
409         c_str.as_bytes();
410     }
411
412     #[test]
413     fn test_as_str() {
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);
422     }
423 }