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
use std::ops::Add;
const LF: char = '\n';
const HASH: char = '#';
const B_SLASH: char = '\\';
const S_QUOTE: char = '\'';
const D_QUOTE: char = '"';
#[derive(Debug, PartialEq)]
pub enum Quote {
Single,
Double,
No,
}
#[derive(Debug, PartialEq)]
pub struct KeyVal {
pub k: String,
pub v: String,
pub q: Quote,
}
#[derive(Debug, PartialEq)]
pub enum Line {
KeyVal(KeyVal),
Empty,
}
impl Line {
fn replace_lf(line: &str) -> String {
let mut s = String::with_capacity(line.len());
let mut chars = line.chars();
loop {
match chars.next() {
Some(x) if x == B_SLASH => match chars.next() {
Some('n') => {
s.push(LF);
}
Some(B_SLASH) => {
s.push(B_SLASH);
}
Some(n) => {
s.push(x);
s.push(n);
}
None => s.push(x),
},
Some(x) => s.push(x),
_ => break,
}
}
s
}
fn escape_lf(x: char) -> String {
if x == LF {
x.escape_debug().to_string()
} else {
x.to_string()
}
}
fn retain_quote(orgnl: String, after: String, q: Quote) -> (String, Quote) {
if orgnl.len().eq(&after.len().add(1)) {
let new_val: String = orgnl.chars().take_while(|c| c != &HASH).collect();
(new_val.trim().to_string(), Quote::No)
} else {
(after, q)
}
}
}
impl From<&str> for Line {
fn from(line: &str) -> Self {
if line.is_empty() || line.starts_with(HASH) {
return Self::Empty;
};
let mut parts = line.splitn(2, '=');
match (parts.next(), parts.next()) {
(Some(k), Some(v)) => {
let key = k.trim().to_string();
let mut chars = v.chars();
let first = chars.next();
match first {
Some(D_QUOTE) => {
let val = {
let v: String = chars.take_while(|x| x != &D_QUOTE).collect();
Self::replace_lf(&v)
};
let (v, q) = Self::retain_quote(v.to_string(), val, Quote::Double);
Line::KeyVal(KeyVal { k: key, v, q })
}
Some(S_QUOTE) => {
let val: String = chars
.take_while(|x| x != &S_QUOTE)
.map(Self::escape_lf)
.collect();
let (v, q) = Self::retain_quote(v.to_string(), val, Quote::Single);
Line::KeyVal(KeyVal { k: key, v, q })
}
Some(a) => {
let mut val = Self::escape_lf(a);
val.push_str(
&chars
.take_while(|x| x != &HASH)
.map(Self::escape_lf)
.collect::<String>(),
);
Line::KeyVal(KeyVal {
k: key,
v: val.trim().to_string(),
q: Quote::No,
})
}
_ => Line::KeyVal(KeyVal {
k: key,
v: String::with_capacity(0),
q: Quote::No,
}),
}
}
_ => Self::Empty,
}
}
}