1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use crate::types::Datatype;
use std::fmt::{self, Debug, Display, Formatter};
use std::num::ParseIntError;
use std::str::FromStr;
use thiserror::Error;
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum ValueError {
#[error("Value not yet known.")]
Unknown,
#[error("Expected value of type {expected} but was {actual}.")]
WrongDatatype {
expected: Datatype,
actual: Datatype,
},
#[error("Invalid or unexpected format {format}.")]
WrongFormat {
format: String,
},
#[error("Parsing {value} as datatype {datatype} failed.")]
ParseFailed {
value: String,
datatype: Datatype,
},
}
pub trait Value: ToString + FromStr {
fn datatype() -> Datatype;
fn valid_for(datatype: Option<Datatype>, format: &Option<String>) -> Result<(), ValueError> {
if let Some(actual) = datatype {
let expected = Self::datatype();
if actual != expected {
return Err(ValueError::WrongDatatype { expected, actual });
}
}
if let Some(ref format) = format {
Self::valid_for_format(format)
} else {
Ok(())
}
}
fn valid_for_format(_format: &str) -> Result<(), ValueError> {
Ok(())
}
}
impl Value for i64 {
fn datatype() -> Datatype {
Datatype::Integer
}
}
impl Value for f64 {
fn datatype() -> Datatype {
Datatype::Float
}
}
impl Value for bool {
fn datatype() -> Datatype {
Datatype::Boolean
}
}
impl Value for String {
fn datatype() -> Datatype {
Datatype::String
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ColorFormat {
Rgb,
Hsv,
}
impl ColorFormat {
fn as_str(&self) -> &'static str {
match self {
Self::Rgb => "rgb",
Self::Hsv => "hsv",
}
}
}
impl FromStr for ColorFormat {
type Err = ValueError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"rgb" => Ok(Self::Rgb),
"hsv" => Ok(Self::Hsv),
_ => Err(ValueError::WrongFormat {
format: s.to_owned(),
}),
}
}
}
impl Display for ColorFormat {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(self.as_str())
}
}
pub trait Color: Value {
fn format() -> ColorFormat;
}
impl<T: Color> Value for T {
fn datatype() -> Datatype {
Datatype::Color
}
fn valid_for_format(format: &str) -> Result<(), ValueError> {
if format == Self::format().as_str() {
Ok(())
} else {
Err(ValueError::WrongFormat {
format: format.to_owned(),
})
}
}
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("Failed to parse color.")]
pub struct ParseColorError();
impl From<ParseIntError> for ParseColorError {
fn from(_: ParseIntError) -> Self {
ParseColorError()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ColorRgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl ColorRgb {
pub fn new(r: u8, g: u8, b: u8) -> Self {
ColorRgb { r, g, b }
}
}
impl Display for ColorRgb {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{},{},{}", self.r, self.g, self.b)
}
}
impl FromStr for ColorRgb {
type Err = ParseColorError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<_> = s.split(',').collect();
if let [r, g, b] = parts.as_slice() {
Ok(ColorRgb {
r: r.parse()?,
g: g.parse()?,
b: b.parse()?,
})
} else {
Err(ParseColorError())
}
}
}
impl Color for ColorRgb {
fn format() -> ColorFormat {
ColorFormat::Rgb
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ColorHsv {
pub h: u16,
pub s: u8,
pub v: u8,
}
impl ColorHsv {
pub fn new(h: u16, s: u8, v: u8) -> Self {
assert!(h <= 360);
assert!(s <= 100);
assert!(v <= 100);
ColorHsv { h, s, v }
}
}
impl Display for ColorHsv {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{},{},{}", self.h, self.s, self.v)
}
}
impl FromStr for ColorHsv {
type Err = ParseColorError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<_> = s.split(',').collect();
if let [h, s, v] = parts.as_slice() {
let h = h.parse()?;
let s = s.parse()?;
let v = v.parse()?;
if h <= 360 && s <= 100 && v <= 100 {
return Ok(ColorHsv { h, s, v });
}
}
Err(ParseColorError())
}
}
impl Color for ColorHsv {
fn format() -> ColorFormat {
ColorFormat::Hsv
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct EnumValue(String);
impl EnumValue {
pub fn new(s: &str) -> Self {
assert!(!s.is_empty());
EnumValue(s.to_owned())
}
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("Empty string is not a valid enum value.")]
pub struct ParseEnumError();
impl FromStr for EnumValue {
type Err = ParseEnumError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
Err(ParseEnumError())
} else {
Ok(EnumValue::new(s))
}
}
}
impl ToString for EnumValue {
fn to_string(&self) -> String {
self.0.to_string()
}
}
impl Value for EnumValue {
fn datatype() -> Datatype {
Datatype::Enum
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn color_rgb_to_from_string() {
let color = ColorRgb::new(111, 222, 42);
assert_eq!(color.to_string().parse(), Ok(color));
}
#[test]
fn color_hsv_to_from_string() {
let color = ColorHsv::new(231, 88, 77);
assert_eq!(color.to_string().parse(), Ok(color));
}
#[test]
fn color_rgb_parse_invalid() {
assert_eq!("".parse::<ColorRgb>(), Err(ParseColorError()));
assert_eq!("1,2".parse::<ColorRgb>(), Err(ParseColorError()));
assert_eq!("1,2,3,4".parse::<ColorRgb>(), Err(ParseColorError()));
assert_eq!("1,2,256".parse::<ColorRgb>(), Err(ParseColorError()));
assert_eq!("1,256,3".parse::<ColorRgb>(), Err(ParseColorError()));
assert_eq!("256,2,3".parse::<ColorRgb>(), Err(ParseColorError()));
assert_eq!("1,-2,3".parse::<ColorRgb>(), Err(ParseColorError()));
}
#[test]
fn color_hsv_parse_invalid() {
assert_eq!("".parse::<ColorHsv>(), Err(ParseColorError()));
assert_eq!("1,2".parse::<ColorHsv>(), Err(ParseColorError()));
assert_eq!("1,2,3,4".parse::<ColorHsv>(), Err(ParseColorError()));
assert_eq!("1,2,101".parse::<ColorHsv>(), Err(ParseColorError()));
assert_eq!("1,101,3".parse::<ColorHsv>(), Err(ParseColorError()));
assert_eq!("361,2,3".parse::<ColorHsv>(), Err(ParseColorError()));
assert_eq!("1,-2,3".parse::<ColorHsv>(), Err(ParseColorError()));
}
}