-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
value.rs
367 lines (321 loc) · 11.4 KB
/
value.rs
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use std::fmt::Display;
/// A specific [KDL Value](https://github.com/kdl-org/kdl/blob/main/SPEC.md#value).
#[derive(Debug, Clone, PartialOrd)]
pub enum KdlValue {
/// A [KDL Raw String](https://github.com/kdl-org/kdl/blob/main/SPEC.md#raw-string).
RawString(String),
/// A [KDL String](https://github.com/kdl-org/kdl/blob/main/SPEC.md#string).
String(String),
/// A [KDL
/// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in
/// binary form (e.g. `0b010101`).
Base2(i64),
/// A [KDL
/// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in
/// octal form (e.g. `0o12345670`).
Base8(i64),
/// A [KDL
/// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in
/// decimal form (e.g. `1234567890`).
Base10(i64),
/// A [KDL
/// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in
/// decimal form (e.g. `1234567890.123`), interpreted as a Rust f64.
Base10Float(f64),
/// A [KDL
/// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in
/// hexadecimal form (e.g. `1234567890abcdef`).
Base16(i64),
/// A [KDL Boolean](https://github.com/kdl-org/kdl/blob/main/SPEC.md#boolean).
Bool(bool),
/// The [KDL Null Value](https://github.com/kdl-org/kdl/blob/main/SPEC.md#null).
Null,
}
impl Eq for KdlValue {}
impl PartialEq for KdlValue {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::RawString(l0), Self::RawString(r0)) => l0 == r0,
(Self::String(l0), Self::String(r0)) => l0 == r0,
(Self::Base2(l0), Self::Base2(r0)) => l0 == r0,
(Self::Base8(l0), Self::Base8(r0)) => l0 == r0,
(Self::Base10(l0), Self::Base10(r0)) => l0 == r0,
(Self::Base10Float(l0), Self::Base10Float(r0)) => {
let l0 = if l0 == &f64::INFINITY {
f64::MAX
} else if l0 == &f64::NEG_INFINITY {
-f64::MAX
} else if l0.is_nan() {
// We collapse NaN to 0.0 because we're evil like that.
0.0
} else {
*l0
};
let r0 = if r0 == &f64::INFINITY {
f64::MAX
} else if r0 == &f64::NEG_INFINITY {
-f64::MAX
} else if r0.is_nan() {
// We collapse NaN to 0.0 because we're evil like that.
0.0
} else {
*r0
};
l0 == r0
}
(Self::Base16(l0), Self::Base16(r0)) => l0 == r0,
(Self::Bool(l0), Self::Bool(r0)) => l0 == r0,
_ => core::mem::discriminant(self) == core::mem::discriminant(other),
}
}
}
// NOTE: I know, I know. This is terrible and I shouldn't do it, but it's
// better than not being able to hash KdlValue at all.
impl std::hash::Hash for KdlValue {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
KdlValue::RawString(val) => val.hash(state),
KdlValue::String(val) => val.hash(state),
KdlValue::Base2(val) => val.hash(state),
KdlValue::Base8(val) => val.hash(state),
KdlValue::Base10(val) => val.hash(state),
KdlValue::Base10Float(val) => {
let val = if val == &f64::INFINITY {
f64::MAX
} else if val == &f64::NEG_INFINITY {
-f64::MAX
} else if val.is_nan() {
// We collapse NaN to 0.0 because we're evil like that.
0.0
} else {
*val
};
// Good enough to be close-ish for our purposes.
(val.trunc() as i64).hash(state);
(val.fract() as i64).hash(state);
}
KdlValue::Base16(val) => val.hash(state),
KdlValue::Bool(val) => val.hash(state),
KdlValue::Null => core::mem::discriminant(self).hash(state),
}
}
}
impl KdlValue {
/// Returns `true` if the value is a [`KdlValue::RawString`].
pub fn is_raw_string(&self) -> bool {
matches!(self, Self::RawString(..))
}
/// Returns `true` if the value is a [`KdlValue::String`].
pub fn is_string(&self) -> bool {
matches!(self, Self::String(..))
}
/// Returns `true` if the value is a [`KdlValue::String`] or [`KdlValue::RawString`].
pub fn is_string_value(&self) -> bool {
matches!(self, Self::String(..) | Self::RawString(..))
}
/// Returns `true` if the value is a [`KdlValue::Base2`].
pub fn is_base2(&self) -> bool {
matches!(self, Self::Base2(..))
}
/// Returns `true` if the value is a [`KdlValue::Base8`].
pub fn is_base8(&self) -> bool {
matches!(self, Self::Base8(..))
}
/// Returns `true` if the value is a [`KdlValue::Base10`].
pub fn is_base10(&self) -> bool {
matches!(self, Self::Base10(..))
}
/// Returns `true` if the value is a [`KdlValue::Base16`].
pub fn is_base16(&self) -> bool {
matches!(self, Self::Base16(..))
}
/// Returns `true` if the value is a [`KdlValue::Base2`],
/// [`KdlValue::Base8`], [`KdlValue::Base10`], or [`KdlValue::Base16`].
pub fn is_i64_value(&self) -> bool {
matches!(
self,
Self::Base2(..) | Self::Base8(..) | Self::Base10(..) | Self::Base16(..)
)
}
/// Returns `true` if the value is a [`KdlValue::Base10Float`].
pub fn is_base10_float(&self) -> bool {
matches!(self, Self::Base10Float(..))
}
/// Returns `true` if the value is a [`KdlValue::Base10Float`].
pub fn is_float_value(&self) -> bool {
matches!(self, Self::Base10Float(..))
}
/// Returns `true` if the value is a [`KdlValue::Bool`].
pub fn is_bool(&self) -> bool {
matches!(self, Self::Bool(..))
}
/// Returns `true` if the value is a [`KdlValue::Null`].
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
/// Returns `Some(&str)` if the `KdlValue` is a [`KdlValue::RawString`] or a
/// [`KdlValue::String`], otherwise returns `None`.
pub fn as_string(&self) -> Option<&str> {
use KdlValue::*;
match self {
String(s) | RawString(s) => Some(s),
_ => None,
}
}
/// Returns `Some(i64)` if the `KdlValue` is a [`KdlValue::Base2`],
/// [`KdlValue::Base8`], [`KdlValue::Base10`], or [`KdlValue::Base16`],
/// otherwise returns `None`.
pub fn as_i64(&self) -> Option<i64> {
use KdlValue::*;
match self {
Base2(i) | Base8(i) | Base10(i) | Base16(i) => Some(*i),
_ => None,
}
}
/// Returns `Some(f64)` if the `KdlValue` is a [`KdlValue::Base10Float`],
/// otherwise returns `None`.
pub fn as_f64(&self) -> Option<f64> {
if let Self::Base10Float(v) = self {
Some(*v)
} else {
None
}
}
/// Returns `Some(bool)` if the `KdlValue` is a [`KdlValue::Bool`], otherwise returns `None`.
pub fn as_bool(&self) -> Option<bool> {
if let Self::Bool(v) = self {
Some(*v)
} else {
None
}
}
}
impl Display for KdlValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::RawString(_) => self.write_raw_string(f),
Self::String(_) => self.write_string(f),
Self::Base2(value) => write!(f, "0b{:b}", value),
Self::Base8(value) => write!(f, "0o{:o}", value),
Self::Base10(value) => write!(f, "{:?}", value),
Self::Base10Float(value) => write!(
f,
"{:?}",
if value == &f64::INFINITY {
f64::MAX
} else if value == &f64::NEG_INFINITY {
-f64::MAX
} else if value.is_nan() {
0.0
} else {
*value
}
),
Self::Base16(value) => write!(f, "0x{:x}", value),
Self::Bool(value) => write!(f, "{}", value),
Self::Null => write!(f, "null"),
}
}
}
impl KdlValue {
fn write_string(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let string = self.as_string().unwrap();
write!(f, "\"")?;
for char in string.chars() {
match char {
'\\' | '"' => write!(f, "\\{}", char)?,
'\n' => write!(f, "\\n")?,
'\r' => write!(f, "\\r")?,
'\t' => write!(f, "\\t")?,
'\u{08}' => write!(f, "\\b")?,
'\u{0C}' => write!(f, "\\f")?,
_ => write!(f, "{}", char)?,
}
}
write!(f, "\"")?;
Ok(())
}
fn write_raw_string(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let raw = self.as_string().unwrap();
let mut consecutive = 0usize;
let mut maxhash = 0usize;
for char in raw.chars() {
if char == '#' {
consecutive += 1;
} else if char == '"' {
maxhash = maxhash.max(consecutive + 1);
} else {
consecutive = 0;
}
}
write!(f, "r")?;
write!(f, "{}", "#".repeat(maxhash))?;
write!(f, "\"{}\"", raw)?;
write!(f, "{}", "#".repeat(maxhash))?;
Ok(())
}
}
impl From<i64> for KdlValue {
fn from(value: i64) -> Self {
KdlValue::Base10(value)
}
}
impl From<f64> for KdlValue {
fn from(value: f64) -> Self {
KdlValue::Base10Float(value)
}
}
impl From<&str> for KdlValue {
fn from(value: &str) -> Self {
KdlValue::String(value.to_string())
}
}
impl From<String> for KdlValue {
fn from(value: String) -> Self {
KdlValue::String(value)
}
}
impl From<bool> for KdlValue {
fn from(value: bool) -> Self {
KdlValue::Bool(value)
}
}
impl<T> From<Option<T>> for KdlValue
where
T: Into<KdlValue>,
{
fn from(value: Option<T>) -> Self {
match value {
Some(value) => value.into(),
None => KdlValue::Null,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn formatting() {
let raw = KdlValue::RawString(r###"r##"foor#"bar"#baz"##"###.into());
assert_eq!(
format!("{}", raw),
r####"r###"r##"foor#"bar"#baz"##"###"####
);
let string = KdlValue::String("foo\n".into());
assert_eq!(format!("{}", string), r#""foo\n""#);
let base2 = KdlValue::Base2(0b1010_1010);
assert_eq!(format!("{}", base2), "0b10101010");
let base8 = KdlValue::Base8(0o12345670);
assert_eq!(format!("{}", base8), "0o12345670");
let base10 = KdlValue::Base10(1234567890);
assert_eq!(format!("{}", base10), "1234567890");
let base10float = KdlValue::Base10Float(1234567890.12345);
assert_eq!(format!("{}", base10float), "1234567890.12345");
let base16 = KdlValue::Base16(0x1234567890ABCDEF);
assert_eq!(format!("{}", base16), "0x1234567890abcdef");
let boolean = KdlValue::Bool(true);
assert_eq!(format!("{}", boolean), "true");
let null = KdlValue::Null;
assert_eq!(format!("{}", null), "null");
}
}