]> git.lizzy.rs Git - rust.git/commitdiff
Test for null buffer in CString.len()/.iter() and fail
authorKevin Ballard <kevin@sb.org>
Thu, 30 Jan 2014 23:29:36 +0000 (15:29 -0800)
committerAlex Crichton <alex@alexcrichton.com>
Sat, 1 Feb 2014 05:43:09 +0000 (21:43 -0800)
Also change .as_str() to fail on null buffer.

src/libstd/c_str.rs

index ded80d07003206c2945c8e3505128317d5bdacc4..b7374b6f15d08ecb61ef81e8cda41fa49987adec 100644 (file)
@@ -162,17 +162,25 @@ pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
     }
 
     /// 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 @@ fn drop(&mut self) {
 }
 
 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 @@ fn test_as_str() {
         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();
     }
 }