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
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use std::borrow::Cow;
use crate::parse::token::{
Comment as ParsedComment, Field as ParsedField, InlineComment as ParsedInlineComment,
Value as ParsedValue,
};
#[derive(Clone, PartialEq, Debug)]
pub enum Token<'a> {
Field(Field<'a>),
Comment {
is_inline: bool,
inner: Cow<'a, str>,
},
}
impl<'input> From<&ParsedField<'input>> for Token<'input> {
fn from(field: &ParsedField<'input>) -> Self {
Self::Field(field.into())
}
}
impl<'a, 'input: 'a> From<&'a ParsedInlineComment<'input>> for Token<'input> {
fn from(comment: &'a ParsedInlineComment<'input>) -> Self {
Self::Comment {
is_inline: true,
inner: Cow::Borrowed(
comment
.inner
.strip_prefix("(")
.unwrap()
.strip_suffix(")")
.unwrap(),
),
}
}
}
impl<'input> From<&ParsedComment<'input>> for Token<'input> {
fn from(comment: &ParsedComment<'input>) -> Self {
Self::Comment {
is_inline: false,
inner: Cow::Borrowed(comment.inner.strip_prefix(";").unwrap()),
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Field<'a> {
pub letters: Cow<'a, str>,
pub value: Value<'a>,
}
impl<'input> From<&ParsedField<'input>> for Field<'input> {
fn from(field: &ParsedField<'input>) -> Self {
Self {
letters: field.letters.into(),
value: Value::from(&field.value),
}
}
}
impl<'a> From<Field<'a>> for Token<'a> {
fn from(field: Field<'a>) -> Token<'a> {
Self::Field(field)
}
}
impl<'a> Field<'a> {
pub fn into_owned(self) -> Field<'static> {
Field {
letters: self.letters.into_owned().into(),
value: self.value.into_owned(),
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub enum Value<'a> {
Rational(Decimal),
Float(f64),
Integer(usize),
String(Cow<'a, str>),
}
impl Value<'_> {
pub fn as_f64(&self) -> Option<f64> {
match self {
Self::Rational(r) => r.to_f64(),
Self::Integer(i) => Some(*i as f64),
Self::Float(f) => Some(*f),
Self::String(_) => None,
}
}
pub fn into_owned(self) -> Value<'static> {
match self {
Self::String(s) => Value::String(s.into_owned().into()),
Self::Rational(r) => Value::Rational(r),
Self::Integer(i) => Value::Integer(i),
Self::Float(f) => Value::Float(f),
}
}
}
impl<'input> From<&ParsedValue<'input>> for Value<'input> {
fn from(val: &ParsedValue<'input>) -> Self {
use ParsedValue::*;
match val {
Rational(r) => Self::Rational(*r),
Integer(i) => Self::Integer(*i),
String(s) => {
Self::String(Cow::Borrowed(
s.strip_prefix('"').unwrap().strip_suffix('"').unwrap(),
))
}
}
}
}