tl/parser/
options.rs

1mod flags {
2    pub const TRACK_IDS: u8 = 1 << 0;
3    pub const TRACK_CLASSES: u8 = 1 << 1;
4    pub const HIGHEST: u8 = TRACK_CLASSES;
5}
6
7/// Options for the HTML Parser
8///
9/// This allows users of this library to configure the parser.
10/// The default options (`ParserOptions::default()`) are optimized for raw parsing.
11/// If you need to do HTML tag lookups by ID or class names, you can enable tracking.
12/// This will cache HTML nodes as they appear in the source code on the fly.
13#[derive(Debug, Copy, Clone, PartialEq, Default)]
14pub struct ParserOptions {
15    flags: u8,
16}
17
18impl ParserOptions {
19    /// Creates a new [ParserOptions] with no flags set
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /// Creates a [ParserOptions] from a bitset
25    pub fn from_raw_checked(flags: u8) -> Option<Self> {
26        if flags > flags::HIGHEST * 2 - 1 {
27            None
28        } else {
29            Some(Self { flags })
30        }
31    }
32
33    /// Returns the raw flags of this bitset
34    pub fn to_raw(&self) -> u8 {
35        self.flags
36    }
37
38    fn set_flag(&mut self, flag: u8) {
39        self.flags |= flag;
40    }
41
42    #[inline]
43    fn has_flag(&self, flag: u8) -> bool {
44        self.flags & flag != 0
45    }
46
47    /// Enables tracking of HTML Tag IDs and stores them in a lookup table.
48    ///
49    /// This makes `get_element_by_id()` lookups ~O(1)
50    pub fn track_ids(mut self) -> Self {
51        self.set_flag(flags::TRACK_IDS);
52        self
53    }
54
55    /// Enables tracking of HTML Tag classes and stores them in a lookup table.
56    ///
57    /// This makes `get_elements_by_class_name()` lookups ~O(1)
58    pub fn track_classes(mut self) -> Self {
59        self.set_flag(flags::TRACK_CLASSES);
60        self
61    }
62
63    /// Returns whether the parser is tracking HTML Tag IDs.
64    #[inline]
65    pub fn is_tracking_ids(&self) -> bool {
66        self.has_flag(flags::TRACK_IDS)
67    }
68
69    /// Returns whether the parser is tracking HTML Tag classes.
70    #[inline]
71    pub fn is_tracking_classes(&self) -> bool {
72        self.has_flag(flags::TRACK_CLASSES)
73    }
74
75    /// Returns whether the parser is tracking HTML Tag IDs or classes (previously enabled by a call to `track_ids()` or `track_classes()`).
76    #[inline]
77    pub fn is_tracking(&self) -> bool {
78        // for now we can just check if any bit is set, may or may not lead to better codegen than two cmps
79        // this must be changed in some way if we ever add more flags
80        // self.is_tracking_ids() || self.is_tracking_classes()
81        self.flags != 0
82    }
83}