From 7232f32428b95a73ec66d586845f0b4a89a224e7 Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Mon, 6 Jun 2022 22:52:11 +1000 Subject: [PATCH] Use `ArrayVec` to avoid heap alloc in `detect_targets` Signed-off-by: Jiahao XU --- src/target.rs | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/target.rs b/src/target.rs index 79eb32ab..da0f3794 100644 --- a/src/target.rs +++ b/src/target.rs @@ -1,3 +1,5 @@ +use arrayvec::ArrayVec; + /// Compiled target triple, used as default for binary fetching pub const TARGET: &str = env!("TARGET"); @@ -14,7 +16,7 @@ pub const TARGET: &str = env!("TARGET"); /// /// Check [this issue](https://github.com/ryankurte/cargo-binstall/issues/155) /// for more information. -pub async fn detect_targets() -> Vec> { +pub async fn detect_targets() -> ArrayVec, 2> { #[cfg(target_os = "linux")] { linux::detect_targets_linux().await @@ -29,13 +31,23 @@ pub async fn detect_targets() -> Vec> { } } +fn from_array(arr: [T; LEN]) -> ArrayVec { + let mut v = ArrayVec::new(); + + for elem in arr { + v.push(elem); + } + + v +} + #[cfg(target_os = "linux")] mod linux { - use super::TARGET; + use super::{from_array, ArrayVec, TARGET}; use std::process::Output; use tokio::process::Command; - pub(super) async fn detect_targets_linux() -> Vec> { + pub(super) async fn detect_targets_linux() -> ArrayVec, 2> { let abi = parse_abi(); if let Ok(Output { @@ -49,19 +61,19 @@ mod linux { } else if let Some(libc_version) = parse_libc_version(stderr) { libc_version } else { - return vec![create_target_str("musl", abi)]; + return from_array([create_target_str("musl", abi)]); }; if libc_version == "gnu" { - return vec![ + return from_array([ create_target_str("gnu", abi), create_target_str("musl", abi), - ]; + ]); } } // Fallback to using musl - vec![create_target_str("musl", abi)] + from_array([create_target_str("musl", abi)]) } fn parse_libc_version(output: &[u8]) -> Option<&'static str> { @@ -104,16 +116,17 @@ mod linux { #[cfg(target_os = "macos")] mod macos { + use super::{from_array, ArrayVec}; use guess_host_triple::guess_host_triple; const AARCH64: &str = "aarch64-apple-darwin"; const X86: &str = "x86_64-apple-darwin"; - pub(super) fn detect_targets_macos() -> Vec> { + pub(super) fn detect_targets_macos() -> ArrayVec, 2> { if guess_host_triple() == Some(AARCH64) { - vec![AARCH64.into(), X86.into()] + from_array([AARCH64.into(), X86.into()]) } else { - vec![X86.into()] + from_array([X86.into()]) } } }