Skip to content

Impl fmt::Write for AsciiString, and add tests #33

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

Merged
merged 3 commits into from
Feb 9, 2017
Merged
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
33 changes: 32 additions & 1 deletion src/ascii_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,20 @@ impl fmt::Debug for AsciiString {
}
}

impl fmt::Write for AsciiString {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add some documentation that fmt::Write methods "[do] not support transmission of an error other than that an error occurred." (from std::fmt::Error). This is just to remind users of this API how to handle errors correctly.

fn write_str(&mut self, s: &str) -> fmt::Result {
let astr = try!(AsciiStr::from_ascii(s).map_err(|_| fmt::Error));
self.push_str(astr);
Ok(())
}

fn write_char(&mut self, c: char) -> fmt::Result {
let achar = try!(AsciiChar::from(c).map_err(|_| fmt::Error));
self.push(achar);
Ok(())
}
}

impl FromIterator<AsciiChar> for AsciiString {
fn from_iter<I: IntoIterator<Item=AsciiChar>>(iter: I) -> AsciiString {
let mut buf = AsciiString::new();
Expand Down Expand Up @@ -644,7 +658,6 @@ impl IntoAsciiString for String {
}
}


#[cfg(test)]
mod tests {
use std::str::FromStr;
Expand Down Expand Up @@ -675,4 +688,22 @@ mod tests {
assert_eq!(format!("{}", s), "abc".to_string());
assert_eq!(format!("{:?}", s), "\"abc\"".to_string());
}

#[test]
fn write_fmt() {
use std::{fmt, str};

let mut s0 = AsciiString::new();
fmt::write(&mut s0, format_args!("Hello World")).unwrap();
assert_eq!(s0, "Hello World");

let mut s1 = AsciiString::new();
fmt::write(&mut s1, format_args!("{}", 9)).unwrap();
assert_eq!(s1, "9");

let mut s2 = AsciiString::new();
let sparkle_heart_bytes = [240, 159, 146, 150];
let sparkle_heart = str::from_utf8(&sparkle_heart_bytes).unwrap();
assert!(fmt::write(&mut s2, format_args!("{}", sparkle_heart)).is_err());
}
}