From 1c81432ff556d1fbbb127524a8136dc2a2fac9a3 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Thu, 20 Jul 2023 14:34:22 +1000 Subject: [PATCH] Optimize `Error::new`: Avoid unnecessary heap alloc (#823) --- src/lib.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e8046eab..b175e23a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -157,21 +157,21 @@ pub struct Error { /// Describes the kind of error that occurred. kind: ErrorKind, /// More explanation of error that occurred. - message: String, + message: Cow<'static, str>, } impl Error { - fn new(kind: ErrorKind, message: &str) -> Error { + fn new(kind: ErrorKind, message: impl Into>) -> Error { Error { - kind: kind, - message: message.to_owned(), + kind, + message: message.into(), } } } impl From for Error { fn from(e: io::Error) -> Error { - Error::new(ErrorKind::IOError, &format!("{}", e)) + Error::new(ErrorKind::IOError, format!("{}", e)) } } @@ -2242,7 +2242,7 @@ impl Build { let arch = target.split('-').nth(0).ok_or_else(|| { Error::new( ErrorKind::ArchitectureInvalid, - format!("Unknown architecture for {} target.", os).as_str(), + format!("Unknown architecture for {} target.", os), ) })?; @@ -2292,7 +2292,7 @@ impl Build { _ => { return Err(Error::new( ErrorKind::ArchitectureInvalid, - format!("Unknown architecture for {} target.", os).as_str(), + format!("Unknown architecture for {} target.", os), )); } } @@ -3147,7 +3147,7 @@ impl Build { Some(s) => Ok(s), None => Err(Error::new( ErrorKind::EnvVarNotFound, - &format!("Environment variable {} not defined.", v.to_string()), + format!("Environment variable {} not defined.", v), )), } } @@ -3167,7 +3167,7 @@ impl Build { Some(res) => Ok(res), None => Err(Error::new( ErrorKind::EnvVarNotFound, - &format!("Could not find environment variable {}.", var_base), + format!("Could not find environment variable {}.", var_base), )), } } @@ -3480,7 +3480,7 @@ fn wait_on_child(cmd: &Command, program: &str, child: &mut Child) -> Result<(), Err(e) => { return Err(Error::new( ErrorKind::ToolExecError, - &format!( + format!( "Failed to wait on spawned child process, command {:?} with args {:?}: {}.", cmd, program, e ), @@ -3494,7 +3494,7 @@ fn wait_on_child(cmd: &Command, program: &str, child: &mut Child) -> Result<(), } else { Err(Error::new( ErrorKind::ToolExecError, - &format!( + format!( "Command {:?} with args {:?} did not execute successfully (status code {}).", cmd, program, status ), @@ -3559,12 +3559,12 @@ fn spawn(cmd: &mut Command, program: &str, pipe_writer: File) -> Result Err(Error::new( ErrorKind::ToolExecError, - &format!( + format!( "Command {:?} with args {:?} failed to start: {:?}", cmd.0, program, e ),