]> git.lizzy.rs Git - rust.git/blob - src/libstd/c_str.rs
auto merge of #11304 : alexcrichton/rust/eintr, r=brson
[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 /*!
12
13 C-string manipulation and management
14
15 This modules provides the basic methods for creating and manipulating
16 null-terminated strings for use with FFI calls (back to C). Most C APIs require
17 that the string being passed to them is null-terminated, and by default rust's
18 string types are *not* null terminated.
19
20 The other problem with translating Rust strings to C strings is that Rust
21 strings can validly contain a null-byte in the middle of the string (0 is a
22 valid unicode codepoint). This means that not all Rust strings can actually be
23 translated to C strings.
24
25 # Creation of a C string
26
27 A C string is managed through the `CString` type defined in this module. It
28 "owns" the internal buffer of characters and will automatically deallocate the
29 buffer when the string is dropped. The `ToCStr` trait is implemented for `&str`
30 and `&[u8]`, but the conversions can fail due to some of the limitations
31 explained above.
32
33 This also means that currently whenever a C string is created, an allocation
34 must be performed to place the data elsewhere (the lifetime of the C string is
35 not tied to the lifetime of the original string/data buffer). If C strings are
36 heavily used in applications, then caching may be advisable to prevent
37 unnecessary amounts of allocations.
38
39 An example of creating and using a C string would be:
40
41 ```rust
42 use std::libc;
43 extern {
44     fn puts(s: *libc::c_char);
45 }
46
47 let my_string = "Hello, world!";
48
49 // Allocate the C string with an explicit local that owns the string. The
50 // `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope.
51 let my_c_string = my_string.to_c_str();
52 my_c_string.with_ref(|c_buffer| {
53     unsafe { puts(c_buffer); }
54 });
55
56 // Don't save off the allocation of the C string, the `c_buffer` will be
57 // deallocated when this block returns!
58 my_string.with_c_str(|c_buffer| {
59     unsafe { puts(c_buffer); }
60 });
61  ```
62
63 */
64
65 use cast;
66 use container::Container;
67 use iter::{Iterator, range};
68 use libc;
69 use ops::Drop;
70 use option::{Option, Some, None};
71 use ptr::RawPtr;
72 use ptr;
73 use str::StrSlice;
74 use str;
75 use vec::{CopyableVector, ImmutableVector, MutableVector};
76 use vec;
77 use unstable::intrinsics;
78
79 /// Resolution options for the `null_byte` condition
80 pub enum NullByteResolution {
81     /// Truncate at the null byte
82     Truncate,
83     /// Use a replacement byte
84     ReplaceWith(libc::c_char)
85 }
86
87 condition! {
88     // This should be &[u8] but there's a lifetime issue (#5370).
89     pub null_byte: (~[u8]) -> NullByteResolution;
90 }
91
92 /// The representation of a C String.
93 ///
94 /// This structure wraps a `*libc::c_char`, and will automatically free the
95 /// memory it is pointing to when it goes out of scope.
96 pub struct CString {
97     priv buf: *libc::c_char,
98     priv owns_buffer_: bool,
99 }
100
101 impl CString {
102     /// Create a C String from a pointer.
103     pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString {
104         CString { buf: buf, owns_buffer_: owns_buffer }
105     }
106
107     /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
108     /// Any ownership of the buffer by the `CString` wrapper is forgotten.
109     pub unsafe fn unwrap(self) -> *libc::c_char {
110         let mut c_str = self;
111         c_str.owns_buffer_ = false;
112         c_str.buf
113     }
114
115     /// Calls a closure with a reference to the underlying `*libc::c_char`.
116     ///
117     /// # Failure
118     ///
119     /// Fails if the CString is null.
120     pub fn with_ref<T>(&self, f: |*libc::c_char| -> T) -> T {
121         if self.buf.is_null() { fail!("CString is null!"); }
122         f(self.buf)
123     }
124
125     /// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
126     ///
127     /// # Failure
128     ///
129     /// Fails if the CString is null.
130     pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T {
131         if self.buf.is_null() { fail!("CString is null!"); }
132         f(unsafe { cast::transmute_mut_unsafe(self.buf) })
133     }
134
135     /// Returns true if the CString is a null.
136     pub fn is_null(&self) -> bool {
137         self.buf.is_null()
138     }
139
140     /// Returns true if the CString is not null.
141     pub fn is_not_null(&self) -> bool {
142         self.buf.is_not_null()
143     }
144
145     /// Returns whether or not the `CString` owns the buffer.
146     pub fn owns_buffer(&self) -> bool {
147         self.owns_buffer_
148     }
149
150     /// Converts the CString into a `&[u8]` without copying.
151     ///
152     /// # Failure
153     ///
154     /// Fails if the CString is null.
155     #[inline]
156     pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
157         if self.buf.is_null() { fail!("CString is null!"); }
158         unsafe {
159             cast::transmute((self.buf, self.len() + 1))
160         }
161     }
162
163     /// Converts the CString into a `&str` without copying.
164     /// Returns None if the CString is not UTF-8 or is null.
165     #[inline]
166     pub fn as_str<'a>(&'a self) -> Option<&'a str> {
167         if self.buf.is_null() { return None; }
168         let buf = self.as_bytes();
169         let buf = buf.slice_to(buf.len()-1); // chop off the trailing NUL
170         str::from_utf8_opt(buf)
171     }
172
173     /// Return a CString iterator.
174     pub fn iter<'a>(&'a self) -> CStringIterator<'a> {
175         CStringIterator {
176             ptr: self.buf,
177             lifetime: unsafe { cast::transmute(self.buf) },
178         }
179     }
180 }
181
182 impl Drop for CString {
183     fn drop(&mut self) {
184         if self.owns_buffer_ {
185             unsafe {
186                 libc::free(self.buf as *libc::c_void)
187             }
188         }
189     }
190 }
191
192 impl Container for CString {
193     #[inline]
194     fn len(&self) -> uint {
195         unsafe {
196             ptr::position(self.buf, |c| *c == 0)
197         }
198     }
199 }
200
201 /// A generic trait for converting a value to a CString.
202 pub trait ToCStr {
203     /// Copy the receiver into a CString.
204     ///
205     /// # Failure
206     ///
207     /// Raises the `null_byte` condition if the receiver has an interior null.
208     fn to_c_str(&self) -> CString;
209
210     /// Unsafe variant of `to_c_str()` that doesn't check for nulls.
211     unsafe fn to_c_str_unchecked(&self) -> CString;
212
213     /// Work with a temporary CString constructed from the receiver.
214     /// The provided `*libc::c_char` will be freed immediately upon return.
215     ///
216     /// # Example
217     ///
218     /// ```rust
219     /// use std::libc;
220     ///
221     /// let s = "PATH".with_c_str(|path| unsafe {
222     ///     libc::getenv(path)
223     /// });
224     /// ```
225     ///
226     /// # Failure
227     ///
228     /// Raises the `null_byte` condition if the receiver has an interior null.
229     #[inline]
230     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
231         self.to_c_str().with_ref(f)
232     }
233
234     /// Unsafe variant of `with_c_str()` that doesn't check for nulls.
235     #[inline]
236     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
237         self.to_c_str_unchecked().with_ref(f)
238     }
239 }
240
241 impl<'a> ToCStr for &'a str {
242     #[inline]
243     fn to_c_str(&self) -> CString {
244         self.as_bytes().to_c_str()
245     }
246
247     #[inline]
248     unsafe fn to_c_str_unchecked(&self) -> CString {
249         self.as_bytes().to_c_str_unchecked()
250     }
251
252     #[inline]
253     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
254         self.as_bytes().with_c_str(f)
255     }
256
257     #[inline]
258     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
259         self.as_bytes().with_c_str_unchecked(f)
260     }
261 }
262
263 // The length of the stack allocated buffer for `vec.with_c_str()`
264 static BUF_LEN: uint = 128;
265
266 impl<'a> ToCStr for &'a [u8] {
267     fn to_c_str(&self) -> CString {
268         let mut cs = unsafe { self.to_c_str_unchecked() };
269         cs.with_mut_ref(|buf| check_for_null(*self, buf));
270         cs
271     }
272
273     unsafe fn to_c_str_unchecked(&self) -> CString {
274         let self_len = self.len();
275         let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8;
276         if buf.is_null() {
277             fail!("failed to allocate memory!");
278         }
279
280         ptr::copy_memory(buf, self.as_ptr(), self_len);
281         *ptr::mut_offset(buf, self_len as int) = 0;
282
283         CString::new(buf as *libc::c_char, true)
284     }
285
286     fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
287         unsafe { with_c_str(*self, true, f) }
288     }
289
290     unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
291         with_c_str(*self, false, f)
292     }
293 }
294
295 // Unsafe function that handles possibly copying the &[u8] into a stack array.
296 unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T {
297     if v.len() < BUF_LEN {
298         let mut buf: [u8, .. BUF_LEN] = intrinsics::uninit();
299         vec::bytes::copy_memory(buf, v);
300         buf[v.len()] = 0;
301
302         let buf = buf.as_mut_ptr();
303         if checked {
304             check_for_null(v, buf as *mut libc::c_char);
305         }
306
307         f(buf as *libc::c_char)
308     } else if checked {
309         v.to_c_str().with_ref(f)
310     } else {
311         v.to_c_str_unchecked().with_ref(f)
312     }
313 }
314
315 #[inline]
316 fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
317     for i in range(0, v.len()) {
318         unsafe {
319             let p = buf.offset(i as int);
320             if *p == 0 {
321                 match null_byte::cond.raise(v.to_owned()) {
322                     Truncate => break,
323                     ReplaceWith(c) => *p = c
324                 }
325             }
326         }
327     }
328 }
329
330 /// External iterator for a CString's bytes.
331 ///
332 /// Use with the `std::iter` module.
333 pub struct CStringIterator<'a> {
334     priv ptr: *libc::c_char,
335     priv lifetime: &'a libc::c_char, // FIXME: #5922
336 }
337
338 impl<'a> Iterator<libc::c_char> for CStringIterator<'a> {
339     fn next(&mut self) -> Option<libc::c_char> {
340         let ch = unsafe { *self.ptr };
341         if ch == 0 {
342             None
343         } else {
344             self.ptr = unsafe { ptr::offset(self.ptr, 1) };
345             Some(ch)
346         }
347     }
348 }
349
350 /// Parses a C "multistring", eg windows env values or
351 /// the req->ptr result in a uv_fs_readdir() call.
352 ///
353 /// Optionally, a `count` can be passed in, limiting the
354 /// parsing to only being done `count`-times.
355 ///
356 /// The specified closure is invoked with each string that
357 /// is found, and the number of strings found is returned.
358 pub unsafe fn from_c_multistring(buf: *libc::c_char,
359                                  count: Option<uint>,
360                                  f: |&CString|) -> uint {
361
362     let mut curr_ptr: uint = buf as uint;
363     let mut ctr = 0;
364     let (limited_count, limit) = match count {
365         Some(limit) => (true, limit),
366         None => (false, 0)
367     };
368     while ((limited_count && ctr < limit) || !limited_count)
369           && *(curr_ptr as *libc::c_char) != 0 as libc::c_char {
370         let cstr = CString::new(curr_ptr as *libc::c_char, false);
371         f(&cstr);
372         curr_ptr += cstr.len() + 1;
373         ctr += 1;
374     }
375     return ctr;
376 }
377
378 #[cfg(test)]
379 mod tests {
380     use super::*;
381     use libc;
382     use ptr;
383     use option::{Some, None};
384
385     #[test]
386     fn test_str_multistring_parsing() {
387         unsafe {
388             let input = bytes!("zero", "\x00", "one", "\x00", "\x00");
389             let ptr = input.as_ptr();
390             let expected = ["zero", "one"];
391             let mut it = expected.iter();
392             let result = from_c_multistring(ptr as *libc::c_char, None, |c| {
393                 let cbytes = c.as_bytes().slice_to(c.len());
394                 assert_eq!(cbytes, it.next().unwrap().as_bytes());
395             });
396             assert_eq!(result, 2);
397             assert!(it.next().is_none());
398         }
399     }
400
401     #[test]
402     fn test_str_to_c_str() {
403         "".to_c_str().with_ref(|buf| {
404             unsafe {
405                 assert_eq!(*ptr::offset(buf, 0), 0);
406             }
407         });
408
409         "hello".to_c_str().with_ref(|buf| {
410             unsafe {
411                 assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
412                 assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
413                 assert_eq!(*ptr::offset(buf, 2), 'l' as libc::c_char);
414                 assert_eq!(*ptr::offset(buf, 3), 'l' as libc::c_char);
415                 assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
416                 assert_eq!(*ptr::offset(buf, 5), 0);
417             }
418         })
419     }
420
421     #[test]
422     fn test_vec_to_c_str() {
423         let b: &[u8] = [];
424         b.to_c_str().with_ref(|buf| {
425             unsafe {
426                 assert_eq!(*ptr::offset(buf, 0), 0);
427             }
428         });
429
430         let _ = bytes!("hello").to_c_str().with_ref(|buf| {
431             unsafe {
432                 assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
433                 assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
434                 assert_eq!(*ptr::offset(buf, 2), 'l' as libc::c_char);
435                 assert_eq!(*ptr::offset(buf, 3), 'l' as libc::c_char);
436                 assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
437                 assert_eq!(*ptr::offset(buf, 5), 0);
438             }
439         });
440
441         let _ = bytes!("foo", 0xff).to_c_str().with_ref(|buf| {
442             unsafe {
443                 assert_eq!(*ptr::offset(buf, 0), 'f' as libc::c_char);
444                 assert_eq!(*ptr::offset(buf, 1), 'o' as libc::c_char);
445                 assert_eq!(*ptr::offset(buf, 2), 'o' as libc::c_char);
446                 assert_eq!(*ptr::offset(buf, 3), 0xff as i8);
447                 assert_eq!(*ptr::offset(buf, 4), 0);
448             }
449         });
450     }
451
452     #[test]
453     fn test_is_null() {
454         let c_str = unsafe { CString::new(ptr::null(), false) };
455         assert!(c_str.is_null());
456         assert!(!c_str.is_not_null());
457     }
458
459     #[test]
460     fn test_unwrap() {
461         let c_str = "hello".to_c_str();
462         unsafe { libc::free(c_str.unwrap() as *libc::c_void) }
463     }
464
465     #[test]
466     fn test_with_ref() {
467         let c_str = "hello".to_c_str();
468         let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
469         assert!(!c_str.is_null());
470         assert!(c_str.is_not_null());
471         assert_eq!(len, 5);
472     }
473
474     #[test]
475     #[should_fail]
476     fn test_with_ref_empty_fail() {
477         let c_str = unsafe { CString::new(ptr::null(), false) };
478         c_str.with_ref(|_| ());
479     }
480
481     #[test]
482     fn test_iterator() {
483         let c_str = "".to_c_str();
484         let mut iter = c_str.iter();
485         assert_eq!(iter.next(), None);
486
487         let c_str = "hello".to_c_str();
488         let mut iter = c_str.iter();
489         assert_eq!(iter.next(), Some('h' as libc::c_char));
490         assert_eq!(iter.next(), Some('e' as libc::c_char));
491         assert_eq!(iter.next(), Some('l' as libc::c_char));
492         assert_eq!(iter.next(), Some('l' as libc::c_char));
493         assert_eq!(iter.next(), Some('o' as libc::c_char));
494         assert_eq!(iter.next(), None);
495     }
496
497     #[test]
498     fn test_to_c_str_fail() {
499         use c_str::null_byte::cond;
500
501         let mut error_happened = false;
502         cond.trap(|err| {
503             assert_eq!(err, bytes!("he", 0, "llo").to_owned())
504             error_happened = true;
505             Truncate
506         }).inside(|| "he\x00llo".to_c_str());
507         assert!(error_happened);
508
509         cond.trap(|_| {
510             ReplaceWith('?' as libc::c_char)
511         }).inside(|| "he\x00llo".to_c_str()).with_ref(|buf| {
512             unsafe {
513                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
514                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
515                 assert_eq!(*buf.offset(2), '?' as libc::c_char);
516                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
517                 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
518                 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
519                 assert_eq!(*buf.offset(6), 0);
520             }
521         })
522     }
523
524     #[test]
525     fn test_to_c_str_unchecked() {
526         unsafe {
527             "he\x00llo".to_c_str_unchecked().with_ref(|buf| {
528                 assert_eq!(*buf.offset(0), 'h' as libc::c_char);
529                 assert_eq!(*buf.offset(1), 'e' as libc::c_char);
530                 assert_eq!(*buf.offset(2), 0);
531                 assert_eq!(*buf.offset(3), 'l' as libc::c_char);
532                 assert_eq!(*buf.offset(4), 'l' as libc::c_char);
533                 assert_eq!(*buf.offset(5), 'o' as libc::c_char);
534                 assert_eq!(*buf.offset(6), 0);
535             })
536         }
537     }
538
539     #[test]
540     fn test_as_bytes() {
541         let c_str = "hello".to_c_str();
542         assert_eq!(c_str.as_bytes(), bytes!("hello", 0));
543         let c_str = "".to_c_str();
544         assert_eq!(c_str.as_bytes(), bytes!(0));
545         let c_str = bytes!("foo", 0xff).to_c_str();
546         assert_eq!(c_str.as_bytes(), bytes!("foo", 0xff, 0));
547     }
548
549     #[test]
550     #[should_fail]
551     fn test_as_bytes_fail() {
552         let c_str = unsafe { CString::new(ptr::null(), false) };
553         c_str.as_bytes();
554     }
555
556     #[test]
557     fn test_as_str() {
558         let c_str = "hello".to_c_str();
559         assert_eq!(c_str.as_str(), Some("hello"));
560         let c_str = "".to_c_str();
561         assert_eq!(c_str.as_str(), Some(""));
562         let c_str = bytes!("foo", 0xff).to_c_str();
563         assert_eq!(c_str.as_str(), None);
564         let c_str = unsafe { CString::new(ptr::null(), false) };
565         assert_eq!(c_str.as_str(), None);
566     }
567 }
568
569 #[cfg(test)]
570 mod bench {
571     use iter::range;
572     use libc;
573     use option::Some;
574     use ptr;
575     use extra::test::BenchHarness;
576
577     #[inline]
578     fn check(s: &str, c_str: *libc::c_char) {
579         let s_buf = s.as_ptr();
580         for i in range(0, s.len()) {
581             unsafe {
582                 assert_eq!(
583                     *ptr::offset(s_buf, i as int) as libc::c_char,
584                     *ptr::offset(c_str, i as int));
585             }
586         }
587     }
588
589     static s_short: &'static str = "Mary";
590     static s_medium: &'static str = "Mary had a little lamb";
591     static s_long: &'static str = "\
592         Mary had a little lamb, Little lamb
593         Mary had a little lamb, Little lamb
594         Mary had a little lamb, Little lamb
595         Mary had a little lamb, Little lamb
596         Mary had a little lamb, Little lamb
597         Mary had a little lamb, Little lamb";
598
599     fn bench_to_str(bh: &mut BenchHarness, s: &str) {
600         bh.iter(|| {
601             let c_str = s.to_c_str();
602             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
603         })
604     }
605
606     #[bench]
607     fn bench_to_c_str_short(bh: &mut BenchHarness) {
608         bench_to_str(bh, s_short)
609     }
610
611     #[bench]
612     fn bench_to_c_str_medium(bh: &mut BenchHarness) {
613         bench_to_str(bh, s_medium)
614     }
615
616     #[bench]
617     fn bench_to_c_str_long(bh: &mut BenchHarness) {
618         bench_to_str(bh, s_long)
619     }
620
621     fn bench_to_c_str_unchecked(bh: &mut BenchHarness, s: &str) {
622         bh.iter(|| {
623             let c_str = unsafe { s.to_c_str_unchecked() };
624             c_str.with_ref(|c_str_buf| check(s, c_str_buf))
625         })
626     }
627
628     #[bench]
629     fn bench_to_c_str_unchecked_short(bh: &mut BenchHarness) {
630         bench_to_c_str_unchecked(bh, s_short)
631     }
632
633     #[bench]
634     fn bench_to_c_str_unchecked_medium(bh: &mut BenchHarness) {
635         bench_to_c_str_unchecked(bh, s_medium)
636     }
637
638     #[bench]
639     fn bench_to_c_str_unchecked_long(bh: &mut BenchHarness) {
640         bench_to_c_str_unchecked(bh, s_long)
641     }
642
643     fn bench_with_c_str(bh: &mut BenchHarness, s: &str) {
644         bh.iter(|| {
645             s.with_c_str(|c_str_buf| check(s, c_str_buf))
646         })
647     }
648
649     #[bench]
650     fn bench_with_c_str_short(bh: &mut BenchHarness) {
651         bench_with_c_str(bh, s_short)
652     }
653
654     #[bench]
655     fn bench_with_c_str_medium(bh: &mut BenchHarness) {
656         bench_with_c_str(bh, s_medium)
657     }
658
659     #[bench]
660     fn bench_with_c_str_long(bh: &mut BenchHarness) {
661         bench_with_c_str(bh, s_long)
662     }
663
664     fn bench_with_c_str_unchecked(bh: &mut BenchHarness, s: &str) {
665         bh.iter(|| {
666             unsafe {
667                 s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
668             }
669         })
670     }
671
672     #[bench]
673     fn bench_with_c_str_unchecked_short(bh: &mut BenchHarness) {
674         bench_with_c_str_unchecked(bh, s_short)
675     }
676
677     #[bench]
678     fn bench_with_c_str_unchecked_medium(bh: &mut BenchHarness) {
679         bench_with_c_str_unchecked(bh, s_medium)
680     }
681
682     #[bench]
683     fn bench_with_c_str_unchecked_long(bh: &mut BenchHarness) {
684         bench_with_c_str_unchecked(bh, s_long)
685     }
686 }