1use std::{collections::HashSet, rc::Rc};
6
7use rquickjs::{
8 atom::PredefinedAtom, function::This, qjs, Ctx, Exception, Function, Object, Result, Type,
9 Value,
10};
11
12use crate::json::escape::escape_json_string;
13
14const CIRCULAR_REF_DETECTION_DEPTH: usize = 20;
15
16struct StringifyContext<'a, 'js> {
17 ctx: &'a Ctx<'js>,
18 result: &'a mut String,
19 value: &'a Value<'js>,
20 depth: usize,
21 indentation: Option<&'a str>,
22 key: Option<&'a str>,
23 index: Option<usize>,
24 parent: Option<&'a Object<'js>>,
25 ancestors: &'a mut Vec<(usize, Rc<str>)>,
26 replacer_fn: Option<&'a Function<'js>>,
27 include_keys_replacer: Option<&'a HashSet<String>>,
28 itoa_buffer: &'a mut itoa::Buffer,
29 ryu_buffer: &'a mut ryu::Buffer,
30}
31
32#[allow(dead_code)]
33pub fn json_stringify<'js>(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Option<String>> {
34 json_stringify_replacer_space(ctx, value, None, None)
35}
36
37#[allow(dead_code)]
38pub fn json_stringify_replacer<'js>(
39 ctx: &Ctx<'js>,
40 value: Value<'js>,
41 replacer: Option<Value<'js>>,
42) -> Result<Option<String>> {
43 json_stringify_replacer_space(ctx, value, replacer, None)
44}
45
46pub fn json_stringify_replacer_space<'js>(
47 ctx: &Ctx<'js>,
48 value: Value<'js>,
49 replacer: Option<Value<'js>>,
50 indentation: Option<String>,
51) -> Result<Option<String>> {
52 let mut result = String::with_capacity(128);
53 let mut replacer_fn = None;
54 let mut include_keys_replacer = None;
55
56 let tmp_function;
57
58 let mut itoa_buffer = itoa::Buffer::new();
59 let mut ryu_buffer = ryu::Buffer::new();
60
61 if let Some(replacer) = replacer {
62 if let Some(function) = replacer.as_function() {
63 tmp_function = function.clone();
64 replacer_fn = Some(&tmp_function);
65 } else if let Some(array) = replacer.as_array() {
66 let mut filter = HashSet::with_capacity(array.len());
67 for value in array.clone().into_iter() {
68 let value = value?;
69 if let Some(string) = value.as_string() {
70 filter.insert(string.to_string()?);
71 } else if let Some(number) = value.as_int() {
72 filter.insert(itoa_buffer.format(number).to_string());
73 } else if let Some(number) = value.as_float() {
74 filter.insert(ryu_buffer.format(number).to_string());
75 }
76 }
77 include_keys_replacer = Some(filter);
78 }
79 }
80
81 let indentation = indentation.as_deref();
82 let include_keys_replacer = include_keys_replacer.as_ref();
83
84 let mut ancestors = Vec::with_capacity(10);
85
86 let mut context = StringifyContext {
87 ctx,
88 result: &mut result,
89 value: &value,
90 depth: 0,
91 indentation: None,
92 key: None,
93 index: None,
94 parent: None,
95 ancestors: &mut ancestors,
96 replacer_fn,
97 include_keys_replacer,
98 itoa_buffer: &mut itoa_buffer,
99 ryu_buffer: &mut ryu_buffer,
100 };
101
102 match write_primitive(&mut context, false)? {
103 PrimitiveStatus::Written => {
104 return Ok(Some(result));
105 }
106 PrimitiveStatus::Ignored => {
107 return Ok(None);
108 }
109 _ => {}
110 }
111
112 context.depth += 1;
113 context.indentation = indentation;
114 iterate(&mut context, None)?;
115 Ok(Some(result))
116}
117
118#[inline(always)]
119#[cold]
120fn write_indentation(result: &mut String, indentation: Option<&str>, depth: usize) {
121 if let Some(indentation) = indentation {
122 result.push('\n');
123 result.push_str(&indentation.repeat(depth - 1));
124 }
125}
126
127#[inline(always)]
128#[cold]
129fn run_to_json<'js>(
130 context: &mut StringifyContext<'_, 'js>,
131 js_object: &Object<'js>,
132) -> Result<()> {
133 let to_json = js_object.get::<_, Function>(PredefinedAtom::ToJSON)?;
134 let val: Value = to_json.call((This(js_object.clone()),))?;
135
136 let indentation = context.indentation.and_then(|indentation| {
138 matches!(
139 val.type_of(),
140 Type::Object | Type::Array | Type::Exception | Type::Proxy
141 )
142 .then_some(indentation)
143 });
144
145 append_value(
146 &mut StringifyContext {
147 ctx: context.ctx,
148 result: context.result,
149 value: &val,
150 depth: context.depth,
151 indentation,
152 key: None,
153 index: None,
154 parent: Some(js_object),
155 ancestors: context.ancestors,
156 replacer_fn: context.replacer_fn,
157 include_keys_replacer: context.include_keys_replacer,
158 itoa_buffer: context.itoa_buffer,
159 ryu_buffer: context.ryu_buffer,
160 },
161 false,
162 )?;
163 Ok(())
164}
165
166#[derive(PartialEq)]
167enum PrimitiveStatus<'js> {
168 Written,
169 Ignored,
170 Iterate(Option<Value<'js>>),
171}
172
173#[inline(always)]
174#[cold]
175fn run_replacer<'js>(
176 context: &mut StringifyContext<'_, 'js>,
177 replacer_fn: &Function<'js>,
178 add_comma: bool,
179) -> Result<PrimitiveStatus<'js>> {
180 let key = context.key;
181 let index = context.index;
182 let value = context.value;
183 let parent = if let Some(parent) = context.parent {
184 parent.clone()
185 } else {
186 let parent = Object::new(context.ctx.clone())?;
187 parent.set("", value.clone())?;
188 parent
189 };
190 let new_value: Value = replacer_fn.call((
191 This(parent),
192 get_key_or_index(context.itoa_buffer, key, index),
193 value,
194 ))?;
195
196 write_primitive2(context, add_comma, Some(new_value))
197}
198
199fn write_primitive<'js>(
200 context: &mut StringifyContext<'_, 'js>,
201 add_comma: bool,
202) -> Result<PrimitiveStatus<'js>> {
203 if let Some(replacer_fn) = context.replacer_fn {
204 return run_replacer(context, replacer_fn, add_comma);
205 }
206
207 write_primitive2(context, add_comma, None)
208}
209
210fn write_primitive2<'js>(
211 context: &mut StringifyContext<'_, 'js>,
212 add_comma: bool,
213 new_value: Option<Value<'js>>,
214) -> Result<PrimitiveStatus<'js>> {
215 let key = context.key;
216 let index = context.index;
217 let include_keys_replacer = context.include_keys_replacer;
218 let indentation = context.indentation;
219 let depth = context.depth;
220
221 let value = new_value.as_ref().unwrap_or(context.value);
222
223 let type_of = value.type_of();
224
225 if context.index.is_none()
226 && matches!(
227 type_of,
228 Type::Symbol | Type::Undefined | Type::Function | Type::Constructor
229 )
230 {
231 return Ok(PrimitiveStatus::Ignored);
232 }
233
234 if matches!(type_of, Type::BigInt) {
235 return Err(Exception::throw_type(
236 context.ctx,
237 "Do not know how to serialize a BigInt",
238 ));
239 }
240
241 if let Some(include_keys_replacer) = include_keys_replacer {
242 let key = get_key_or_index(context.itoa_buffer, key, index);
243 if !include_keys_replacer.contains(key) {
244 return Ok(PrimitiveStatus::Ignored);
245 }
246 };
247
248 if let Some(indentation) = indentation {
249 write_indented_separator(context.result, key, add_comma, indentation, depth);
250 } else {
251 write_sep(context.result, add_comma, false);
252 if let Some(key) = key {
253 write_key(context.result, key, false);
254 }
255 }
256
257 match type_of {
258 Type::Null | Type::Undefined => context.result.push_str("null"),
259 Type::Bool => {
260 let bool_str = if unsafe { value.as_bool().unwrap_unchecked() } {
261 "true"
262 } else {
263 "false"
264 };
265 context.result.push_str(bool_str);
266 }
267 Type::Int => context.result.push_str(
268 context
269 .itoa_buffer
270 .format(unsafe { value.as_int().unwrap_unchecked() }),
271 ),
272 Type::Float => {
273 let float_value = unsafe { value.as_float().unwrap_unchecked() };
274 const EXP_MASK: u64 = 0x7ff0000000000000;
275 let bits = float_value.to_bits();
276 if bits & EXP_MASK == EXP_MASK {
277 context.result.push_str("null");
278 } else {
279 let str = context.ryu_buffer.format_finite(float_value);
280
281 let bytes = str.as_bytes();
282 let len = bytes.len();
283
284 context.result.push_str(str);
285
286 if &bytes[len - 2..] == b".0" {
287 let len = context.result.len();
288 unsafe { context.result.as_mut_vec().set_len(len - 2) }
289 }
290 }
291 }
292 Type::String => {
293 let js_string = unsafe { value.as_string().unwrap_unchecked() }.clone();
294 write_string(context.result, js_string.to_cstring()?.as_str());
295 }
296 _ => return Ok(PrimitiveStatus::Iterate(new_value)),
297 }
298 Ok(PrimitiveStatus::Written)
299}
300
301#[inline(always)]
302#[cold]
303fn write_indented_separator(
304 result: &mut String,
305 key: Option<&str>,
306 add_comma: bool,
307 indentation: &str,
308 depth: usize,
309) {
310 write_sep(result, add_comma, true);
311 result.push_str(&indentation.repeat(depth));
312 if let Some(key) = key {
313 write_key(result, key, true);
314 }
315}
316
317#[cold]
318fn detect_circular_reference(
319 ctx: &Ctx<'_>,
320 value: &Object<'_>,
321 key: Option<&str>,
322 index: Option<usize>,
323 parent: Option<&Object<'_>>,
324 ancestors: &mut Vec<(usize, Rc<str>)>,
325 itoa_buffer: &mut itoa::Buffer,
326) -> Result<()> {
327 let parent_ptr = unsafe { qjs::JS_VALUE_GET_PTR(parent.unwrap_unchecked().as_raw()) as usize };
328 let current_ptr = unsafe { qjs::JS_VALUE_GET_PTR(value.as_raw()) as usize };
329
330 while !ancestors.is_empty()
331 && match ancestors.last() {
332 Some((ptr, _)) => ptr != &parent_ptr,
333 _ => false,
334 }
335 {
336 ancestors.pop();
337 }
338
339 if ancestors.iter().any(|(ptr, _)| ptr == ¤t_ptr) {
340 let mut iter = ancestors.iter_mut();
341
342 let first = &unsafe { iter.next().unwrap_unchecked() }.1;
343
344 let mut message = iter.rev().take(4).rev().fold(
345 String::from("Circular reference detected at: \".."),
346 |mut acc, (_, key)| {
347 if !key.starts_with('[') {
348 acc.push('.');
349 }
350 acc.push_str(key);
351 acc
352 },
353 );
354
355 if !first.starts_with('[') {
356 message.push('.');
357 }
358
359 message.push_str(first);
360 message.push('"');
361
362 return Err(Exception::throw_type(ctx, &message));
363 }
364 ancestors.push((
365 current_ptr,
366 key.map(|k| k.into()).unwrap_or_else(|| {
367 ["[", itoa_buffer.format(index.unwrap_or_default()), "]"]
368 .concat()
369 .into()
370 }),
371 ));
372
373 Ok(())
374}
375
376#[inline(always)]
377fn append_value(context: &mut StringifyContext<'_, '_>, add_comma: bool) -> Result<bool> {
378 match write_primitive(context, add_comma)? {
379 PrimitiveStatus::Written => Ok(true),
380 PrimitiveStatus::Ignored => Ok(false),
381 PrimitiveStatus::Iterate(new_value) => {
382 context.depth += 1;
383 iterate(context, new_value)?;
384 Ok(true)
385 }
386 }
387}
388
389#[inline(always)]
390fn write_key(string: &mut String, key: &str, indent: bool) {
391 string.push('"');
392 escape_json_string(string, key.as_bytes());
393 string.push_str("\":");
394 if indent {
395 string.push(' ');
396 }
397}
398
399#[inline(always)]
400fn write_sep(result: &mut String, add_comma: bool, has_indentation: bool) {
401 if add_comma {
402 result.push(',');
403 }
404 if has_indentation {
405 result.push('\n');
406 }
407}
408
409#[inline(always)]
410fn write_string(string: &mut String, value: &str) {
411 string.push('"');
412 escape_json_string(string, value.as_bytes());
413 string.push('"');
414}
415
416#[inline(always)]
417fn get_key_or_index<'a>(
418 itoa_buffer: &'a mut itoa::Buffer,
419 key: Option<&'a str>,
420 index: Option<usize>,
421) -> &'a str {
422 key.unwrap_or_else(|| itoa_buffer.format(index.unwrap_or_default()))
423}
424
425fn iterate<'js>(
426 context: &mut StringifyContext<'_, 'js>,
427 new_value: Option<Value<'js>>,
428) -> Result<()> {
429 let mut add_comma;
430 let mut value_written;
431 let elem = new_value.as_ref().unwrap_or(context.value);
432 let depth = context.depth;
433 let ctx = context.ctx;
434 let indentation = context.indentation;
435 match elem.type_of() {
436 Type::Object | Type::Exception | Type::Proxy => {
437 let js_object = unsafe { elem.as_object().unwrap_unchecked() };
438 if js_object.contains_key(PredefinedAtom::ToJSON)? {
439 return run_to_json(context, js_object);
440 }
441
442 if depth > CIRCULAR_REF_DETECTION_DEPTH {
444 detect_circular_reference(
445 ctx,
446 js_object,
447 context.key,
448 context.index,
449 context.parent,
450 context.ancestors,
451 context.itoa_buffer,
452 )?;
453 }
454
455 context.result.push('{');
456
457 value_written = false;
458
459 let keys: Vec<String> = {
462 let collected: Vec<String> = js_object.keys::<String>().flatten().collect();
463 if collected.is_empty() {
464 ctx.catch();
466 ctx.globals()
467 .get::<_, Object>("Object")
468 .ok()
469 .and_then(|o| o.get::<_, Function>("keys").ok())
470 .and_then(|f| f.call::<_, Vec<String>>((js_object.clone(),)).ok())
471 .unwrap_or_default()
472 } else {
473 collected
474 }
475 };
476
477 for key in keys {
478 let val = js_object.get(&key)?;
479
480 add_comma = append_value(
481 &mut StringifyContext {
482 ctx,
483 result: context.result,
484 value: &val,
485 depth,
486 key: Some(&key),
487 indentation,
488 index: None,
489 parent: Some(js_object),
490 ancestors: context.ancestors,
491 replacer_fn: context.replacer_fn,
492 include_keys_replacer: context.include_keys_replacer,
493 itoa_buffer: context.itoa_buffer,
494 ryu_buffer: context.ryu_buffer,
495 },
496 value_written,
497 )?;
498 value_written = value_written || add_comma;
499 }
500
501 if value_written {
502 write_indentation(context.result, indentation, depth);
503 }
504 context.result.push('}');
505 }
506 Type::Array => {
507 context.result.push('[');
508 add_comma = false;
509 value_written = false;
510 let js_array = unsafe { elem.as_array().unwrap_unchecked() };
511 if depth > CIRCULAR_REF_DETECTION_DEPTH {
513 detect_circular_reference(
514 ctx,
515 js_array.as_object(),
516 context.key,
517 context.index,
518 context.parent,
519 context.ancestors,
520 context.itoa_buffer,
521 )?;
522 }
523 for (i, val) in js_array.iter::<Value>().enumerate() {
524 let val = val?;
525 add_comma = append_value(
526 &mut StringifyContext {
527 ctx,
528 result: context.result,
529 value: &val,
530 depth,
531 key: None,
532 indentation,
533 index: Some(i),
534 parent: Some(js_array),
535 ancestors: context.ancestors,
536 replacer_fn: context.replacer_fn,
537 include_keys_replacer: context.include_keys_replacer,
538 itoa_buffer: context.itoa_buffer,
539 ryu_buffer: context.ryu_buffer,
540 },
541 add_comma,
542 )?;
543 value_written = value_written || add_comma;
544 }
545 if value_written {
546 write_indentation(context.result, indentation, depth);
547 }
548 context.result.push(']');
549 }
550 _ => {}
551 }
552 Ok(())
553}