codify/javascript/
type.rs

1// This is free and unencumbered software released into the public domain.
2
3use crate::{
4    prelude::{fmt, format, Cow, Named},
5    rust,
6};
7
8/// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
9#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub enum Type {
12    /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type
13    Boolean,
14
15    /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type
16    Number,
17}
18
19impl core::str::FromStr for Type {
20    type Err = ();
21
22    fn from_str(input: &str) -> Result<Self, Self::Err> {
23        use Type::*;
24        Ok(match input {
25            "boolean" => Boolean,
26            "number" => Number,
27            _ => return Err(()),
28        })
29    }
30}
31
32impl fmt::Display for Type {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        use Type::*;
35        match self {
36            Boolean => write!(f, "boolean"),
37            Number => write!(f, "number"),
38        }
39    }
40}
41
42impl Named for Type {
43    fn name(&self) -> Cow<str> {
44        Cow::Owned(format!("{}", self))
45    }
46}
47
48impl TryFrom<rust::Type> for Type {
49    type Error = ();
50
51    fn try_from(input: rust::Type) -> Result<Self, Self::Error> {
52        use Type::*;
53        Ok(match input {
54            rust::Type::Bool => Boolean,
55            rust::Type::F32 | rust::Type::F64 => Number,
56            _ => return Err(()),
57        })
58    }
59}
60
61impl crate::ToRust for Type {
62    fn to_rust(&self) -> Option<rust::Type> {
63        use Type::*;
64        Some(match self {
65            Boolean => rust::Type::Bool,
66            Number => rust::Type::F64,
67        })
68    }
69}
70
71impl crate::Type for Type {}