1use 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#[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 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 return Err(ctx.raise_exception());
49 }
50 Ok(Atom { atom, ctx })
51 }
52
53 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 return Err(Error::Exception);
59 }
60 Ok(Atom { atom, ctx })
61 }
62
63 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 return Err(Error::Exception);
70 }
71 Ok(Atom { atom, ctx })
72 }
73
74 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 return Err(Error::Exception);
81 }
82 Ok(Atom { atom, ctx })
83 }
84
85 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 return Err(Error::Exception);
91 }
92 Ok(Atom { atom, ctx })
93 }
94
95 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 return Err(Error::Exception);
103 }
104 Ok(Atom { atom, ctx })
105 }
106 }
107
108 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 pub fn to_string(&self) -> Result<StdString> {
115 self.to_js_string()?.to_string()
116 }
117
118 pub fn to_string_lossy(&self) -> Result<StdString> {
121 self.to_js_string()?.to_string_lossy()
122 }
123
124 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 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}