tfm 0.1.0

Parsers for the TeX font metric (.tfm) and property list (.pl) file formats
Documentation
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Parsers for the TeX font metric (.tfm) and property list (.pl) file formats

use std::panic;
pub mod format;
pub mod pl;

/// Complete contents of a TeX font metric (.tfm) or property list (.pl) file.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct File {
    /// The file header.
    pub header: Header,

    /// Ordered list of character information
    pub char_infos: Vec<CharInfo>,

    // TODO lig_kerns and extensible characters
    /// Additional parameters contained in the file.
    pub params: Params,
}

/// The TFM header, which contains metadata about the file.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Header {
    pub checksum: u32,
    pub design_size: FixWord,
    // TODO: these all have defaults so probably should not be optional
    pub character_coding_scheme: Option<String>,
    pub font_family: Option<String>,
    pub seven_bit_safe: Option<bool>,
    pub face: Option<Face>,

    /// The TFM format allows the header to contain arbitrary additional data.
    pub additional_data: Vec<u32>,
}

/// Fixed-width numeric type used in TFM files.
///
/// This type has 11 bits for the integer part,
/// 20 bits for the fractional part, and a single signed bit.
///
/// In property list files, this type is represented as a decimal number
///   with up to 6 digits after the decimal point.
/// This is a non-lossy representation
///   because 10^(-6) is larger than 2^(-20).
#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
pub struct FixWord(i32);

impl FixWord {
    /// Representation of the number 0 as a [FixWord].
    pub const ZERO: FixWord = FixWord(0);

    /// Representation of the number 1 as a [FixWord].
    pub const UNITY: FixWord = FixWord(1 << 20);
}

impl TryFrom<&str> for FixWord {
    type Error = String;

    fn try_from(input: &str) -> Result<Self, Self::Error> {
        let mut input = input.chars();
        enum Char {
            Digit(i32),
            Other(char),
        }
        impl Char {
            fn new(c: char) -> Char {
                match c {
                    '0' => Char::Digit(0),
                    '1' => Char::Digit(1),
                    '2' => Char::Digit(2),
                    '3' => Char::Digit(3),
                    '4' => Char::Digit(4),
                    '5' => Char::Digit(5),
                    '6' => Char::Digit(6),
                    '7' => Char::Digit(7),
                    '8' => Char::Digit(8),
                    '9' => Char::Digit(9),
                    other => Char::Other(other),
                }
            }
        }

        let mut negative = false;
        let mut integer = None;
        for c in input.by_ref() {
            match Char::new(c) {
                Char::Other('+') | Char::Other(' ') => (),
                Char::Other('-') => {
                    negative = !negative;
                }
                Char::Digit(d) => {
                    integer = Some(d);
                    break;
                }
                Char::Other(other) => return Err(format!["unexpected character {other}"]),
            }
        }
        let negative = negative;

        let mut integer = match integer {
            None => panic![""],
            Some(integer) => integer,
        };
        for c in input.by_ref() {
            match Char::new(c) {
                Char::Digit(d) => {
                    integer = integer * 10 + d;
                    if integer >= 2048 {
                        return Err("real numbers must be in the range [-2048,2048]".to_string());
                    }
                }
                Char::Other('.') => break,
                Char::Other(other) => return Err(format!["unexpected character {other}"]),
            }
        }
        let integer = integer;

        let mut num_fractional_digits = 0;
        let mut fraction_digits = [0; 7];
        for c in input.by_ref() {
            match Char::new(c) {
                Char::Digit(d) => {
                    if num_fractional_digits < 7 {
                        fraction_digits[num_fractional_digits] = d * (1 << 21);
                        num_fractional_digits += 1;
                    }
                }
                Char::Other(other) => return Err(format!["unexpected character {other}"]),
            }
        }
        let mut fraction = 0;
        for i in (0..num_fractional_digits).rev() {
            fraction = fraction_digits[i] + fraction / 10;
        }
        let fraction = (fraction + 10) / 20;

        if integer == 2047 && fraction >= (1 << 20) {
            if negative {
                return Ok(FixWord(i32::MIN));
            }
            return Err("real numbers must be in the range [-2048,2048]".to_string());
        }
        let mut result = integer * FixWord::UNITY.0 + fraction;
        if negative {
            result *= -1;
        }
        Ok(FixWord(result))
    }
}

