Skip to main content

rquickjs_core/value/
atom.rs

1//!  QuickJS atom functionality.
2
3use crate::{qjs, Ctx, Error, Result, String, Value};
4use alloc::string::String as StdString;
5use core::hash::Hash;
6
7mod predefined;
8pub use predefined::PredefinedAtom;
9
10/// A QuickJS Atom.
11///
12/// In QuickJS atoms are similar to interned string but with additional uses.
13/// A symbol for instance is just an atom.
14///
15/// # Representation
16///
17/// Atoms in QuickJS are handled differently depending on what type of index the represent.
18/// When the atom represents a number like index, like `object[1]` the atom is just
19/// a normal number.
20/// However when the atom represents a string link index like `object["foo"]` or `object.foo`
21/// the atom represents a value in a hashmap.
22#[derive(Debug)]
23pub struct Atom<'js> {
24    pub(crate) atom: qjs::JSAtom,
25    pub(crate) ctx: Ctx<'js>,
26}
27
28impl<'js> PartialEq for Atom<'js> {
29    fn eq(&self, other: &Self) -> bool {
30        self.atom == other.atom
31    }
32}
33impl<'js> Eq for Atom<'js> {}
34
35impl<'js> Hash for Atom<'js> {
36    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
37        state.write_u32(self.atom)
38    }
39}
40
41impl<'js> Atom<'js> {
42    /// Create an atom from a JavaScript value.
43    pub fn from_value(ctx: Ctx<'js>, val: &Value<'js>) -> Result<Atom<'js>> {
44        let atom = unsafe { qjs::JS_ValueToAtom(ctx.as_ptr(), val.as_js_value()) };
45        if atom == qjs::JS_ATOM_NULL {
46            // A value can be anything, including an object which might contain a callback so check
47            // for panics.
48            return Err(ctx.raise_exception());
49        }
50        Ok(Atom { atom, ctx })
51    }
52
53    /// Create an atom from a `u32`
54    pub fn from_u32(ctx: Ctx<'js>, val: u32) -> Result<Atom<'js>> {
55        let atom = unsafe { qjs::JS_NewAtomUInt32(ctx.as_ptr(), val) };
56        if atom == qjs::JS_ATOM_NULL {
57            // Should never invoke a callback so no panics
58            return Err(Error::Exception);
59        }
60        Ok(Atom { atom, ctx })
61    }
62
63    /// Create an atom from an `i32` via value
64    pub fn from_i32(ctx: Ctx<'js>, val: i32) -> Result<Atom<'js>> {
65        let atom =
66            unsafe { qjs::JS_ValueToAtom(ctx.as_ptr(), qjs::JS_MKVAL(qjs::JS_TAG_INT, val)) };
67        if atom == qjs::JS_ATOM_NULL {
68            // Should never invoke a callback so no panics
69            return Err(Error::Exception);
70        }
71        Ok(Atom { atom, ctx })
72    }
73
74    /// Create an atom from a `bool` via value
75    pub fn from_bool(ctx: Ctx<'js>, val: bool) -> Result<Atom<'js>> {
76        let val = if val { qjs::JS_TRUE } else { qjs::JS_FALSE };
77        let atom = unsafe { qjs::JS_ValueToAtom(ctx.as_ptr(), val) };
78        if atom == qjs::JS_ATOM_NULL {
79            // Should never invoke a callback so no panics
80            return Err(Error::Exception);
81        }
82        Ok(Atom { atom, ctx })
83    }
84
85    /// Create an atom from a `f64` via value
86    pub fn from_f64(ctx: Ctx<'js>, val: f64) -> Result<Atom<'js>> {
87        let atom = unsafe { qjs::JS_ValueToAtom(ctx.as_ptr(), qjs::JS_NewFloat64(val)) };
88        if atom == qjs::JS_ATOM_NULL {
89            // Should never invoke a callback so no panics
90            return Err(Error::Exception);
91        }
92        Ok(Atom { atom, ctx })
93    }
94
95    /// Create an atom from a Rust string
96    pub fn from_str(ctx: Ctx<'js>, name: &str) -> Result<Atom<'js>> {
97        unsafe {
98            let ptr = name.as_ptr() as *const core::ffi::c_char;
99            let atom = qjs::JS_NewAtomLen(ctx.as_ptr(), ptr, name.len() as _);
100            if atom == qjs::JS_ATOM_NULL {
101                // Should never invoke a callback so no panics
102                return Err(Error::Exception);
103            }
104            Ok(Atom { atom, ctx })
105        }
106    }
107
108    /// Create an atom from a predefined atom.
109    pub fn from_predefined(ctx: Ctx<'js>, predefined: PredefinedAtom) -> Atom<'js> {
110        unsafe { Atom::from_atom_val(ctx, predefined as qjs::JSAtom) }
111    }
112
113    /// Convert the atom to a Rust string.
114    pub fn to_string(&self) -> Result<StdString> {
115        self.to_js_string()?.to_string()
116    }
117
118    /// Convert the atom to a Rust string, replacing invalid UTF-8 sequences
119    /// with the Unicode replacement character (`U+FFFD`).
120    pub fn to_string_lossy(&self) -> Result<StdString> {
121        self.to_js_string()?.to_string_lossy()
122    }
123
124    /// Convert the atom to a JavaScript string.
125    pub fn to_js_string(&self) -> Result<String<'js>> {
126        unsafe {
127            let val = qjs::JS_AtomToString(self.ctx.as_ptr(), self.atom);
128            let val = self.ctx.handle_exception(val)?;
129            Ok(String::from_js_value(self.ctx.clone(), val))
130        }
131    }
132
133    /// Convert the atom to a JavaScript value, which will be either a [String] or a [Symbol][crate::Symbol].
134    pub fn to_value(&self) -> Result<Value<'js>> {
135        unsafe {
136            let val = qjs::JS_AtomToValue(self.ctx.as_ptr(), self.atom);
137            let val = self.ctx.handle_exception(val)?;
138            Ok(Value::from_js_value(self.ctx.clone(), val))
139        }
140    }
141
142    pub(crate) unsafe fn from_atom_val(ctx: Ctx<'js>, val: qjs::JSAtom) -> Self {
143        Atom { atom: val, ctx }
144    }
145
146    pub(crate) unsafe fn from_atom_val_dup(ctx: Ctx<'js>, val: qjs::JSAtom) -> Self {
147        qjs::JS_DupAtom(ctx.as_ptr(), val);
148        Atom { atom: val, ctx }
149    }
150}
151
152impl<'js> Clone for Atom<'js> {
153    fn clone(&self) -> Atom<'js> {
154        let atom = unsafe { qjs::JS_DupAtom(self.ctx.as_ptr(), self.atom) };
155        Atom {
156            atom,
157            ctx: self.ctx.clone(),
158        }
159    }
160}
161
162impl<'js> Drop for Atom<'js> {
163    fn drop(&mut self) {
164        unsafe {
165            qjs::JS_FreeAtom(self.ctx.as_ptr(), self.atom);
166        }
167    }
168}
169
170#[cfg(test)]
171mod test {
172    use crate::*;
173    #[test]
174    fn to_string() {
175        test_with(|ctx| {
176            for text in ["", "hello", "hello\0😀"] {
177                let atom = Atom::from_str(ctx.clone(), text).unwrap();
178                assert_eq!(atom.to_string().unwrap(), text);
179            }
180            let atom = Atom::from_u32(ctx.clone(), 123).unwrap();
181            assert_eq!(atom.to_string().unwrap(), "123");
182
183            for source in [r#""\ud800""#, r#""\udfff""#] {
184                let value: Value = ctx.eval(source).unwrap();
185                let atom = Atom::from_value(ctx.clone(), &value).unwrap();
186                assert!(matches!(atom.to_string(), Err(Error::Utf8(_))));
187            }
188        });
189    }
190
191    #[test]
192    fn to_string_lossy() {
193        test_with(|ctx| {
194            for text in ["", "hello", "hello\0😀"] {
195                let atom = Atom::from_str(ctx.clone(), text).unwrap();
196                assert_eq!(atom.to_string_lossy().unwrap(), text);
197            }
198            let atom = Atom::from_u32(ctx.clone(), 123).unwrap();
199            assert_eq!(atom.to_string_lossy().unwrap(), "123");
200
201            for source in [r#""\ud800""#, r#""\udfff""#] {
202                let value: Value = ctx.eval(source).unwrap();
203                let atom = Atom::from_value(ctx.clone(), &value).unwrap();
204                assert_eq!(atom.to_string_lossy().unwrap(), "���");
205            }
206        });
207    }
208
209    #[test]
210    fn to_value() {
211        test_with(|ctx| {
212            let local_symbol = Symbol::new(ctx.clone()).unwrap();
213            for (atom, expected) in [
214                (
215                    Atom::from_bool(ctx.clone(), false).unwrap(),
216                    String::from_str(ctx.clone(), "false").unwrap().into(),
217                ),
218                (
219                    Atom::from_u32(ctx.clone(), 123).unwrap(),
220                    String::from_str(ctx.clone(), "123").unwrap().into(),
221                ),
222                (
223                    Atom::from_f64(ctx.clone(), 123.4).unwrap(),
224                    String::from_str(ctx.clone(), "123.4").unwrap().into(),
225                ),
226                (
227                    Atom::from_predefined(ctx.clone(), atom::PredefinedAtom::New),
228                    String::from_str(ctx.clone(), "new").unwrap().into(),
229                ),
230                (
231                    Atom::from_predefined(ctx.clone(), atom::PredefinedAtom::SymbolToStringTag),
232                    ctx.eval("Symbol.toStringTag").unwrap(),
233                ),
234                (
235                    Atom::from_value(ctx.clone(), &local_symbol).unwrap(),
236                    local_symbol.into(),
237                ),
238            ] {
239                let to_value = atom.to_value().unwrap();
240                assert!(
241                    to_value.strict_eq(&expected),
242                    "{to_value:?} != {expected:?}",
243                );
244            }
245        });
246    }
247}