MCPcopy Create free account
hub / github.com/awslabs/llrt / detect_circular_reference

Function detect_circular_reference

libs/llrt_json/src/stringify.rs:316–372  ·  view source on GitHub ↗
(
    ctx: &Ctx<'_>,
    value: &Object<'_>,
    key: Option<&str>,
    index: Option<usize>,
    parent: Option<&Object<'_>>,
    ancestors: &mut Vec<(usize, Rc<str>)>,
    itoa_buffer: &mut itoa::Bu

Source from the content-addressed store, hash-verified

314
315#[cold]
316fn detect_circular_reference(
317 ctx: &Ctx<'_>,
318 value: &Object<'_>,
319 key: Option<&str>,
320 index: Option<usize>,
321 parent: Option<&Object<'_>>,
322 ancestors: &mut Vec<(usize, Rc<str>)>,
323 itoa_buffer: &mut itoa::Buffer,
324) -> Result<()> {
325 let parent_ptr = unsafe { qjs::JS_VALUE_GET_PTR(parent.unwrap_unchecked().as_raw()) as usize };
326 let current_ptr = unsafe { qjs::JS_VALUE_GET_PTR(value.as_raw()) as usize };
327
328 while !ancestors.is_empty()
329 && match ancestors.last() {
330 Some((ptr, _)) => ptr != &parent_ptr,
331 _ => false,
332 }
333 {
334 ancestors.pop();
335 }
336
337 if ancestors.iter().any(|(ptr, _)| ptr == &current_ptr) {
338 let mut iter = ancestors.iter_mut();
339
340 let first = &unsafe { iter.next().unwrap_unchecked() }.1;
341
342 let mut message = iter.rev().take(4).rev().fold(
343 String::from("Circular reference detected at: \".."),
344 |mut acc, (_, key)| {
345 if !key.starts_with('[') {
346 acc.push('.');
347 }
348 acc.push_str(key);
349 acc
350 },
351 );
352
353 if !first.starts_with('[') {
354 message.push('.');
355 }
356
357 message.push_str(first);
358 message.push('"');
359
360 return Err(Exception::throw_type(ctx, &message));
361 }
362 ancestors.push((
363 current_ptr,
364 key.map(|k| k.into()).unwrap_or_else(|| {
365 ["[", itoa_buffer.format(index.unwrap_or_default()), "]"]
366 .concat()
367 .into()
368 }),
369 ));
370
371 Ok(())
372}
373

Callers 1

iterateFunction · 0.85

Calls 9

fromFunction · 0.85
anyMethod · 0.80
iter_mutMethod · 0.80
pushMethod · 0.80
concatMethod · 0.80
formatMethod · 0.65
is_emptyMethod · 0.45
iterMethod · 0.45
nextMethod · 0.45

Tested by

no test coverage detected