impl std::fmt::Display for FixWord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut output = String::new();
        let abs: u32 = if self.0 < 0 {
            if self.0 == i32::MIN {
                return write!(f, "-2047.9999999");
            } else {
                output.push('-');
                self.0.unsigned_abs()
            }
        } else {
            self.0 as u32
        };
        let mut integer = abs / (1 << 20);

        // The integer part is at most 2^11 < 10^4, so there are at most 4 decimal digits.
        let mut integer_digits = [0; 4];
        let mut i = 4;
        loop {
            integer_digits[i - 1] = integer % 10;
            integer /= 10;
            i -= 1;
            if integer == 0 {
                break;
            }
        }
        while i < 4 {
            output.push(std::char::from_digit(integer_digits[i], 10).unwrap());
            i += 1;
        }

        output.push('.');
        let mut delta = 10;
        let mut fraction = abs % (1 << 20);
        fraction = fraction * 10 + 5;
        loop {
            if delta > (1 << 20) {
                fraction = fraction + (1 << 19) - (delta / 2);
            }
            output.push(std::char::from_digit(fraction / (1 << 20), 10).unwrap());
            fraction = (fraction % (1 << 20)) * 10;
            delta *= 10;
            if fraction <= delta {
                break;
            }
        }
        write!(f, "{output}")
    }
}

/// Information about a character.
#[derive(Debug, PartialEq, Eq)]
pub struct CharInfo {
    pub id: u8,
    /// Width of the character.
    pub width: FixWord,
    /// Height of the character.
    pub height: FixWord,
    /// Depth of the character.
    pub depth: FixWord,
    /// Italic correction of the character.
    pub italic_correction: FixWord,
}

#[derive(Debug, PartialEq, Eq)]
enum Tag {
    None,
    Ligature(usize),
    List(usize),
    Extension(usize),
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct Face(pub u8);

impl TryFrom<Face> for String {
    type Error = ();

    fn try_from(value: Face) -> Result<Self, Self::Error> {
        let mut raw = value.0;
        if raw >= 18 {
            Err(())
        } else {
            let slope = if raw % 2 == 0 { 'R' } else { 'I' };
            raw /= 2;
            let weight = match raw % 3 {
                0 => 'M',
                1 => 'B',
                _ => 'L',
            };
            raw /= 3;
            let expansion = match raw % 3 {
                0 => 'R',
                1 => 'C',
                _ => 'E',
            };
            Ok(format!["{weight}{slope}{expansion}"])
        }
    }
}

impl TryFrom<&str> for Face {
    type Error = &'static str;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let chars: Vec<char> = value.chars().collect();
        if chars.len() != 3 {
            return Err("face string must have exactly 3 characters");
        }
        let a = match chars[0] {
            'M' => 0_u8,
            'B' => 2_u8,
            'L' => 4_u8,
            _ => {
                return Err("the first character must be either M, B or L");
            }
        };
        let b = match chars[1] {
            'R' => 0_u8,
            'I' => 1_u8,
            _ => {
                return Err("the second character must be either R or I");
            }
        };
        let c = match chars[2] {
            'R' => 0_u8,
            'C' => 6_u8,
            'E' => 12_u8,
            _ => {
                return Err("the third character must be either R, C or E");
            }
        };
        Ok(Face(a + b + c))
    }
}

#[derive(Debug, PartialEq, Eq)]
struct RawCharInfo {
    width_index: usize,
    height_index: usize,
    depth_index: usize,
    italic_index: usize,
    tag: Tag,
}

#[derive(Debug, PartialEq, Eq)]
struct RawLigKern {
    next_raw_lig_kern: Option<usize>,
    next_char: u8,
    op: RawLigKernOp,
}

#[derive(Debug, PartialEq, Eq)]
enum RawLigKernOp {
    Kern(usize),
    Ligature {
        insert_char: u8,
        delete_current: bool,
        delete_next: bool,
        skip: u8,
    },
}

