diff --git a/src/communicate.rs b/src/communicate.rs index a27b411..b78d4cb 100644 --- a/src/communicate.rs +++ b/src/communicate.rs @@ -508,10 +508,7 @@ impl Communicator { /// replacement character. pub fn read_string(&mut self) -> Result<(Option, Option), 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 @@ -529,6 +526,15 @@ impl Communicator { } } +/// Like String::from_utf8_lossy(), but takes `Vec` and reuses its storage if +/// possible. +fn from_utf8_lossy(v: Vec) -> String { + match String::from_utf8(v) { + Ok(s) => s, + Err(e) => String::from_utf8_lossy(e.as_bytes()).into(), + } +} + pub fn communicate( stdin: Option, stdout: Option,