1use std::fmt;
8use std::str::FromStr;
9
10#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
13#[error("unknown {kind} code: {value}")]
14pub struct UnknownCode {
15 pub kind: &'static str,
16 pub value: String,
17}
18
19macro_rules! code_enum {
20 (
21 $(#[$attr:meta])*
22 $vis:vis enum $name:ident as $kind:literal {
23 $(
24 $(#[$variant_attr:meta])*
25 $variant:ident => $wire:literal
26 ),+ $(,)?
27 }
28 ) => {
29 $(#[$attr])*
30 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
31 $vis enum $name {
32 $(
33 $(#[$variant_attr])*
34 $variant,
35 )+
36 }
37
38 impl $name {
39 #[must_use]
41 pub const fn as_str(self) -> &'static str {
42 match self {
43 $( Self::$variant => $wire, )+
44 }
45 }
46
47 #[must_use]
49 pub const fn all() -> &'static [Self] {
50 &[ $( Self::$variant, )+ ]
51 }
52 }
53
54 impl fmt::Display for $name {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 f.write_str(self.as_str())
57 }
58 }
59
60 impl FromStr for $name {
61 type Err = UnknownCode;
62 fn from_str(s: &str) -> Result<Self, Self::Err> {
63 Ok(match s {
64 $( $wire => Self::$variant, )+
65 other => return Err(UnknownCode {
66 kind: $kind,
67 value: other.to_string(),
68 }),
69 })
70 }
71 }
72 };
73}
74
75code_enum! {
76 pub enum Role as "role" {
78 Doc => "doc",
79 Btn => "btn",
80 Lnk => "lnk",
81 Tf => "tf",
82 Ta => "ta",
83 Sel => "sel",
84 Chk => "chk",
85 Rad => "rad",
86 Img => "img",
87 Hd => "hd",
88 P => "p",
89 Li => "li",
90 Lst => "lst",
91 Tbl => "tbl",
92 Row => "row",
93 Cell => "cell",
94 Hdr => "hdr",
95 Nav => "nav",
96 Frm => "frm",
97 Dlg => "dlg",
98 Itm => "itm",
99 Sec => "sec",
100 Art => "art",
101 Mn => "mn",
102 El => "el",
103 }
104}
105
106code_enum! {
107 pub enum Op as "op" {
109 Click => "click",
110 Fill => "fill",
111 Scroll => "scroll",
112 Key => "key",
113 Submit => "submit",
114 Hover => "hover",
115 Focus => "focus",
116 }
117}
118
119code_enum! {
120 pub enum ErrorCode as "error" {
122 StaleToken => "STALE_TOKEN",
123 EngineUnsupported => "ENGINE_UNSUPPORTED",
124 PolicyDeny => "POLICY_DENY",
125 Timeout => "TIMEOUT",
126 NotFound => "NOT_FOUND",
127 WrongSession => "WRONG_SESSION",
128 ConfirmRequired => "CONFIRM_REQUIRED",
129 DaemonStartFailed => "DAEMON_START_FAILED",
130 EngineCrash => "ENGINE_CRASH",
131 BadRequest => "BAD_REQUEST",
132 UnknownKind => "UNKNOWN_KIND",
133 EvalError => "EVAL_ERROR",
134 EvalSyntax => "EVAL_SYNTAX",
135 }
136}
137
138code_enum! {
139 pub enum WarningCode as "warning" {
141 Nav => "nav",
142 CaptchaVisible => "captcha_visible",
143 AuthLoaded => "auth_loaded",
144 ViewportChanged => "viewport_changed",
145 IdempotentHit => "idempotent_hit",
146 ConsoleError => "console_error",
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 fn round_trip<C>(samples: &[C])
155 where
156 C: Copy + PartialEq + fmt::Debug + fmt::Display + FromStr<Err = UnknownCode>,
157 {
158 for c in samples {
159 let s = c.to_string();
160 let parsed: C = s.parse().expect("known code");
161 assert_eq!(parsed, *c);
162 }
163 }
164
165 #[test]
166 fn roles_round_trip() {
167 round_trip(Role::all());
168 }
169
170 #[test]
171 fn ops_round_trip() {
172 round_trip(Op::all());
173 }
174
175 #[test]
176 fn error_codes_round_trip() {
177 round_trip(ErrorCode::all());
178 }
179
180 #[test]
181 fn warning_codes_round_trip() {
182 round_trip(WarningCode::all());
183 }
184
185 #[test]
186 fn unknown_role_rejected() {
187 let err = "xx".parse::<Role>().unwrap_err();
188 assert_eq!(err.kind, "role");
189 assert_eq!(err.value, "xx");
190 }
191
192 #[test]
193 fn unknown_error_rejected() {
194 let err = "WHATEVER".parse::<ErrorCode>().unwrap_err();
195 assert_eq!(err.kind, "error");
196 }
197
198 #[test]
199 fn role_display_matches_wire() {
200 assert_eq!(Role::Btn.to_string(), "btn");
201 assert_eq!(Role::Lnk.as_str(), "lnk");
202 }
203
204 #[test]
205 fn role_count() {
206 assert_eq!(Role::all().len(), 25);
207 assert_eq!(Op::all().len(), 7);
208 }
209}