forked from embedded-graphics/bdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproperties.rs
More file actions
341 lines (304 loc) · 8.24 KB
/
Copy pathproperties.rs
File metadata and controls
341 lines (304 loc) · 8.24 KB
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
use std::{collections::HashMap, convert::TryFrom};
use thiserror::Error;
use crate::parser::{Lines, ParserError};
/// BDF file property.
///
/// Source: <https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/XLFD/xlfd.html>
#[derive(Debug, PartialEq, Copy, Clone, Eq, PartialOrd, Ord, strum::Display)]
#[strum(serialize_all = "shouty_snake_case")]
pub enum Property {
/// ADD_STYLE_NAME
AddStyleName,
/// AVERAGE_WIDTH
AverageWidth,
/// AVG_CAPITAL_WIDTH
AvgCapitalWidth,
/// AVG_LOWERCASE_WIDTH
AvgLowercaseWidth,
/// AXIS_LIMITS
AxisLimits,
/// AXIS_NAMES
AxisNames,
/// AXIS_TYPES
AxisTypes,
/// CAP_HEIGHT
CapHeight,
/// CHARSET_ENCODING
CharsetEncoding,
/// CHARSET_REGISTRY
CharsetRegistry,
/// COPYRIGHT
Copyright,
/// DEFAULT_CHAR
DefaultChar,
/// DESTINATION
Destination,
/// END_SPACE
EndSpace,
/// FACE_NAME
FaceName,
/// FAMILY_NAME
FamilyName,
/// FIGURE_WIDTH
FigureWidth,
/// FONT
Font,
/// FONT_ASCENT
FontAscent,
/// FONT_DESCENT
FontDescent,
/// FONT_TYPE
FontType,
/// FONT_VERSION
FontVersion,
/// FOUNDRY
Foundry,
/// FULL_NAME
FullName,
/// ITALIC_ANGLE
ItalicAngle,
/// MAX_SPACE
MaxSpace,
/// MIN_SPACE
MinSpace,
/// NORM_SPACE
NormSpace,
/// NOTICE
Notice,
/// PIXEL_SIZE
PixelSize,
/// POINT_SIZE
PointSize,
/// QUAD_WIDTH
QuadWidth,
/// RASTERIZER_NAME
RasterizerName,
/// RASTERIZER_VERSION
RasterizerVersion,
/// RAW_ASCENT
RawAscent,
/// RAW_DESCENT
RawDescent,
/// RELATIVE_SETWIDTH
RelativeSetwidth,
/// RELATIVE_WEIGHT
RelativeWeight,
/// RESOLUTION
Resolution,
/// RESOLUTION_X
ResolutionX,
/// RESOLUTION_Y
ResolutionY,
/// SETWIDTH_NAME
SetwidthName,
/// SLANT
Slant,
/// SMALL_CAP_SIZE
SmallCapSize,
/// SPACING
Spacing,
/// STRIKEOUT_ASCENT
StrikeoutAscent,
/// STRIKEOUT_DESCENT
StrikeoutDescent,
/// SUBSCRIPT_SIZE
SubscriptSize,
/// SUBSCRIPT_X
SubscriptX,
/// SUBSCRIPT_Y
SubscriptY,
/// SUPERSCRIPT_SIZE
SuperscriptSize,
/// SUPERSCRIPT_X
SuperscriptX,
/// SUPERSCRIPT_Y
SuperscriptY,
/// UNDERLINE_POSITION
UnderlinePosition,
/// UNDERLINE_THICKNESS
UnderlineThickness,
/// WEIGHT
Weight,
/// WEIGHT_NAME
WeightName,
/// X_HEIGHT
XHeight,
}
/// BDF file properties.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Properties {
properties: HashMap<String, PropertyValue>,
}
impl Properties {
#[cfg(test)]
pub(crate) fn new(properties: HashMap<String, PropertyValue>) -> Self {
Self { properties }
}
pub(crate) fn parse(lines: &mut Lines<'_>) -> Result<Self, ParserError> {
let start = lines.next().unwrap();
assert_eq!(start.keyword, "STARTPROPERTIES");
// TODO: check if number of properties is correct
let _n_properties: usize = start
.parameters
.parse()
.map_err(|_| ParserError::with_line("invalid \"STARTPROPERTIES\"", &start))?;
let mut properties = HashMap::new();
for line in lines {
if line.keyword == "ENDPROPERTIES" {
break;
}
let value = if let Ok(int) = line.parameters.parse::<i32>() {
PropertyValue::Int(int)
} else if let Some(text) = line
.parameters
.strip_prefix('"')
.and_then(|p| p.strip_suffix('"'))
{
PropertyValue::Text(text.replace("\"\"", "\""))
} else {
return Err(ParserError::with_line("invalid property", &line));
};
properties.insert(line.keyword.to_string(), value);
}
Ok(Self { properties })
}
/// Tries to get a property.
///
/// Returns `None` if the property doesn't exits and an error if the value has the wrong type.
pub fn try_get<T: PropertyType>(
&self,
property: Property,
) -> Result<Option<T>, PropertyTypeError> {
self.try_get_by_name(&property.to_string())
}
/// Tries to get a property by name.
///
/// Returns `None` if the property doesn't exits and an error if the value has the wrong type.
pub fn try_get_by_name<T: PropertyType>(
&self,
name: &str,
) -> Result<Option<T>, PropertyTypeError> {
self.properties
.get(name)
.map(|value| value.try_into())
.transpose()
}
/// Returns `true` if no properties exist.
pub fn is_empty(&self) -> bool {
self.properties.is_empty()
}
}
/// Marker trait for property value types.
pub trait PropertyType
where
Self: for<'a> TryFrom<&'a PropertyValue, Error = PropertyTypeError>,
{
}
impl PropertyType for String {}
impl PropertyType for i32 {}
impl PropertyType for u32 {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PropertyValue {
Text(String),
Int(i32),
}
impl TryFrom<&PropertyValue> for String {
type Error = PropertyTypeError;
fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
match value {
PropertyValue::Text(text) => Ok(text.clone()),
_ => Err(PropertyTypeError),
}
}
}
impl TryFrom<&PropertyValue> for i32 {
type Error = PropertyTypeError;
fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
match value {
PropertyValue::Int(int) => Ok(*int),
_ => Err(PropertyTypeError),
}
}
}
impl TryFrom<&PropertyValue> for u32 {
type Error = PropertyTypeError;
fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
match value {
PropertyValue::Int(int) if *int >= 0 => Ok(*int as u32),
_ => Err(PropertyTypeError),
}
}
}
/// Invalid property type error.
#[derive(Debug, Error, PartialEq, Eq, PartialOrd, Ord)]
#[error("invalid property type")]
pub struct PropertyTypeError;
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
#[test]
fn string_properties() {
const INPUT: &str = indoc! {r#"
STARTPROPERTIES 3
KEY1 "VALUE"
KEY2 "RANDOM WORDS AND STUFF"
WITH_QUOTE "1""23"""
ENDPROPERTIES
"#};
let mut lines = Lines::new(INPUT);
let properties = Properties::parse(&mut lines).unwrap();
for (key, expected) in [
("KEY1", "VALUE"),
("KEY2", "RANDOM WORDS AND STUFF"),
("WITH_QUOTE", "1\"23\""),
] {
assert_eq!(
properties.try_get_by_name::<String>(key).unwrap(),
Some(expected.to_string()),
"key=\"{key}\""
);
}
}
#[test]
fn integer_properties() {
const INPUT: &str = indoc! {r#"
STARTPROPERTIES 2
POS_INT 10
NEG_INT -20
ENDPROPERTIES
"#};
let mut lines = Lines::new(INPUT);
let properties = Properties::parse(&mut lines).unwrap();
assert_eq!(properties.try_get_by_name::<i32>("POS_INT"), Ok(Some(10)));
assert_eq!(properties.try_get_by_name::<i32>("NEG_INT"), Ok(Some(-20)));
assert_eq!(properties.try_get_by_name::<u32>("POS_INT"), Ok(Some(10)));
assert_eq!(
properties.try_get_by_name::<u32>("NEG_INT"),
Err(PropertyTypeError)
);
assert_eq!(
properties.try_get_by_name::<String>("POS_INT"),
Err(PropertyTypeError)
);
}
#[test]
fn empty_properties() {
const INPUT: &str = indoc! {r#"
STARTPROPERTIES 0
ENDPROPERTIES
"#};
let mut lines = Lines::new(INPUT);
let properties = Properties::parse(&mut lines).unwrap();
assert_eq!(properties.properties, HashMap::new());
}
#[test]
fn property_to_string() {
assert_eq!(&Property::Font.to_string(), "FONT");
assert_eq!(&Property::SuperscriptX.to_string(), "SUPERSCRIPT_X");
assert_eq!(
&Property::AvgLowercaseWidth.to_string(),
"AVG_LOWERCASE_WIDTH"
);
}
}