1use quote::{quote, ToTokens};
2use std::str::FromStr;
3
4#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
6pub enum Primitive {
7 Bool,
8 F32,
9 F64,
10 I8,
11 I16,
12 I32,
13 I64,
14 U8,
15 U16,
16 U32,
17 U64,
18}
19
20impl Primitive {
21 pub fn name(&self) -> String {
22 use Primitive::*;
23 let string = match self {
24 Bool => "bool",
25 F32 => "f32",
26 F64 => "f64",
27 I8 => "i8",
28 I16 => "i16",
29 I32 => "i32",
30 I64 => "i64",
31 U8 => "u8",
32 U16 => "u16",
33 U32 => "u32",
34 U64 => "u64",
35 };
36 string.to_owned()
37 }
38
39 pub fn js_array_name(&self) -> Option<String> {
40 use Primitive::*;
41 match self {
42 U8 => Some("Uint8Array"),
43 U16 => Some("Uint16Array"),
44 U32 => Some("Uint32Array"),
45 I8 => Some("Int8Array"),
46 I16 => Some("Int16Array"),
47 I32 => Some("Int32Array"),
48 F32 => Some("Float32Array"),
49 F64 => Some("Float64Array"),
50 _ => None,
51 }
52 .map(|s| s.to_owned())
53 }
54}
55
56impl FromStr for Primitive {
57 type Err = String;
58
59 fn from_str(string: &str) -> Result<Self, Self::Err> {
60 let primitive = match string {
61 "bool" => Primitive::Bool,
62 "f32" => Primitive::F32,
63 "f64" => Primitive::F64,
64 "i8" => Primitive::I8,
65 "i16" => Primitive::I16,
66 "i32" => Primitive::I32,
67 "i64" => Primitive::I64,
68 "u8" => Primitive::U8,
69 "u16" => Primitive::U16,
70 "u32" => Primitive::U32,
71 "u64" => Primitive::U64,
72 string => return Err(format!("Unknown primitive type: \"{string}\"")),
73 };
74 Ok(primitive)
75 }
76}
77
78impl ToTokens for Primitive {
79 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
80 (match self {
81 Primitive::Bool => quote! {bool},
82 Primitive::F32 => quote! {f32},
83 Primitive::F64 => quote! {f64},
84 Primitive::I8 => quote! {i8},
85 Primitive::I16 => quote! {i16},
86 Primitive::I32 => quote! {i32},
87 Primitive::I64 => quote! {i64},
88 Primitive::U8 => quote! {u8},
89 Primitive::U16 => quote! {u16},
90 Primitive::U32 => quote! {u32},
91 Primitive::U64 => quote! {u64},
92 })
93 .to_tokens(tokens)
94 }
95}