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
use write_fonts::tables::post::Post;

use super::{GlyphId, GlyphIdent, GlyphName};
use std::{
    borrow::Cow,
    collections::{BTreeMap, HashMap},
    convert::TryInto,
    iter::FromIterator,
};

/// A glyph map for mapping from raw glyph identifiers to numeral `GlyphId`s.
///
/// This is used to map from names or CIDS encountered in a FEA file to the actual
/// GlyphIds that will be used in the final font.
///
/// Currently, the only way to construct this type is by calling `collect()`
/// on an iterator of cids or names.
#[derive(Clone, Debug, Default)]
pub struct GlyphMap {
    names: HashMap<GlyphName, GlyphId>,
    cids: HashMap<u16, GlyphId>,
}

impl GlyphMap {
    /// The total number of glyphs
    pub fn len(&self) -> usize {
        self.names.len() + self.cids.len()
    }

    /// Returns `true` if this map contains no glyphs
    pub fn is_empty(&self) -> bool {
        self.names.is_empty() && self.cids.is_empty()
    }

    /// Generates a reverse map of ids -> raw identifers (names or CIDs)
    //  maybe just for testing?
    pub fn reverse_map(&self) -> BTreeMap<GlyphId, GlyphIdent> {
        self.names
            .iter()
            .map(|(name, id)| (*id, GlyphIdent::Name(name.clone())))
            .chain(
                self.cids
                    .iter()
                    .map(|(cid, id)| (*id, GlyphIdent::Cid(*cid))),
            )
            .collect()
    }

    /// Return `true` if the map contains the provided `GlyphIdent`.
    pub fn contains<Q: ?Sized + sealed::AsGlyphIdent>(&self, key: &Q) -> bool {
        if let Some(name) = key.named() {
            self.names.contains_key(name)
        } else if let Some(cid) = key.cid() {
            self.cids.contains_key(cid)
        } else {
            unreachable!()
        }
    }

    /// Return the `GlyphId` for the provided `GlyphIdent`
    pub fn get<Q: ?Sized + sealed::AsGlyphIdent>(&self, key: &Q) -> Option<GlyphId> {
        if let Some(name) = key.named() {
            self.names.get(name).copied()
        } else if let Some(cid) = key.cid() {
            self.cids.get(cid).copied()
        } else {
            unreachable!()
        }
    }

    /// Generate a post table from this glyph map
    pub fn make_post_table(&self) -> Post {
        let reverse = self.reverse_map();
        let rev_vec = reverse
            .values()
            .map(|val| match val {
                GlyphIdent::Name(s) => Cow::Borrowed(s.as_str()),
                GlyphIdent::Cid(cid) => Cow::Owned(format!("cid{:05}", *cid)),
            })
            .collect::<Vec<_>>();

        Post::new_v2(rev_vec.iter().map(Cow::as_ref))
    }
}

impl FromIterator<u16> for GlyphMap {
    fn from_iter<T: IntoIterator<Item = u16>>(iter: T) -> Self {
        GlyphMap {
            names: HashMap::new(),
            cids: iter
                .into_iter()
                .enumerate()
                .map(|(i, cid)| (cid, GlyphId::new(i.try_into().unwrap())))
                .collect(),
        }
    }
}

impl FromIterator<GlyphName> for GlyphMap {
    fn from_iter<T: IntoIterator<Item = GlyphName>>(iter: T) -> Self {
        GlyphMap {
            names: iter
                .into_iter()
                .enumerate()
                .map(|(i, cid)| (cid, GlyphId::new(i.try_into().unwrap())))
                .collect(),
            cids: HashMap::new(),
        }
    }
}

// only intended for testing.
impl FromIterator<GlyphIdent> for GlyphMap {
    fn from_iter<T: IntoIterator<Item = GlyphIdent>>(iter: T) -> Self {
        let mut names = HashMap::new();
        let mut cids = HashMap::new();
        for (idx, item) in iter.into_iter().enumerate() {
            let idx = GlyphId::new(idx.try_into().unwrap());
            match item {
                GlyphIdent::Cid(cid) => cids.insert(cid, idx),
                GlyphIdent::Name(name) => names.insert(name, idx),
            };
        }
        GlyphMap { names, cids }
    }
}

mod sealed {
    use super::{super::GlyphIdent, GlyphName};

    /// Something that is either a Cid or a glyph name.
    ///
    /// This is only implemented internally.
    ///
    /// Invariant: an implementor must return `Some` from exactly one of these
    /// two methods.
    pub trait AsGlyphIdent {
        fn named(&self) -> Option<&str> {
            None
        }

        fn cid(&self) -> Option<&u16> {
            None
        }
    }

    impl AsGlyphIdent for str {
        fn named(&self) -> Option<&str> {
            Some(self)
        }
    }

    impl AsGlyphIdent for GlyphName {
        fn named(&self) -> Option<&str> {
            Some(self)
        }
    }

    impl AsGlyphIdent for u16 {
        fn cid(&self) -> Option<&u16> {
            Some(self)
        }
    }

    impl AsGlyphIdent for GlyphIdent {
        fn named(&self) -> Option<&str> {
            if let GlyphIdent::Name(name) = self {
                Some(name)
            } else {
                None
            }
        }

        fn cid(&self) -> Option<&u16> {
            if let GlyphIdent::Cid(cid) = self {
                Some(cid)
            } else {
                None
            }
        }
    }
}