1use std::borrow::Borrow;
8use std::fmt;
9use std::ops::Deref;
10use std::sync::Arc;
11
12use cssparser::{ToCss, serialize_identifier, serialize_string};
13use precomputed_hash::PrecomputedHash;
14
15#[derive(Clone, PartialEq, Eq, Hash)]
21pub struct Atom {
22 text: Arc<str>,
23 hash: u32,
24}
25
26impl Atom {
27 pub fn new(text: &str) -> Self {
28 Self {
29 text: Arc::from(text),
30 hash: fnv1a(text),
31 }
32 }
33
34 pub fn as_str(&self) -> &str {
35 &self.text
36 }
37}
38
39impl Default for Atom {
40 fn default() -> Self {
41 Self::new("")
42 }
43}
44
45impl Deref for Atom {
46 type Target = str;
47
48 fn deref(&self) -> &str {
49 &self.text
50 }
51}
52
53impl Borrow<str> for Atom {
54 fn borrow(&self) -> &str {
55 &self.text
56 }
57}
58
59impl From<&str> for Atom {
60 fn from(text: &str) -> Self {
61 Self::new(text)
62 }
63}
64
65impl fmt::Debug for Atom {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 fmt::Debug::fmt(&*self.text, f)
68 }
69}
70
71impl fmt::Display for Atom {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 f.write_str(&self.text)
74 }
75}
76
77impl PrecomputedHash for Atom {
78 fn precomputed_hash(&self) -> u32 {
79 self.hash
80 }
81}
82
83impl ToCss for Atom {
84 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
85 serialize_identifier(&self.text, dest)
86 }
87}
88
89#[derive(Clone, PartialEq, Eq, Hash, Default)]
91pub struct AttrValue(Arc<str>);
92
93impl AsRef<str> for AttrValue {
94 fn as_ref(&self) -> &str {
95 &self.0
96 }
97}
98
99impl Deref for AttrValue {
100 type Target = str;
101
102 fn deref(&self) -> &str {
103 &self.0
104 }
105}
106
107impl From<&str> for AttrValue {
108 fn from(text: &str) -> Self {
109 Self(Arc::from(text))
110 }
111}
112
113impl fmt::Debug for AttrValue {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 fmt::Debug::fmt(&*self.0, f)
116 }
117}
118
119impl ToCss for AttrValue {
120 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
121 serialize_string(&self.0, dest)
122 }
123}
124
125fn fnv1a(text: &str) -> u32 {
126 let mut hash: u32 = 0x811c_9dc5;
127 for byte in text.bytes() {
128 hash ^= u32::from(byte);
129 hash = hash.wrapping_mul(0x0100_0193);
130 }
131 hash
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137
138 #[test]
139 fn equal_atoms_share_a_hash() {
140 assert_eq!(Atom::new("button"), Atom::from("button"));
141 assert_eq!(
142 Atom::new("button").precomputed_hash(),
143 Atom::new("button").precomputed_hash()
144 );
145 assert_ne!(
146 Atom::new("button").precomputed_hash(),
147 Atom::new("label").precomputed_hash()
148 );
149 assert_eq!(Atom::default(), Atom::new(""));
150 }
151
152 #[test]
153 fn serialises_as_css() {
154 assert_eq!(Atom::new("a b").to_css_string(), "a\\ b");
155 assert_eq!(AttrValue::from("a\"b").to_css_string(), "\"a\\\"b\"");
156 }
157}