swc_atoms/fast.rs
1use std::{
2 mem::{transmute_copy, ManuallyDrop},
3 ops::Deref,
4};
5
6use crate::Atom;
7
8/// UnsafeAtom is a wrapper around [Atom] that does not allocate, but extremely
9/// unsafe.
10///
11/// Do not use this unless you know what you are doing.
12///
13/// **Currently, it's considered as a unstable API and may be changed in the
14/// future without a semver bump.**
15#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct UnsafeAtom(ManuallyDrop<Atom>);
17
18impl UnsafeAtom {
19 /// # Safety
20 ///
21 /// - You should ensure that the passed `atom` is not freed.
22 ///
23 /// Some simple solutions to ensure this are
24 ///
25 /// - Collect all [Atom] and store them somewhere while you are using
26 /// [UnsafeAtom]
27 /// - Use [UnsafeAtom] only for short-lived operations where all [Atom] is
28 /// stored in AST and ensure that the AST is not dropped.
29 #[inline]
30 pub unsafe fn new(atom: &Atom) -> Self {
31 Self(ManuallyDrop::new(transmute_copy(atom)))
32 }
33}
34
35impl Deref for UnsafeAtom {
36 type Target = Atom;
37
38 #[inline]
39 fn deref(&self) -> &Self::Target {
40 &self.0
41 }
42}
43
44impl Clone for UnsafeAtom {
45 #[inline]
46 fn clone(&self) -> Self {
47 unsafe { Self::new(&self.0) }
48 }
49}
50
51impl PartialEq<Atom> for UnsafeAtom {
52 #[inline]
53 fn eq(&self, other: &Atom) -> bool {
54 *self.0 == *other
55 }
56}