IteratorProtocol.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using Jint.Native.Array;
  2. namespace Jint.Native.Iterator
  3. {
  4. /// <summary>
  5. /// Handles looping of iterator values, sub-classes can use to implement wanted actions.
  6. /// </summary>
  7. internal abstract class IteratorProtocol
  8. {
  9. protected readonly Engine _engine;
  10. private readonly IIterator _iterator;
  11. private readonly int _argCount;
  12. protected IteratorProtocol(
  13. Engine engine,
  14. IIterator iterator,
  15. int argCount)
  16. {
  17. _engine = engine;
  18. _iterator = iterator;
  19. _argCount = argCount;
  20. }
  21. internal void Execute()
  22. {
  23. var args = _engine._jsValueArrayPool.RentArray(_argCount);
  24. try
  25. {
  26. do
  27. {
  28. var item = _iterator.Next();
  29. if (item.TryGetValue("done", out var done) && done.AsBoolean())
  30. {
  31. break;
  32. }
  33. if (!item.TryGetValue("value", out var currentValue))
  34. {
  35. currentValue = JsValue.Undefined;
  36. }
  37. ProcessItem(args, currentValue);
  38. } while (ShouldContinue);
  39. }
  40. catch
  41. {
  42. ReturnIterator();
  43. throw;
  44. }
  45. finally
  46. {
  47. _engine._jsValueArrayPool.ReturnArray(args);
  48. }
  49. IterationEnd();
  50. }
  51. protected void ReturnIterator()
  52. {
  53. _iterator.Return();
  54. }
  55. protected virtual bool ShouldContinue => true;
  56. protected virtual void IterationEnd()
  57. {
  58. }
  59. protected abstract void ProcessItem(JsValue[] args, JsValue currentValue);
  60. protected static JsValue ExtractValueFromIteratorInstance(JsValue jsValue)
  61. {
  62. if (jsValue is ArrayInstance ai)
  63. {
  64. uint index = 0;
  65. if (ai.GetLength() > 1)
  66. {
  67. index = 1;
  68. }
  69. ai.TryGetValue(index, out var value);
  70. return value;
  71. }
  72. return jsValue;
  73. }
  74. }
  75. }