From 789853e83d5f0a4ba1346ccc547a921fed53c475 Mon Sep 17 00:00:00 2001 From: Mahmoud Al-Qudsi Date: Thu, 9 Feb 2023 15:03:33 -0600 Subject: [PATCH] Prevent clones on every `get_xxx()` call They're dereferencing `Arc` variables, but need a fallback in case the variable wasn't set. This implies there's a desire to avoid cloning them everywhere. Return a `Cow` instead of `String`. We never use the allocated results and just compare against them, so there's no need to re-allocate each time. --- src/lib.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d26ba67bd..b90ec2cba 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,6 +56,7 @@ #![allow(deprecated)] #![deny(missing_docs)] +use std::borrow::Cow; use std::collections::{hash_map, HashMap}; use std::env; use std::ffi::{OsStr, OsString}; @@ -3040,24 +3041,24 @@ impl Build { prefixes.first().map(|prefix| *prefix)) } - fn get_target(&self) -> Result { - match self.target { - Some(ref t) => Ok((*t).to_string()), - None => Ok(self.getenv_unwrap("TARGET")?), + fn get_target(&self) -> Result, Error> { + match &self.target { + Some(t) => Ok(Cow::Borrowed(&t)), + None => Ok(Cow::Owned(self.getenv_unwrap("TARGET")?)), } } - fn get_host(&self) -> Result { + fn get_host(&self) -> Result, Error> { match &self.host { - Some(h) => Ok((**h).to_string()), - None => Ok(self.getenv_unwrap("HOST")?), + Some(h) => Ok(Cow::Borrowed(&h)), + None => Ok(Cow::Owned(self.getenv_unwrap("HOST")?)), } } - fn get_opt_level(&self) -> Result { + fn get_opt_level(&self) -> Result, Error> { match &self.opt_level { - Some(ol) => Ok((**ol).to_string()), - None => Ok(self.getenv_unwrap("OPT_LEVEL")?), + Some(ol) => Ok(Cow::Borrowed(&ol)), + None => Ok(Cow::Owned(self.getenv_unwrap("OPT_LEVEL")?)), } }