cargo_swift/
lib_type.rs

1use std::{fmt::Display, str::FromStr};
2
3use cargo_metadata::CrateType;
4use clap::ValueEnum;
5use thiserror::Error;
6
7#[derive(ValueEnum, Debug, PartialEq, Eq, Clone, Copy)]
8#[value()]
9pub enum LibType {
10    Static,
11    Dynamic,
12}
13
14impl LibType {
15    /// The identifier used in the crate-type field in Cargo.toml
16    pub fn identifier(&self) -> &str {
17        match self {
18            LibType::Static => "staticlib",
19            LibType::Dynamic => "cdylib",
20        }
21    }
22
23    pub fn file_extension(&self) -> &str {
24        match self {
25            LibType::Static => "a",
26            LibType::Dynamic => "dylib",
27        }
28    }
29}
30
31impl Display for LibType {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self {
34            Self::Static => write!(f, "static"),
35            Self::Dynamic => write!(f, "dynamic"),
36        }
37    }
38}
39
40impl TryFrom<CrateType> for LibType {
41    type Error = ();
42
43    fn try_from(value: CrateType) -> Result<Self, Self::Error> {
44        match value {
45            CrateType::CDyLib | CrateType::DyLib => Ok(LibType::Dynamic),
46            CrateType::StaticLib => Ok(LibType::Static),
47            _ => Err(()),
48        }
49    }
50}
51
52#[derive(Debug, Error)]
53pub struct VariantError {
54    input: String,
55}
56
57impl Display for VariantError {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        f.write_fmt(format_args!(
60            "Unsupported variant for crate-type: {}",
61            &self.input
62        ))
63    }
64}
65
66impl FromStr for LibType {
67    type Err = VariantError;
68
69    fn from_str(s: &str) -> Result<Self, Self::Err> {
70        match s {
71            "staticlib" => Ok(Self::Static),
72            "cdylib" => Ok(Self::Dynamic),
73            _ => Err(VariantError {
74                input: String::from(s),
75            }),
76        }
77    }
78}