Skip to content

Commit

Permalink
Reuse storage when converting Vec to String in Communicator::read_str…
Browse files Browse the repository at this point in the history
…ing()
  • Loading branch information
hniksic committed Oct 11, 2021
1 parent 6cacc8c commit ce298fe
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/communicate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,10 +508,7 @@ impl Communicator {
/// replacement character.
pub fn read_string(&mut self) -> Result<(Option<String>, Option<String>), CommunicateError> {
let (o, e) = self.read()?;
Ok((
o.map(|v| String::from_utf8_lossy(&v).into()),
e.map(|v| String::from_utf8_lossy(&v).into()),
))
Ok((o.map(from_utf8_lossy), e.map(from_utf8_lossy)))
}

/// Limit the amount of data the next `read()` will read from the
Expand All @@ -529,6 +526,15 @@ impl Communicator {
}
}

/// Like String::from_utf8_lossy(), but takes `Vec<u8>` and reuses its storage if
/// possible.
fn from_utf8_lossy(v: Vec<u8>) -> String {
match String::from_utf8(v) {
Ok(s) => s,
Err(e) => String::from_utf8_lossy(e.as_bytes()).into(),
}
}

pub fn communicate(
stdin: Option<File>,
stdout: Option<File>,
Expand Down

0 comments on commit ce298fe

Please sign in to comment.