Skip to main content

harfrust/
feature.rs

1use crate::{text_parser::TextParser, Tag};
2use core::{
3    ops::{Bound, RangeBounds},
4    str::FromStr,
5};
6
7/// An OpenType feature and the text range where it applies.
8#[repr(C)]
9#[derive(Clone, Copy, PartialEq, Hash, Debug)]
10pub struct Feature {
11    /// OpenType feature tag.
12    pub tag: Tag,
13    /// Value assigned to the feature, usually `0` to disable or `1` to enable it.
14    pub value: u32,
15    /// First cluster index to which the feature applies.
16    pub start: u32,
17    /// Upper cluster index of the feature's range.
18    pub end: u32,
19}
20
21impl Feature {
22    /// Start index for a feature that applies to the whole buffer.
23    pub const GLOBAL_START: u32 = 0;
24    /// End index for a feature that applies to the whole buffer.
25    pub const GLOBAL_END: u32 = u32::MAX;
26
27    /// Creates a feature for the given tag, value, and cluster range.
28    pub fn new(tag: Tag, value: u32, range: impl RangeBounds<usize>) -> Feature {
29        let max = Self::GLOBAL_END as usize;
30        let start = match range.start_bound() {
31            Bound::Included(&included) => included.min(max) as u32,
32            Bound::Excluded(&excluded) => excluded.min(max - 1) as u32 + 1,
33            Bound::Unbounded => Self::GLOBAL_START,
34        };
35        let end = match range.end_bound() {
36            Bound::Included(&included) => included.min(max) as u32,
37            Bound::Excluded(&excluded) => excluded.saturating_sub(1).min(max) as u32,
38            Bound::Unbounded => Self::GLOBAL_END,
39        };
40
41        Feature {
42            tag,
43            value,
44            start,
45            end,
46        }
47    }
48
49    pub(crate) fn is_global(&self) -> bool {
50        self.start == Self::GLOBAL_START && self.end == Self::GLOBAL_END
51    }
52}
53
54impl FromStr for Feature {
55    type Err = &'static str;
56
57    /// Parses HarfBuzz feature syntax.
58    ///
59    /// Possible values:
60    ///
61    /// - `kern` and `+kern` enable kerning globally.
62    /// - `-kern` and `kern=0` disable it globally.
63    /// - `aalt=2` selects value 2 for the `aalt` feature.
64    /// - `kern[5:]` applies from cluster 5 onward.
65    /// - `kern[3:5]` applies to clusters 3 and 4.
66    /// - `kern[3]` applies to cluster 3.
67    fn from_str(s: &str) -> Result<Self, Self::Err> {
68        fn parse(s: &str) -> Option<Feature> {
69            if s.is_empty() {
70                return None;
71            }
72
73            let mut p = TextParser::new(s);
74
75            // Parse prefix.
76            let mut value = 1;
77            match p.curr_byte()? {
78                b'-' => {
79                    value = 0;
80                    p.advance(1);
81                }
82                b'+' => {
83                    value = 1;
84                    p.advance(1);
85                }
86                _ => {}
87            }
88
89            // Parse tag.
90            p.skip_spaces();
91            let quote = p.consume_quote();
92
93            let tag = p.consume_tag()?;
94
95            // Force closing quote.
96            if let Some(quote) = quote {
97                p.consume_byte(quote)?;
98            }
99
100            // Parse indices.
101            p.skip_spaces();
102
103            let (start, end) = if p.consume_byte(b'[').is_some() {
104                let start_opt = p.consume_i32();
105                let start = start_opt.unwrap_or(0) as u32; // negative value overflow is ok
106
107                let end = if matches!(p.curr_byte(), Some(b':' | b';')) {
108                    p.advance(1);
109                    p.consume_i32().unwrap_or(-1) as u32 // negative value overflow is ok
110                } else {
111                    if start_opt.is_some() && start != Feature::GLOBAL_END {
112                        start + 1
113                    } else {
114                        Feature::GLOBAL_END
115                    }
116                };
117
118                p.consume_byte(b']')?;
119
120                (start, end)
121            } else {
122                (Feature::GLOBAL_START, Feature::GLOBAL_END)
123            };
124
125            // Parse postfix.
126            let had_equal = p.consume_byte(b'=').is_some();
127            let value1 = p
128                .consume_i32()
129                .or_else(|| p.consume_bool().map(|b| b as i32));
130
131            if had_equal && value1.is_none() {
132                return None;
133            }
134
135            if let Some(value1) = value1 {
136                value = value1 as u32; // negative value overflow is ok
137            }
138
139            p.skip_spaces();
140
141            if !p.at_end() {
142                return None;
143            }
144
145            Some(Feature {
146                tag,
147                value,
148                start,
149                end,
150            })
151        }
152
153        parse(s).ok_or("invalid feature")
154    }
155}
156
157#[cfg(test)]
158mod tests_features {
159    use super::*;
160    use core::str::FromStr;
161
162    macro_rules! test {
163        ($name:ident, $text:expr, $tag:expr, $value:expr, $range:expr) => {
164            #[test]
165            fn $name() {
166                assert_eq!(
167                    Feature::from_str($text).unwrap(),
168                    Feature::new(Tag::new($tag), $value, $range)
169                );
170            }
171        };
172    }
173
174    test!(parse_01, "kern", b"kern", 1, ..);
175    test!(parse_02, "+kern", b"kern", 1, ..);
176    test!(parse_03, "-kern", b"kern", 0, ..);
177    test!(parse_04, "kern=0", b"kern", 0, ..);
178    test!(parse_05, "kern=1", b"kern", 1, ..);
179    test!(parse_06, "kern=2", b"kern", 2, ..);
180    test!(parse_07, "kern[]", b"kern", 1, ..);
181    test!(parse_08, "kern[:]", b"kern", 1, ..);
182    test!(parse_09, "kern[5:]", b"kern", 1, 5..);
183    test!(parse_10, "kern[:5]", b"kern", 1, ..=5);
184    test!(parse_11, "kern[3:5]", b"kern", 1, 3..=5);
185    test!(parse_12, "kern[3]", b"kern", 1, 3..=4);
186    test!(parse_13, "kern[3:5]=2", b"kern", 2, 3..=5);
187    test!(parse_14, "kern[3;5]=2", b"kern", 2, 3..=5);
188    test!(parse_15, "kern[:-1]", b"kern", 1, ..);
189    test!(parse_16, "kern[-1]", b"kern", 1, u32::MAX as usize..);
190    test!(parse_17, "kern=on", b"kern", 1, ..);
191    test!(parse_18, "kern=off", b"kern", 0, ..);
192    test!(parse_19, "kern=oN", b"kern", 1, ..);
193    test!(parse_20, "kern=oFf", b"kern", 0, ..);
194}