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
use super::RawValue;
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub enum ColumnValue<A> {
Invalid,
Missing,
Some(A),
}
impl<T> ColumnValue<T> {
pub fn or_else(self, op: impl FnOnce() -> ColumnValue<T>) -> ColumnValue<T> {
match self {
ColumnValue::Missing => op(),
ColumnValue::Invalid => op(),
some => some,
}
}
pub fn unwrap_or_else(self, op: impl FnOnce() -> T) -> T {
match self {
ColumnValue::Missing => op(),
ColumnValue::Invalid => op(),
ColumnValue::Some(t) => t,
}
}
pub fn map<U>(self, op: impl FnOnce(T) -> U) -> ColumnValue<U> {
match self {
ColumnValue::Missing => ColumnValue::Missing,
ColumnValue::Invalid => ColumnValue::Invalid,
ColumnValue::Some(t) => ColumnValue::Some(op(t)),
}
}
pub fn is_some(&self) -> bool {
matches!(self, ColumnValue::Some(_))
}
}
pub trait ValueParser<T> {
fn parse_csv(&self) -> ColumnValue<T>;
}
impl ValueParser<bool> for RawValue {
fn parse_csv(&self) -> ColumnValue<bool> {
match self.0.trim().to_lowercase().as_ref() {
"" => ColumnValue::Missing,
"1" | "t" => ColumnValue::Some(true),
"0" | "f" => ColumnValue::Some(false),
otherwise => otherwise
.parse()
.map(ColumnValue::Some)
.unwrap_or(ColumnValue::Invalid),
}
}
}
impl ValueParser<i64> for RawValue {
fn parse_csv(&self) -> ColumnValue<i64> {
match self.0.trim() {
"" => ColumnValue::Missing,
otherwise => otherwise
.parse()
.map(ColumnValue::Some)
.unwrap_or(ColumnValue::Invalid),
}
}
}
impl ValueParser<f64> for RawValue {
fn parse_csv(&self) -> ColumnValue<f64> {
match self.0.trim().to_lowercase().as_ref() {
"" => ColumnValue::Missing,
"nan" => ColumnValue::Some(f64::NAN),
otherwise => otherwise
.parse()
.map(ColumnValue::Some)
.unwrap_or(ColumnValue::Invalid),
}
}
}
impl ValueParser<String> for RawValue {
fn parse_csv(&self) -> ColumnValue<String> {
ColumnValue::Some(self.0.to_string())
}
}