| 314 | |
| 315 | #[cold] |
| 316 | fn 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 == ¤t_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 | |