From a56315c2734ca7961e1c659bddb72aef82324265 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Fri, 15 Sep 2023 16:19:43 +0800 Subject: [PATCH] refactor: use `Cow` to avoid unnecessary allocations --- src/cargo/core/source_id.rs | 9 +++++---- src/cargo/ops/mod.rs | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cargo/core/source_id.rs b/src/cargo/core/source_id.rs index 42840b5efaa2..5bcff5ab98f5 100644 --- a/src/cargo/core/source_id.rs +++ b/src/cargo/core/source_id.rs @@ -7,6 +7,7 @@ use crate::util::{config, CanonicalUrl, CargoResult, Config, IntoUrl, ToSemver}; use anyhow::Context; use serde::de; use serde::ser; +use std::borrow::Cow; use std::cmp::{self, Ordering}; use std::collections::HashSet; use std::fmt::{self, Formatter}; @@ -308,17 +309,17 @@ impl SourceId { } /// Displays the name of a registry if it has one. Otherwise just the URL. - pub fn display_registry_name(self) -> String { + pub fn display_registry_name<'a>(self) -> Cow<'a, str> { if self.is_crates_io() { - CRATES_IO_REGISTRY.to_string() + CRATES_IO_REGISTRY.into() } else if let Some(key) = &self.inner.registry_key { - key.clone() + key.into() } else if self.precise().is_some() { // We remove `precise` here to retrieve an permissive version of // `SourceIdInner`, which may contain the registry name. self.with_precise(None).display_registry_name() } else { - url_display(self.url()) + url_display(self.url()).into() } } diff --git a/src/cargo/ops/mod.rs b/src/cargo/ops/mod.rs index d4ec442dd918..0bea9bba0069 100644 --- a/src/cargo/ops/mod.rs +++ b/src/cargo/ops/mod.rs @@ -75,7 +75,7 @@ fn check_dep_has_version(dep: &crate::core::Dependency, publish: bool) -> crate: if !dep.specified_req() && dep.is_transitive() { let dep_version_source = dep.registry_id().map_or_else( - || CRATES_IO_DOMAIN.to_string(), + || CRATES_IO_DOMAIN.into(), |registry_id| registry_id.display_registry_name(), ); anyhow::bail!(