Skip to content

Test for null buffer in CString.len()/.iter() and fail #11942

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 36 additions & 3 deletions src/libstd/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,17 +161,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,
lifetime: unsafe { cast::transmute(self.buf) },
Expand All @@ -190,8 +198,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)
}
Expand Down Expand Up @@ -561,8 +575,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();
}
}

Expand Down