Skip to main content

svgtypes/
stream.rs

1// Copyright 2018 the SVG Types Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use crate::Error;
5use alloc::borrow::ToOwned;
6use alloc::vec;
7
8/// Extension methods for XML-subset only operations.
9pub(crate) trait ByteExt {
10    /// Checks if a byte is a numeric sign.
11    fn is_sign(&self) -> bool;
12
13    /// Checks if a byte is a digit.
14    ///
15    /// `[0-9]`
16    fn is_digit(&self) -> bool;
17
18    /// Checks if a byte is a hex digit.
19    ///
20    /// `[0-9A-Fa-f]`
21    fn is_hex_digit(&self) -> bool;
22
23    /// Checks if a byte is a space.
24    ///
25    /// `[ \r\n\t]`
26    fn is_space(&self) -> bool;
27
28    /// Checks if a byte is an ASCII ident char.
29    fn is_ascii_ident(&self) -> bool;
30}
31
32impl ByteExt for u8 {
33    #[inline]
34    fn is_sign(&self) -> bool {
35        matches!(*self, b'+' | b'-')
36    }
37
38    #[inline]
39    fn is_digit(&self) -> bool {
40        matches!(*self, b'0'..=b'9')
41    }
42
43    #[inline]
44    fn is_hex_digit(&self) -> bool {
45        matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
46    }
47
48    #[inline]
49    fn is_space(&self) -> bool {
50        matches!(*self, b' ' | b'\t' | b'\n' | b'\r')
51    }
52
53    #[inline]
54    fn is_ascii_ident(&self) -> bool {
55        matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'-' | b'_')
56    }
57}
58
59trait CharExt {
60    fn is_name_start(&self) -> bool;
61    fn is_name_char(&self) -> bool;
62    fn is_non_ascii_ident(&self) -> bool;
63    fn is_escape(&self) -> bool;
64}
65
66impl CharExt for char {
67    #[inline]
68    fn is_name_start(&self) -> bool {
69        match *self {
70            '_' | 'a'..='z' | 'A'..='Z' => true,
71            _ => self.is_non_ascii_ident() || self.is_escape(),
72        }
73    }
74
75    #[inline]
76    fn is_name_char(&self) -> bool {
77        match *self {
78            '_' | 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' => true,
79            _ => self.is_non_ascii_ident() || self.is_escape(),
80        }
81    }
82
83    /// <https://www.w3.org/TR/css-syntax-3/#non-ascii-ident-code-point>
84    #[inline]
85    fn is_non_ascii_ident(&self) -> bool {
86        matches!(
87            *self,
88            '\u{B7}'
89                | '\u{C0}'..='\u{D6}'
90                | '\u{D8}'..='\u{F6}'
91                | '\u{F8}'..='\u{37D}'
92                | '\u{37F}'..='\u{1FFF}'
93                | '\u{200C}'
94                | '\u{200D}'
95                | '\u{203F}'
96                | '\u{2040}'
97                | '\u{2070}'..='\u{218F}'
98                | '\u{2C00}'..='\u{2FEF}'
99                | '\u{3001}'..='\u{D7FF}'
100                | '\u{F900}'..='\u{FDCF}'
101                | '\u{FDF0}'..='\u{FFFD}'
102                | '\u{10000}'..
103        )
104    }
105
106    #[inline]
107    fn is_escape(&self) -> bool {
108        // TODO: this
109        false
110    }
111}
112
113/// A streaming text parsing interface.
114#[derive(Clone, Copy, PartialEq, Eq, Debug)]
115pub struct Stream<'a> {
116    text: &'a str,
117    pos: usize,
118}
119
120impl<'a> From<&'a str> for Stream<'a> {
121    #[inline]
122    fn from(text: &'a str) -> Self {
123        Stream { text, pos: 0 }
124    }
125}
126
127impl<'a> Stream<'a> {
128    /// Returns the current position in bytes.
129    #[inline]
130    pub fn pos(&self) -> usize {
131        self.pos
132    }
133
134    /// Calculates the current position in chars.
135    pub fn calc_char_pos(&self) -> usize {
136        self.calc_char_pos_at(self.pos)
137    }
138
139    /// Calculates the current position in chars.
140    pub fn calc_char_pos_at(&self, byte_pos: usize) -> usize {
141        let mut pos = 1;
142        for (idx, _) in self.text.char_indices() {
143            if idx >= byte_pos {
144                break;
145            }
146
147            pos += 1;
148        }
149
150        pos
151    }
152
153    /// Sets current position equal to the end.
154    ///
155    /// Used to indicate end of parsing on error.
156    #[inline]
157    pub fn jump_to_end(&mut self) {
158        self.pos = self.text.len();
159    }
160
161    /// Checks if the stream is reached the end.
162    ///
163    /// Any [`pos()`] value larger than original text length indicates stream end.
164    ///
165    /// Accessing stream after reaching end via safe methods will produce
166    /// an `UnexpectedEndOfStream` error.
167    ///
168    /// Accessing stream after reaching end via *_unchecked methods will produce
169    /// a Rust's bound checking error.
170    ///
171    /// [`pos()`]: #method.pos
172    #[inline]
173    pub fn at_end(&self) -> bool {
174        self.pos >= self.text.len()
175    }
176
177    /// Returns a byte from a current stream position.
178    ///
179    /// # Errors
180    ///
181    /// - `UnexpectedEndOfStream`
182    #[inline]
183    pub fn curr_byte(&self) -> Result<u8, Error> {
184        if self.at_end() {
185            return Err(Error::UnexpectedEndOfStream);
186        }
187
188        Ok(self.curr_byte_unchecked())
189    }
190
191    #[inline]
192    pub fn chars(&self) -> core::str::Chars<'a> {
193        self.text[self.pos..].chars()
194    }
195
196    /// Returns a byte from a current stream position.
197    ///
198    /// # Panics
199    ///
200    /// - if the current position is after the end of the data
201    #[inline]
202    pub fn curr_byte_unchecked(&self) -> u8 {
203        self.text.as_bytes()[self.pos]
204    }
205
206    /// Checks that current byte is equal to provided.
207    ///
208    /// Returns `false` if no bytes left.
209    #[inline]
210    pub fn is_curr_byte_eq(&self, c: u8) -> bool {
211        if !self.at_end() {
212            self.curr_byte_unchecked() == c
213        } else {
214            false
215        }
216    }
217
218    /// Returns a next byte from a current stream position.
219    ///
220    /// # Errors
221    ///
222    /// - `UnexpectedEndOfStream`
223    #[inline]
224    pub fn next_byte(&self) -> Result<u8, Error> {
225        if self.pos + 1 >= self.text.len() {
226            return Err(Error::UnexpectedEndOfStream);
227        }
228
229        Ok(self.text.as_bytes()[self.pos + 1])
230    }
231
232    /// Advances by `n` bytes.
233    #[inline]
234    pub fn advance(&mut self, n: usize) {
235        debug_assert!(self.pos + n <= self.text.len());
236        self.pos += n;
237    }
238
239    /// Skips whitespaces.
240    ///
241    /// Accepted values: `' ' \n \r \t`.
242    pub fn skip_spaces(&mut self) {
243        while !self.at_end() && self.curr_byte_unchecked().is_space() {
244            self.advance(1);
245        }
246    }
247
248    /// Checks that the stream starts with a selected text.
249    ///
250    /// We are using `&[u8]` instead of `&str` for performance reasons.
251    #[inline]
252    pub fn starts_with(&self, text: &[u8]) -> bool {
253        self.text.as_bytes()[self.pos..].starts_with(text)
254    }
255
256    /// Consumes current byte if it's equal to the provided byte.
257    ///
258    /// # Errors
259    ///
260    /// - `InvalidChar`
261    /// - `UnexpectedEndOfStream`
262    pub fn consume_byte(&mut self, c: u8) -> Result<(), Error> {
263        if self.curr_byte()? != c {
264            return Err(Error::InvalidChar(
265                vec![self.curr_byte_unchecked(), c],
266                self.calc_char_pos(),
267            ));
268        }
269
270        self.advance(1);
271        Ok(())
272    }
273
274    /// Parses a single [ident](https://drafts.csswg.org/css-syntax-3/#typedef-ident-token).
275    ///
276    /// # Errors
277    ///
278    /// - `InvalidIdent`
279    pub fn parse_ident(&mut self) -> Result<&'a str, Error> {
280        let start = self.pos();
281
282        if self.curr_byte() == Ok(b'-') {
283            self.advance(1);
284        }
285
286        let mut iter = self.chars();
287        if let Some(c) = iter.next() {
288            if c.is_name_start() {
289                self.advance(c.len_utf8());
290            } else {
291                return Err(Error::InvalidIdent);
292            }
293        }
294
295        for c in iter {
296            if c.is_name_char() {
297                self.advance(c.len_utf8());
298            } else {
299                break;
300            }
301        }
302
303        if start == self.pos() {
304            return Err(Error::InvalidIdent);
305        }
306
307        let name = self.slice_back(start);
308        Ok(name)
309    }
310
311    /// Consumes a single ident consisting of ASCII characters, if available.
312    pub fn consume_ascii_ident(&mut self) -> &'a str {
313        let start = self.pos;
314        self.skip_bytes(|_, c| c.is_ascii_ident());
315        self.slice_back(start)
316    }
317
318    /// Parses a single [quoted string](https://drafts.csswg.org/css-syntax-3/#typedef-string-token)
319    ///
320    /// # Errors
321    ///
322    /// - `UnexpectedEndOfStream`
323    /// - `InvalidValue`
324    pub fn parse_quoted_string(&mut self) -> Result<&'a str, Error> {
325        // Check for opening quote.
326        let quote = self.curr_byte()?;
327
328        if quote != b'\'' && quote != b'"' {
329            return Err(Error::InvalidValue);
330        }
331
332        let mut prev = quote;
333        self.advance(1);
334
335        let start = self.pos();
336
337        while !self.at_end() {
338            let curr = self.curr_byte_unchecked();
339
340            // Advance until the closing quote.
341            if curr == quote {
342                // Check for escaped quote.
343                if prev != b'\\' {
344                    break;
345                }
346            }
347
348            prev = curr;
349            self.advance(1);
350        }
351
352        let value = self.slice_back(start);
353
354        // Check for closing quote.
355        self.consume_byte(quote)?;
356
357        Ok(value)
358    }
359
360    /// Consumes selected string.
361    ///
362    /// # Errors
363    ///
364    /// - `InvalidChar`
365    /// - `UnexpectedEndOfStream`
366    pub fn consume_string(&mut self, text: &[u8]) -> Result<(), Error> {
367        if self.at_end() {
368            return Err(Error::UnexpectedEndOfStream);
369        }
370
371        if !self.starts_with(text) {
372            let len = core::cmp::min(text.len(), self.text.len() - self.pos);
373            // Collect chars and do not slice a string,
374            // because the `len` can be on the char boundary.
375            // Which lead to a panic.
376            let actual = self.text[self.pos..].chars().take(len).collect();
377
378            // Assume that all input `text` are valid UTF-8 strings, so unwrap is safe.
379            let expected = core::str::from_utf8(text).unwrap().to_owned();
380
381            return Err(Error::InvalidString(
382                vec![actual, expected],
383                self.calc_char_pos(),
384            ));
385        }
386
387        self.advance(text.len());
388        Ok(())
389    }
390
391    /// Consumes bytes by the predicate and returns them.
392    ///
393    /// The result can be empty.
394    pub fn consume_bytes<F>(&mut self, f: F) -> &'a str
395    where
396        F: Fn(&Stream<'_>, u8) -> bool,
397    {
398        let start = self.pos();
399        self.skip_bytes(f);
400        self.slice_back(start)
401    }
402
403    /// Consumes bytes by the predicate.
404    pub fn skip_bytes<F>(&mut self, f: F)
405    where
406        F: Fn(&Stream<'_>, u8) -> bool,
407    {
408        while !self.at_end() {
409            let c = self.curr_byte_unchecked();
410            if f(self, c) {
411                self.advance(1);
412            } else {
413                break;
414            }
415        }
416    }
417
418    /// Slices data from `pos` to the current position.
419    #[inline]
420    pub fn slice_back(&self, pos: usize) -> &'a str {
421        &self.text[pos..self.pos]
422    }
423
424    /// Slices data from the current position to the end.
425    #[inline]
426    pub fn slice_tail(&self) -> &'a str {
427        &self.text[self.pos..]
428    }
429
430    /// Parses number or percent from the stream.
431    ///
432    /// Percent value will be normalized.
433    pub fn parse_number_or_percent(&mut self) -> Result<f64, Error> {
434        self.skip_spaces();
435
436        let n = self.parse_number()?;
437        if self.starts_with(b"%") {
438            self.advance(1);
439            Ok(n / 100.0)
440        } else {
441            Ok(n)
442        }
443    }
444
445    /// Parses number or percent from a list of numbers and/or percents.
446    pub fn parse_list_number_or_percent(&mut self) -> Result<f64, Error> {
447        if self.at_end() {
448            return Err(Error::UnexpectedEndOfStream);
449        }
450
451        let l = self.parse_number_or_percent()?;
452        self.skip_spaces();
453        self.parse_list_separator();
454        Ok(l)
455    }
456
457    /// Skips digits.
458    pub fn skip_digits(&mut self) {
459        self.skip_bytes(|_, c| c.is_digit());
460    }
461
462    #[inline]
463    pub(crate) fn parse_list_separator(&mut self) {
464        if self.is_curr_byte_eq(b',') {
465            self.advance(1);
466        }
467    }
468}