Skip to main content

strata_style/
specificity.rs

1//! Specificity tuple and ordering per W3C Selectors Level 4.
2
3use std::ops::{Add, AddAssign};
4
5/// Specificity vector $\mathbf{S} = (I, A, B, C)$:
6/// - $I$: Inline style (1 for style attribute, 0 otherwise)
7/// - $A$: Number of ID selectors
8/// - $B$: Number of class selectors, attribute selectors, and pseudo-classes
9/// - $C$: Number of type (tag) selectors and pseudo-elements
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
11pub struct Specificity {
12    pub inline: u8,
13    pub id_count: u16,
14    pub class_count: u16,
15    pub type_count: u16,
16}
17
18impl Specificity {
19    pub const ZERO: Self = Self {
20        inline: 0,
21        id_count: 0,
22        class_count: 0,
23        type_count: 0,
24    };
25    pub const INLINE: Self = Self {
26        inline: 1,
27        id_count: 0,
28        class_count: 0,
29        type_count: 0,
30    };
31    pub const ID: Self = Self {
32        inline: 0,
33        id_count: 1,
34        class_count: 0,
35        type_count: 0,
36    };
37    pub const CLASS: Self = Self {
38        inline: 0,
39        id_count: 0,
40        class_count: 1,
41        type_count: 0,
42    };
43    pub const TYPE: Self = Self {
44        inline: 0,
45        id_count: 0,
46        class_count: 0,
47        type_count: 1,
48    };
49
50    pub const fn new(inline: u8, id_count: u16, class_count: u16, type_count: u16) -> Self {
51        Self {
52            inline,
53            id_count,
54            class_count,
55            type_count,
56        }
57    }
58}
59
60impl Add for Specificity {
61    type Output = Self;
62
63    fn add(self, rhs: Self) -> Self::Output {
64        Self {
65            inline: self.inline.saturating_add(rhs.inline),
66            id_count: self.id_count.saturating_add(rhs.id_count),
67            class_count: self.class_count.saturating_add(rhs.class_count),
68            type_count: self.type_count.saturating_add(rhs.type_count),
69        }
70    }
71}
72
73impl AddAssign for Specificity {
74    fn add_assign(&mut self, rhs: Self) {
75        *self = *self + rhs;
76    }
77}