From 2983f519a2f1e57867c45686bc80887b975817a5 Mon Sep 17 00:00:00 2001 From: Rain Date: Tue, 3 Dec 2024 00:39:43 +0000 Subject: [PATCH] add FromStr and Display impls for TargetKind and CrateType I'd like to use the string representations in a few places (particularly to avoid exposing cargo-metadata types as a public dependency). Add `FromStr` and `Display` impls. --- src/lib.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 588fa607..1787770b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -88,7 +88,7 @@ use std::fmt; use std::hash::Hash; use std::path::PathBuf; use std::process::{Command, Stdio}; -use std::str::from_utf8; +use std::str::{from_utf8, FromStr}; pub use camino; pub use semver; @@ -699,6 +699,33 @@ impl From<&str> for TargetKind { } } +impl FromStr for TargetKind { + type Err = std::convert::Infallible; + + fn from_str(s: &str) -> std::result::Result { + Ok(TargetKind::from(s)) + } +} + +impl fmt::Display for TargetKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Bench => "bench".fmt(f), + Self::Bin => "bin".fmt(f), + Self::CustomBuild => "custom-build".fmt(f), + Self::CDyLib => "cdylib".fmt(f), + Self::DyLib => "dylib".fmt(f), + Self::Example => "example".fmt(f), + Self::Lib => "lib".fmt(f), + Self::ProcMacro => "proc-macro".fmt(f), + Self::RLib => "rlib".fmt(f), + Self::StaticLib => "staticlib".fmt(f), + Self::Test => "test".fmt(f), + Self::Unknown(x) => x.fmt(f), + } + } +} + /// Similar to `kind`, but only reports the /// [Cargo crate types](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-crate-type-field): /// `bin`, `lib`, `rlib`, `dylib`, `cdylib`, `staticlib`, `proc-macro`. @@ -749,6 +776,29 @@ impl From<&str> for CrateType { } } +impl FromStr for CrateType { + type Err = std::convert::Infallible; + + fn from_str(s: &str) -> std::result::Result { + Ok(CrateType::from(s)) + } +} + +impl fmt::Display for CrateType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Bin => "bin".fmt(f), + Self::CDyLib => "cdylib".fmt(f), + Self::DyLib => "dylib".fmt(f), + Self::Lib => "lib".fmt(f), + Self::ProcMacro => "proc-macro".fmt(f), + Self::RLib => "rlib".fmt(f), + Self::StaticLib => "staticlib".fmt(f), + Self::Unknown(x) => x.fmt(f), + } + } +} + /// The Rust edition /// /// As of writing this comment rust editions 2024, 2027 and 2030 are not actually a thing yet but are parsed nonetheless for future proofing.