Skip to content

Commit cad4fcd

Browse files
lilyballalexcrichton
authored andcommitted
Test for null buffer in CString.len()/.iter() and fail
Also change .as_str() to fail on null buffer.
1 parent a9f73b5 commit cad4fcd

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

src/libstd/c_str.rs

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,17 +162,25 @@ impl CString {
162162
}
163163

164164
/// Converts the CString into a `&str` without copying.
165-
/// Returns None if the CString is not UTF-8 or is null.
165+
/// Returns None if the CString is not UTF-8.
166+
///
167+
/// # Failure
168+
///
169+
/// Fails if the CString is null.
166170
#[inline]
167171
pub fn as_str<'a>(&'a self) -> Option<&'a str> {
168-
if self.buf.is_null() { return None; }
169172
let buf = self.as_bytes();
170173
let buf = buf.slice_to(buf.len()-1); // chop off the trailing NUL
171174
str::from_utf8(buf)
172175
}
173176

174177
/// Return a CString iterator.
178+
///
179+
/// # Failure
180+
///
181+
/// Fails if the CString is null.
175182
pub fn iter<'a>(&'a self) -> CChars<'a> {
183+
if self.buf.is_null() { fail!("CString is null!"); }
176184
CChars {
177185
ptr: self.buf,
178186
marker: marker::ContravariantLifetime,
@@ -191,8 +199,14 @@ impl Drop for CString {
191199
}
192200

193201
impl Container for CString {
202+
/// Return the number of bytes in the CString (not including the NUL terminator).
203+
///
204+
/// # Failure
205+
///
206+
/// Fails if the CString is null.
194207
#[inline]
195208
fn len(&self) -> uint {
209+
if self.buf.is_null() { fail!("CString is null!"); }
196210
unsafe {
197211
ptr::position(self.buf, |c| *c == 0)
198212
}
@@ -562,8 +576,27 @@ mod tests {
562576
assert_eq!(c_str.as_str(), Some(""));
563577
let c_str = bytes!("foo", 0xff).to_c_str();
564578
assert_eq!(c_str.as_str(), None);
579+
}
580+
581+
#[test]
582+
#[should_fail]
583+
fn test_as_str_fail() {
565584
let c_str = unsafe { CString::new(ptr::null(), false) };
566-
assert_eq!(c_str.as_str(), None);
585+
c_str.as_str();
586+
}
587+
588+
#[test]
589+
#[should_fail]
590+
fn test_len_fail() {
591+
let c_str = unsafe { CString::new(ptr::null(), false) };
592+
c_str.len();
593+
}
594+
595+
#[test]
596+
#[should_fail]
597+
fn test_iter_fail() {
598+
let c_str = unsafe { CString::new(ptr::null(), false) };
599+
c_str.iter();
567600
}
568601
}
569602

0 commit comments

Comments
 (0)