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 Ifr => "ifr",
109 El => "el",
110 }
111}
112
113code_enum! {
114 pub enum Op as "op" {
116 Click => "click",
117 Fill => "fill",
118 Scroll => "scroll",
119 Key => "key",
120 Submit => "submit",
121 Hover => "hover",
122 Focus => "focus",
123 }
124}
125
126code_enum! {
127 pub enum ErrorCode as "error" {
129 StaleToken => "STALE_TOKEN",
130 EngineUnsupported => "ENGINE_UNSUPPORTED",
131 PolicyDeny => "POLICY_DENY",
132 Timeout => "TIMEOUT",
133 NotFound => "NOT_FOUND",
134 WrongSession => "WRONG_SESSION",
135 ConfirmRequired => "CONFIRM_REQUIRED",
136 DaemonStartFailed => "DAEMON_START_FAILED",
137 EngineCrash => "ENGINE_CRASH",
138 BadRequest => "BAD_REQUEST",
139 UnknownKind => "UNKNOWN_KIND",
140 EvalError => "EVAL_ERROR",
141 EvalSyntax => "EVAL_SYNTAX",
142 }
143}
144
145code_enum! {
146 pub enum WarningCode as "warning" {
148 Nav => "nav",
149 CaptchaVisible => "captcha_visible",
150 AuthLoaded => "auth_loaded",
151 ViewportChanged => "viewport_changed",
152 IdempotentHit => "idempotent_hit",
153 ConsoleError => "console_error",
154 HiddenTarget => "hidden_target",
155 }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 fn round_trip<C>(samples: &[C])
163 where
164 C: Copy + PartialEq + fmt::Debug + fmt::Display + FromStr<Err = UnknownCode>,
165 {
166 for c in samples {
167 let s = c.to_string();
168 let parsed: C = s.parse().expect("known code");
169 assert_eq!(parsed, *c);
170 }
171 }
172
173 #[test]
174 fn roles_round_trip() {
175 round_trip(Role::all());
176 }
177
178 #[test]
179 fn ops_round_trip() {
180 round_trip(Op::all());
181 }
182
183 #[test]
184 fn error_codes_round_trip() {
185 round_trip(ErrorCode::all());
186 }
187
188 #[test]
189 fn warning_codes_round_trip() {
190 round_trip(WarningCode::all());
191 }
192
193 #[test]
194 fn unknown_role_rejected() {
195 let err = "xx".parse::<Role>().unwrap_err();
196 assert_eq!(err.kind, "role");
197 assert_eq!(err.value, "xx");
198 }
199
200 #[test]
201 fn unknown_error_rejected() {
202 let err = "WHATEVER".parse::<ErrorCode>().unwrap_err();
203 assert_eq!(err.kind, "error");
204 }
205
206 #[test]
207 fn role_display_matches_wire() {
208 assert_eq!(Role::Btn.to_string(), "btn");
209 assert_eq!(Role::Lnk.as_str(), "lnk");
210 }
211
212 #[test]
216 fn role_count() {
217 assert_eq!(Role::all().len(), 26);
218 assert_eq!(Op::all().len(), 7);
219 }
220
221 #[test]
222 fn iframe_role_round_trips() {
223 assert_eq!(Role::Ifr.as_str(), "ifr");
224 assert_eq!("ifr".parse::<Role>().unwrap(), Role::Ifr);
225 }
226}