Files
a0_basic_app
a1_vehicle
a2_async_sim
ab_glyph
ab_glyph_rasterizer
adler
adler32
agents
aho_corasick
anyhow
approx
aquamarine
ash
atty
bitflags
bytemuck
byteorder
cache_padded
cfg_if
chrono
color_quant
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
deflate
draw2d
either
flexi_logger
generic_array
gif
glfw
glfw_sys
glob
image
indoc
itertools
jpeg_decoder
lazy_static
libc
libloading
log
matrixmultiply
memchr
memoffset
miniz_oxide
nalgebra
base
geometry
linalg
third_party
num_complex
num_cpus
num_integer
num_iter
num_rational
num_traits
owned_ttf_parser
paste
png
proc_macro2
proc_macro_error
proc_macro_error_attr
quote
raw_window_handle
rawpointer
rayon
rayon_core
regex
regex_syntax
scoped_threadpool
scopeguard
semver
semver_parser
serde
serde_derive
simba
smawk
spin_sleep
syn
terminal_size
textwrap
thiserror
thiserror_impl
tiff
time
triple_buffer
ttf_parser
typenum
unicode_width
unicode_xid
unindent
vk_sys
weezl
yansi
  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
// https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx

use core::num::NonZeroU16;

use crate::GlyphId;
use crate::parser::{Stream, FromData, LazyArray16};


#[derive(Clone, Copy)]
struct HorizontalMetrics {
    advance_width: u16,
    lsb: i16,
}

impl FromData for HorizontalMetrics {
    const SIZE: usize = 4;

    #[inline]
    fn parse(data: &[u8]) -> Option<Self> {
        let mut s = Stream::new(data);
        Some(HorizontalMetrics {
            advance_width: s.read::<u16>()?,
            lsb: s.read::<i16>()?,
        })
    }
}


#[derive(Clone, Copy)]
pub struct Table<'a> {
    metrics: LazyArray16<'a, HorizontalMetrics>,
    bearings: Option<LazyArray16<'a, i16>>,
    number_of_metrics: u16, // Sum of long metrics + bearings.
}

impl<'a> Table<'a> {
    pub fn parse(
        data: &'a [u8],
        number_of_hmetrics: NonZeroU16,
        number_of_glyphs: NonZeroU16,
    ) -> Option<Self> {
        let mut s = Stream::new(data);
        let metrics = s.read_array16::<HorizontalMetrics>(number_of_hmetrics.get())?;

        let mut number_of_metrics = number_of_hmetrics.get();

        // 'If the number_of_hmetrics is less than the total number of glyphs,
        // then that array is followed by an array for the left side bearing values
        // of the remaining glyphs.'
        let bearings_count = number_of_glyphs.get().checked_sub(number_of_hmetrics.get());
        let bearings = if let Some(count) = bearings_count {
            number_of_metrics += count;
            s.read_array16::<i16>(count)
        } else {
            None
        };

        Some(Table {
            metrics,
            bearings,
            number_of_metrics,
        })
    }

    #[inline]
    pub fn advance(&self, glyph_id: GlyphId) -> Option<u16> {
        if glyph_id.0 >= self.number_of_metrics {
            return None;
        }

        if let Some(metrics) = self.metrics.get(glyph_id.0) {
            Some(metrics.advance_width)
        } else {
            // 'As an optimization, the number of records can be less than the number of glyphs,
            // in which case the advance width value of the last record applies
            // to all remaining glyph IDs.'
            self.metrics.last().map(|m| m.advance_width)
        }
    }

    #[inline]
    pub fn side_bearing(&self, glyph_id: GlyphId) -> Option<i16> {
        if let Some(metrics) = self.metrics.get(glyph_id.0) {
            Some(metrics.lsb)
        } else if let Some(bearings) = self.bearings {
            // 'If the number_of_hmetrics is less than the total number of glyphs,
            // then that array is followed by an array for the left side bearing values
            // of the remaining glyphs.'

            let number_of_hmetrics = self.metrics.len();

            // Check for overflow.
            if glyph_id.0 < number_of_hmetrics {
                return None;
            }

            bearings.get(glyph_id.0 - number_of_hmetrics)
        } else {
            None
        }
    }
}

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

    macro_rules! nzu16 {
        ($n:expr) => { NonZeroU16::new($n).unwrap() };
    }

    #[test]
    fn simple_case() {
        let data = &[
            0x00, 0x01, // advance width [0]: 1
            0x00, 0x02, // side bearing [0]: 2
        ];

        let table = Table::parse(data, nzu16!(1), nzu16!(1)).unwrap();
        assert_eq!(table.advance(GlyphId(0)), Some(1));
        assert_eq!(table.side_bearing(GlyphId(0)), Some(2));
    }

    #[test]
    fn empty() {
        assert!(Table::parse(&[], nzu16!(1), nzu16!(1)).is_none());
    }

    #[test]
    fn smaller_than_glyphs_count() {
        let data = &[
            0x00, 0x01, // advance width [0]: 1
            0x00, 0x02, // side bearing [0]: 2

            0x00, 0x03, // side bearing [1]: 3
        ];

        let table = Table::parse(data, nzu16!(1), nzu16!(2)).unwrap();
        assert_eq!(table.advance(GlyphId(0)), Some(1));
        assert_eq!(table.side_bearing(GlyphId(0)), Some(2));
        assert_eq!(table.advance(GlyphId(1)), Some(1));
        assert_eq!(table.side_bearing(GlyphId(1)), Some(3));
    }

    #[test]
    fn less_metrics_than_glyphs() {
        let data = &[
            0x00, 0x01, // advance width [0]: 1
            0x00, 0x02, // side bearing [0]: 2

            0x00, 0x03, // advance width [1]: 3
            0x00, 0x04, // side bearing [1]: 4

            0x00, 0x05, // side bearing [2]: 5
        ];

        let table = Table::parse(data, nzu16!(2), nzu16!(1)).unwrap();
        assert_eq!(table.side_bearing(GlyphId(0)), Some(2));
        assert_eq!(table.side_bearing(GlyphId(1)), Some(4));
        assert_eq!(table.side_bearing(GlyphId(2)), None);
    }

    #[test]
    fn glyph_out_of_bounds_0() {
        let data = &[
            0x00, 0x01, // advance width [0]: 1
            0x00, 0x02, // side bearing [0]: 2
        ];

        let table = Table::parse(data, nzu16!(1), nzu16!(1)).unwrap();
        assert_eq!(table.advance(GlyphId(0)), Some(1));
        assert_eq!(table.side_bearing(GlyphId(0)), Some(2));
        assert_eq!(table.advance(GlyphId(1)), None);
        assert_eq!(table.side_bearing(GlyphId(1)), None);
    }

    #[test]
    fn glyph_out_of_bounds_1() {
        let data = &[
            0x00, 0x01, // advance width [0]: 1
            0x00, 0x02, // side bearing [0]: 2

            0x00, 0x03, // side bearing [1]: 3
        ];

        let table = Table::parse(data, nzu16!(1), nzu16!(2)).unwrap();
        assert_eq!(table.advance(GlyphId(1)), Some(1));
        assert_eq!(table.side_bearing(GlyphId(1)), Some(3));
        assert_eq!(table.advance(GlyphId(2)), None);
        assert_eq!(table.side_bearing(GlyphId(2)), None);
    }
}