ObjectTraverseStack.cs 902 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using Jint.Native;
  2. using Jint.Runtime;
  3. namespace Jint.Collections;
  4. /// <summary>
  5. /// Helps traversing objects and checks for cyclic references.
  6. /// </summary>
  7. internal sealed class ObjectTraverseStack
  8. {
  9. private readonly Engine _engine;
  10. private readonly Stack<object> _stack = new();
  11. public ObjectTraverseStack(Engine engine)
  12. {
  13. _engine = engine;
  14. }
  15. public bool TryEnter(JsValue value)
  16. {
  17. if (value is null)
  18. {
  19. Throw.ArgumentNullException(nameof(value));
  20. }
  21. if (_stack.Contains(value))
  22. {
  23. return false;
  24. }
  25. _stack.Push(value);
  26. return true;
  27. }
  28. public void Enter(JsValue value)
  29. {
  30. if (!TryEnter(value))
  31. {
  32. Throw.TypeError(_engine.Realm, "Cyclic reference detected.");
  33. }
  34. }
  35. public void Exit()
  36. {
  37. _stack.Pop();
  38. }
  39. }