Skip to main content

actix_web_csp/
utils.rs

1use bytes::BytesMut;
2use parking_lot::Mutex;
3use smallvec::SmallVec;
4use std::sync::atomic::{AtomicUsize, Ordering};
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8#[derive(Debug)]
9pub(crate) struct BytesCache<const N: usize> {
10    buffers: SmallVec<[BytesMut; N]>,
11    hit_count: usize,
12    miss_count: usize,
13}
14
15impl<const N: usize> BytesCache<N> {
16    #[inline]
17    pub fn new() -> Self {
18        Self {
19            buffers: SmallVec::new(),
20            hit_count: 0,
21            miss_count: 0,
22        }
23    }
24
25    #[inline]
26    pub fn get(&mut self, capacity: usize) -> BytesMut {
27        if let Some(mut buf) = self.buffers.pop() {
28            self.hit_count += 1;
29            buf.clear();
30            if buf.capacity() < capacity {
31                buf.reserve(capacity.saturating_sub(buf.capacity()));
32            }
33            buf
34        } else {
35            self.miss_count += 1;
36            BytesMut::with_capacity(capacity.max(1024))
37        }
38    }
39
40    #[inline]
41    pub fn recycle(&mut self, mut buffer: BytesMut) {
42        if self.buffers.len() < N && buffer.capacity() >= 512 {
43            buffer.clear();
44            self.buffers.push(buffer);
45        }
46    }
47}
48
49impl<const N: usize> Default for BytesCache<N> {
50    #[inline]
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56pub(crate) trait BufferWriter {
57    fn write_to_buffer(&self, buffer: &mut BytesMut);
58}
59
60#[derive(Debug, Clone)]
61pub(crate) struct CachedValue<T> {
62    value: T,
63    timestamp: Instant,
64    ttl: Duration,
65}
66
67impl<T> CachedValue<T> {
68    #[inline]
69    pub fn new(value: T, ttl: Duration) -> Self {
70        Self {
71            value,
72            timestamp: Instant::now(),
73            ttl,
74        }
75    }
76
77    #[inline]
78    pub fn is_valid(&self) -> bool {
79        self.timestamp.elapsed() < self.ttl
80    }
81
82    #[inline]
83    pub fn value(&self) -> &T {
84        &self.value
85    }
86}
87
88use rustc_hash::FxHashMap;
89use std::sync::OnceLock;
90
91static COMMON_STRINGS: &[&str] = &[
92    "'self'",
93    "'none'",
94    "'unsafe-inline'",
95    "'unsafe-eval'",
96    "'strict-dynamic'",
97    "'report-sample'",
98    "'wasm-unsafe-eval'",
99    "'unsafe-hashes'",
100    "https:",
101    "http:",
102    "data:",
103    "blob:",
104    "filesystem:",
105    "ws:",
106    "wss:",
107    "'unsafe-allow-redirects'",
108    "default-src",
109    "script-src",
110    "style-src",
111    "img-src",
112    "connect-src",
113    "font-src",
114    "object-src",
115    "media-src",
116    "frame-src",
117    "worker-src",
118    "manifest-src",
119    "child-src",
120    "frame-ancestors",
121    "base-uri",
122    "form-action",
123    "sandbox",
124];
125
126static STRING_INTERN_MAP: OnceLock<FxHashMap<&'static str, &'static str>> = OnceLock::new();
127
128#[inline]
129pub fn intern_string(s: &str) -> Option<&'static str> {
130    let map = STRING_INTERN_MAP.get_or_init(|| {
131        let mut map = FxHashMap::with_capacity_and_hasher(COMMON_STRINGS.len(), Default::default());
132        for &common in COMMON_STRINGS {
133            map.insert(common, common);
134        }
135        map
136    });
137    map.get(s).copied()
138}
139
140pub struct PooledItem<T> {
141    item: Option<T>,
142    pool: Arc<Mutex<SmallVec<[T; 64]>>>,
143    reset_fn: fn(&mut T),
144    max_size: usize,
145}
146
147impl<T> std::ops::Deref for PooledItem<T> {
148    type Target = T;
149
150    #[inline]
151    fn deref(&self) -> &Self::Target {
152        unsafe { self.item.as_ref().unwrap_unchecked() }
153    }
154}
155
156impl<T> std::ops::DerefMut for PooledItem<T> {
157    #[inline]
158    fn deref_mut(&mut self) -> &mut Self::Target {
159        unsafe { self.item.as_mut().unwrap_unchecked() }
160    }
161}
162
163impl<T> Drop for PooledItem<T> {
164    fn drop(&mut self) {
165        if let Some(mut item) = self.item.take() {
166            (self.reset_fn)(&mut item);
167            let mut pool = self.pool.lock();
168            if pool.len() < self.max_size {
169                pool.push(item);
170            }
171        }
172    }
173}
174
175#[cfg(target_arch = "x86_64")]
176use std::arch::x86_64::*;
177
178#[allow(dead_code)]
179pub struct FastStringBuilder {
180    buffer: BytesMut,
181}
182
183#[allow(dead_code)]
184impl FastStringBuilder {
185    #[inline]
186    pub fn with_capacity(capacity: usize) -> Self {
187        Self {
188            buffer: BytesMut::with_capacity(capacity),
189        }
190    }
191
192    #[inline]
193    pub fn push_str(&mut self, s: &str) {
194        self.buffer.extend_from_slice(s.as_bytes());
195    }
196
197    #[inline]
198    pub fn push_static(&mut self, s: &'static str) {
199        self.buffer.extend_from_slice(s.as_bytes());
200    }
201
202    #[inline]
203    pub fn push_bytes(&mut self, bytes: &[u8]) {
204        self.buffer.extend_from_slice(bytes);
205    }
206
207    #[inline]
208    pub fn push_char(&mut self, c: char) {
209        let mut buf = [0; 4];
210        let s = c.encode_utf8(&mut buf);
211        self.buffer.extend_from_slice(s.as_bytes());
212    }
213
214    #[inline]
215    pub fn len(&self) -> usize {
216        self.buffer.len()
217    }
218
219    #[inline]
220    pub fn is_empty(&self) -> bool {
221        self.buffer.is_empty()
222    }
223
224    #[inline]
225    pub fn clear(&mut self) {
226        self.buffer.clear();
227    }
228
229    #[inline]
230    pub fn finish(self) -> BytesMut {
231        self.buffer
232    }
233
234    #[inline]
235    pub fn as_bytes(&self) -> &[u8] {
236        &self.buffer
237    }
238
239    #[inline]
240    pub fn reserve(&mut self, additional: usize) {
241        self.buffer.reserve(additional);
242    }
243
244    #[cfg(target_arch = "x86_64")]
245    #[target_feature(enable = "avx2")]
246    #[allow(dead_code)]
247    unsafe fn simd_copy_aligned(src: &[u8], dst: &mut [u8]) {
248        if src.len() >= 32 && dst.len() >= 32 {
249            let chunks = src.len() / 32;
250            for i in 0..chunks {
251                let src_ptr = src.as_ptr().add(i * 32);
252                let dst_ptr = dst.as_mut_ptr().add(i * 32);
253                let data = _mm256_loadu_si256(src_ptr as *const __m256i);
254                _mm256_storeu_si256(dst_ptr as *mut __m256i, data);
255            }
256
257            let remainder = src.len() % 32;
258            if remainder > 0 {
259                let start = chunks * 32;
260                dst[start..start + remainder].copy_from_slice(&src[start..start + remainder]);
261            }
262        } else {
263            dst[..src.len()].copy_from_slice(src);
264        }
265    }
266
267    #[inline]
268    #[allow(dead_code)]
269    pub fn fast_bulk_copy(&mut self, sources: &[&[u8]]) {
270        let total_len: usize = sources.iter().map(|s| s.len()).sum();
271        self.reserve(total_len);
272
273        #[cfg(target_arch = "x86_64")]
274        {
275            if is_x86_feature_detected!("avx2") && total_len >= 128 {
276                for &src in sources {
277                    if src.len() >= 32 {
278                        let remaining_capacity = self.buffer.capacity() - self.buffer.len();
279                        if remaining_capacity >= src.len() {
280                            let dst_start = self.buffer.len();
281                            self.buffer.resize(dst_start + src.len(), 0);
282                            let dst_slice = &mut self.buffer[dst_start..dst_start + src.len()];
283                            unsafe {
284                                Self::simd_copy_aligned(src, dst_slice);
285                            }
286                            continue;
287                        }
288                    }
289                    self.buffer.extend_from_slice(src);
290                }
291                return;
292            }
293        }
294
295        for &src in sources {
296            self.buffer.extend_from_slice(src);
297        }
298    }
299}
300
301impl Default for FastStringBuilder {
302    #[inline]
303    fn default() -> Self {
304        Self::with_capacity(1024)
305    }
306}
307
308#[derive(Debug, Clone)]
309pub struct CompactString {
310    data: SmallVec<[u8; 24]>,
311}
312
313#[allow(dead_code)]
314impl CompactString {
315    #[inline]
316    pub fn new() -> Self {
317        Self {
318            data: SmallVec::new(),
319        }
320    }
321
322    #[inline]
323    pub fn from_str(s: &str) -> Self {
324        let mut data = SmallVec::new();
325        data.extend_from_slice(s.as_bytes());
326        Self { data }
327    }
328
329    #[inline]
330    pub fn from_static(s: &'static str) -> Self {
331        Self::from_str(s)
332    }
333
334    #[inline]
335    pub fn as_str(&self) -> &str {
336        unsafe { std::str::from_utf8_unchecked(&self.data) }
337    }
338
339    #[inline]
340    pub fn len(&self) -> usize {
341        self.data.len()
342    }
343
344    #[inline]
345    pub fn is_empty(&self) -> bool {
346        self.data.is_empty()
347    }
348
349    #[inline]
350    pub fn capacity(&self) -> usize {
351        self.data.capacity()
352    }
353
354    #[inline]
355    pub fn push_str(&mut self, s: &str) {
356        self.data.extend_from_slice(s.as_bytes());
357    }
358
359    #[inline]
360    pub fn clear(&mut self) {
361        self.data.clear();
362    }
363
364    #[inline]
365    pub fn is_inline(&self) -> bool {
366        self.data.spilled()
367    }
368}
369
370impl Default for CompactString {
371    #[inline]
372    fn default() -> Self {
373        Self::new()
374    }
375}
376
377impl std::fmt::Display for CompactString {
378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379        f.write_str(self.as_str())
380    }
381}
382
383impl PartialEq<str> for CompactString {
384    #[inline]
385    fn eq(&self, other: &str) -> bool {
386        self.as_str() == other
387    }
388}
389
390impl PartialEq<&str> for CompactString {
391    #[inline]
392    fn eq(&self, other: &&str) -> bool {
393        self.as_str() == *other
394    }
395}
396
397impl PartialEq for CompactString {
398    #[inline]
399    fn eq(&self, other: &Self) -> bool {
400        self.data == other.data
401    }
402}
403
404impl Eq for CompactString {}
405
406impl std::hash::Hash for CompactString {
407    #[inline]
408    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
409        self.data.hash(state);
410    }
411}
412
413#[inline]
414pub fn fast_string_compare(a: &str, b: &str) -> bool {
415    if a.len() != b.len() {
416        return false;
417    }
418
419    let a_bytes = a.as_bytes();
420    let b_bytes = b.as_bytes();
421
422    #[cfg(target_arch = "x86_64")]
423    {
424        if a_bytes.len() >= 32 && is_x86_feature_detected!("avx2") {
425            return unsafe { simd_string_compare_avx2(a_bytes, b_bytes) };
426        }
427    }
428
429    a_bytes == b_bytes
430}
431
432#[cfg(target_arch = "x86_64")]
433#[target_feature(enable = "avx2")]
434unsafe fn simd_string_compare_avx2(a: &[u8], b: &[u8]) -> bool {
435    let len = a.len();
436    let chunks = len / 32;
437
438    for i in 0..chunks {
439        let a_ptr = a.as_ptr().add(i * 32);
440        let b_ptr = b.as_ptr().add(i * 32);
441
442        let a_vec = _mm256_loadu_si256(a_ptr as *const __m256i);
443        let b_vec = _mm256_loadu_si256(b_ptr as *const __m256i);
444
445        let cmp = _mm256_cmpeq_epi8(a_vec, b_vec);
446        let mask = _mm256_movemask_epi8(cmp);
447
448        if mask != -1 {
449            return false;
450        }
451    }
452
453    let remainder = len % 32;
454    if remainder > 0 {
455        let start = chunks * 32;
456        return a[start..].eq(&b[start..]);
457    }
458
459    true
460}
461
462pub struct AtomicCounter {
463    value: AtomicUsize,
464}
465
466impl AtomicCounter {
467    #[inline]
468    pub const fn new(initial: usize) -> Self {
469        Self {
470            value: AtomicUsize::new(initial),
471        }
472    }
473
474    #[inline]
475    pub fn get(&self) -> usize {
476        self.value.load(Ordering::Relaxed)
477    }
478}
479
480impl Default for AtomicCounter {
481    #[inline]
482    fn default() -> Self {
483        Self::new(0)
484    }
485}
486
487impl std::fmt::Debug for AtomicCounter {
488    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
489        f.debug_struct("AtomicCounter")
490            .field("value", &self.get())
491            .finish()
492    }
493}