Skip to content

Commit

Permalink
Merge pull request #196 from dtolnay/ensure
Browse files Browse the repository at this point in the history
Exclude messages containing whitespace
  • Loading branch information
dtolnay committed Nov 22, 2021
2 parents 4ff48fe + c866f2b commit b75dcd2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
28 changes: 16 additions & 12 deletions src/ensure.rs
Expand Up @@ -47,20 +47,24 @@ impl Buf {

impl Write for Buf {
fn write_str(&mut self, s: &str) -> fmt::Result {
if s.bytes().any(|b| b == b' ' || b == b'\n') {
return Err(fmt::Error);
}

let remaining = self.bytes.len() - self.written;
if s.len() <= remaining {
unsafe {
ptr::copy_nonoverlapping(
s.as_ptr(),
self.bytes.as_mut_ptr().add(self.written).cast::<u8>(),
s.len(),
);
}
self.written += s.len();
Ok(())
} else {
Err(fmt::Error)
if s.len() > remaining {
return Err(fmt::Error);
}

unsafe {
ptr::copy_nonoverlapping(
s.as_ptr(),
self.bytes.as_mut_ptr().add(self.written).cast::<u8>(),
s.len(),
);
}
self.written += s.len();
Ok(())
}
}

Expand Down
13 changes: 13 additions & 0 deletions tests/test_ensure.rs
Expand Up @@ -366,6 +366,19 @@ fn test_trailer() {
);
}

#[test]
fn test_whitespace() {
#[derive(Debug)]
pub struct Point {
pub x: i32,
pub y: i32,
}

let point = Point { x: 0, y: 0 };
let test = || Ok(ensure!("" == format!("{:#?}", point)));
assert_err(test, "Condition failed: `\"\" == format!(\"{:#?}\", point)`");
}

#[test]
fn test_too_long() {
let test = || Ok(ensure!("" == "x".repeat(10)));
Expand Down

0 comments on commit b75dcd2

Please sign in to comment.