serenade_form/
transformer.rs1use crate::FormError;
4use crate::kind::ChoiceOptions;
5
6pub trait DataTransformer: Send + Sync {
19 fn transform(&self, model: &str) -> Result<String, FormError>;
25
26 fn reverse_transform(&self, view: &str) -> Result<String, FormError>;
32}
33
34#[derive(Debug, Clone, Copy, Default)]
36pub struct BoolToStringTransformer;
37
38impl DataTransformer for BoolToStringTransformer {
39 fn transform(&self, model: &str) -> Result<String, FormError> {
40 Ok(if is_truthy(model) {
41 String::from("1")
42 } else {
43 String::new()
44 })
45 }
46
47 fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
48 Ok(if is_truthy(view) {
49 String::from("1")
50 } else {
51 String::from("0")
52 })
53 }
54}
55
56#[derive(Debug, Clone, Copy, Default)]
58pub struct I64ToStringTransformer;
59
60impl DataTransformer for I64ToStringTransformer {
61 fn transform(&self, model: &str) -> Result<String, FormError> {
62 if model.is_empty() {
63 return Ok(String::new());
64 }
65 model
66 .parse::<i64>()
67 .map(|n| n.to_string())
68 .map_err(|_| FormError::Transform(String::from("invalid i64 model value")))
69 }
70
71 fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
72 if view.is_empty() {
73 return Ok(String::new());
74 }
75 view.parse::<i64>()
76 .map(|n| n.to_string())
77 .map_err(|_| FormError::Transform(String::from("invalid i64 view value")))
78 }
79}
80
81#[derive(Debug, Clone)]
83pub struct ChoiceToValueTransformer {
84 options: ChoiceOptions,
85}
86
87impl ChoiceToValueTransformer {
88 #[must_use]
90 pub const fn new(options: ChoiceOptions) -> Self {
91 Self { options }
92 }
93}
94
95impl DataTransformer for ChoiceToValueTransformer {
96 fn transform(&self, model: &str) -> Result<String, FormError> {
97 if model.is_empty() {
98 return Ok(String::new());
99 }
100 if self.options.multiple {
101 let mut out = Vec::new();
102 for part in split_multi(model) {
103 if !self.is_allowed(part) {
104 return Err(FormError::Transform(format!(
105 "choice value {part:?} is not allowed"
106 )));
107 }
108 out.push(part.to_owned());
109 }
110 return Ok(join_multi(&out));
111 }
112 if self.is_allowed(model) {
113 Ok(model.to_owned())
114 } else {
115 Err(FormError::Transform(format!(
116 "choice value {model:?} is not allowed"
117 )))
118 }
119 }
120
121 fn reverse_transform(&self, view: &str) -> Result<String, FormError> {
122 self.transform(view)
123 }
124}
125
126impl ChoiceToValueTransformer {
127 fn is_allowed(&self, value: &str) -> bool {
128 self.options.choices.iter().any(|c| c.value == value)
129 }
130}
131
132fn is_truthy(value: &str) -> bool {
133 matches!(
134 value.trim().to_ascii_lowercase().as_str(),
135 "1" | "true" | "on" | "yes"
136 )
137}
138
139#[must_use]
141pub fn split_multi(value: &str) -> Vec<&str> {
142 value.split_whitespace().filter(|s| !s.is_empty()).collect()
143}
144
145#[must_use]
147pub fn join_multi(values: &[String]) -> String {
148 values.join(" ")
149}