#[derive(Debug, PartialEq, Eq)]
pub struct ExtensibleChar {
    top: u8,
    middle: u8,
    bottom: u8,
    rep: u8,
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Params {
    slant: FixWord,
    space: FixWord,
    space_stretch: FixWord,
    space_shrink: FixWord,
    x_height: FixWord,
    quad: FixWord,
    extra_space: FixWord,
    math_params: MathParams,
    additional_params: Vec<FixWord>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum MathParams {
    None,
    Symbols {
        num_1: FixWord,
        num_2: FixWord,
        num_3: FixWord,
        denom_1: FixWord,
        denom_2: FixWord,
        sup_1: FixWord,
        sup_2: FixWord,
        sup_3: FixWord,
        sub_1: FixWord,
        sub_2: FixWord,
        sup_drop: FixWord,
        sub_drop: FixWord,
        delim_1: FixWord,
        delim_2: FixWord,
        axis_height: FixWord,
    },
    Extension {
        default_thickness: FixWord,
        big_op_spacing: [FixWord; 5],
    },
}

impl Default for MathParams {
    fn default() -> Self {
        MathParams::None
    }
}

impl MathParams {
    fn symbols_default() -> MathParams {
        MathParams::Symbols {
            num_1: FixWord::default(),
            num_2: FixWord::default(),
            num_3: FixWord::default(),
            denom_1: FixWord::default(),
            denom_2: FixWord::default(),
            sup_1: FixWord::default(),
            sup_2: FixWord::default(),
            sup_3: FixWord::default(),
            sub_1: FixWord::default(),
            sub_2: FixWord::default(),
            sup_drop: FixWord::default(),
            sub_drop: FixWord::default(),
            delim_1: FixWord::default(),
            delim_2: FixWord::default(),
            axis_height: FixWord::default(),
        }
    }

    fn extension_default() -> MathParams {
        MathParams::Extension {
            default_thickness: FixWord::default(),
            big_op_spacing: [FixWord::default(); 5],
        }
    }
}

impl Params {
    pub fn set(&mut self, i: usize, value: FixWord) {
        let f = match (i, &mut self.math_params) {
            (0, _) => &mut self.slant,
            (1, _) => &mut self.space,
            (2, _) => &mut self.space_stretch,
            (3, _) => &mut self.space_shrink,
            (4, _) => &mut self.x_height,
            (5, _) => &mut self.quad,
            (6, _) => &mut self.extra_space,

            (i, MathParams::None) => get_additional_param(&mut self.additional_params, i - 7),

            (7, MathParams::Symbols { num_1, .. }) => num_1,
            (8, MathParams::Symbols { num_2, .. }) => num_2,
            (9, MathParams::Symbols { num_3, .. }) => num_3,
            (10, MathParams::Symbols { denom_1, .. }) => denom_1,
            (11, MathParams::Symbols { denom_2, .. }) => denom_2,
            (12, MathParams::Symbols { sup_1, .. }) => sup_1,
            (13, MathParams::Symbols { sup_2, .. }) => sup_2,
            (14, MathParams::Symbols { sup_3, .. }) => sup_3,
            (15, MathParams::Symbols { sub_1, .. }) => sub_1,
            (16, MathParams::Symbols { sub_2, .. }) => sub_2,
            (17, MathParams::Symbols { sup_drop, .. }) => sup_drop,
            (18, MathParams::Symbols { sub_drop, .. }) => sub_drop,
            (19, MathParams::Symbols { delim_1, .. }) => delim_1,
            (20, MathParams::Symbols { delim_2, .. }) => delim_2,
            (21, MathParams::Symbols { axis_height, .. }) => axis_height,
            (i, MathParams::Symbols { .. }) => {
                get_additional_param(&mut self.additional_params, i - 22)
            }

            (
                7,
                MathParams::Extension {
                    default_thickness, ..
                },
            ) => default_thickness,
            (8, MathParams::Extension { big_op_spacing, .. }) => &mut big_op_spacing[0],
            (9, MathParams::Extension { big_op_spacing, .. }) => &mut big_op_spacing[1],
            (10, MathParams::Extension { big_op_spacing, .. }) => &mut big_op_spacing[2],
            (11, MathParams::Extension { big_op_spacing, .. }) => &mut big_op_spacing[3],
            (12, MathParams::Extension { big_op_spacing, .. }) => &mut big_op_spacing[4],
            (i, MathParams::Extension { .. }) => {
                get_additional_param(&mut self.additional_params, i - 13)
            }
        };
        *f = value;
    }
}

fn get_additional_param(additional_params: &mut Vec<FixWord>, i: usize) -> &mut FixWord {
    if additional_params.len() <= i {
        additional_params.resize_with(i + 1, Default::default);
    }
    additional_params.get_mut(i).unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn face_to_string_round_trip() {
        for i in 0_u8..=17_u8 {
            let f1 = Face(i);
            let s: String = f1.try_into().unwrap();
            let s_ref: &str = &s;
            let f2: Face = s_ref.try_into().unwrap();
            assert_eq!(f1, f2)
        }
    }

    #[test]
    fn face_to_string_impossible() {
        for i in 18_u8..=255_u8 {
            let f1 = Face(i);
            let s: Result<String, ()> = f1.try_into();
            assert_eq![s, Err(())];
        }
    }
}