about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorKevin Ballard <kevin@sb.org>2014-01-30 15:29:36 -0800
committerAlex Crichton <alex@alexcrichton.com>2014-01-31 21:43:09 -0800
commitcad4fcd21b0e620830b818037101e523323746ea (patch)
treef79fe9466bcface9ff3f7d724c840cfb1a361a2f /src/libstd
parenta9f73b5e3d947c3b8ef8c3a8fbd30823ba099886 (diff)
downloadrust-cad4fcd21b0e620830b818037101e523323746ea.tar.gz
rust-cad4fcd21b0e620830b818037101e523323746ea.zip
Test for null buffer in CString.len()/.iter() and fail
Also change .as_str() to fail on null buffer.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/c_str.rs39
1 files changed, 36 insertions, 3 deletions
diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs
index ded80d07003..b7374b6f15d 100644
--- a/src/libstd/c_str.rs
+++ b/src/libstd/c_str.rs
@@ -162,17 +162,25 @@ impl CString {
     }
 
     /// Converts the CString into a `&str` without copying.
-    /// Returns None if the CString is not UTF-8 or is null.
+    /// Returns None if the CString is not UTF-8.
+    ///
+    /// # Failure
+    ///
+    /// Fails if the CString is null.
     #[inline]
     pub fn as_str<'a>(&'a self) -> Option<&'a str> {
-        if self.buf.is_null() { return None; }
         let buf = self.as_bytes();
         let buf = buf.slice_to(buf.len()-1); // chop off the trailing NUL
         str::from_utf8(buf)
     }
 
     /// Return a CString iterator.
+    ///
+    /// # Failure
+    ///
+    /// Fails if the CString is null.
     pub fn iter<'a>(&'a self) -> CChars<'a> {
+        if self.buf.is_null() { fail!("CString is null!"); }
         CChars {
             ptr: self.buf,
             marker: marker::ContravariantLifetime,
@@ -191,8 +199,14 @@ impl Drop for CString {
 }
 
 impl Container for CString {
+    /// Return the number of bytes in the CString (not including the NUL terminator).
+    ///
+    /// # Failure
+    ///
+    /// Fails if the CString is null.
     #[inline]
     fn len(&self) -> uint {
+        if self.buf.is_null() { fail!("CString is null!"); }
         unsafe {
             ptr::position(self.buf, |c| *c == 0)
         }
@@ -562,8 +576,27 @@ mod tests {
         assert_eq!(c_str.as_str(), Some(""));
         let c_str = bytes!("foo", 0xff).to_c_str();
         assert_eq!(c_str.as_str(), None);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_as_str_fail() {
         let c_str = unsafe { CString::new(ptr::null(), false) };
-        assert_eq!(c_str.as_str(), None);
+        c_str.as_str();
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_len_fail() {
+        let c_str = unsafe { CString::new(ptr::null(), false) };
+        c_str.len();
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_iter_fail() {
+        let c_str = unsafe { CString::new(ptr::null(), false) };
+        c_str.iter();
     }
 }