AtomicsInstance.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Numerics;
  2. using System.Threading;
  3. using Jint.Collections;
  4. using Jint.Native.Object;
  5. using Jint.Runtime;
  6. using Jint.Runtime.Descriptors;
  7. using Jint.Runtime.Interop;
  8. namespace Jint.Native.Atomics;
  9. /// <summary>
  10. /// https://tc39.es/ecma262/#sec-atomics-object
  11. /// </summary>
  12. internal sealed class AtomicsInstance : ObjectInstance
  13. {
  14. private readonly Realm _realm;
  15. public AtomicsInstance(
  16. Engine engine,
  17. Realm realm,
  18. ObjectPrototype objectPrototype) : base(engine)
  19. {
  20. _realm = realm;
  21. _prototype = objectPrototype;
  22. }
  23. protected override void Initialize()
  24. {
  25. var properties = new PropertyDictionary(1, checkExistingKeys: false)
  26. {
  27. ["pause"] = new(new ClrFunction(Engine, "pause", Pause, 0, PropertyFlag.Configurable), true, false, true),
  28. };
  29. SetProperties(properties);
  30. }
  31. private JsValue Pause(JsValue thisObject, JsValue[] arguments)
  32. {
  33. var iterationNumber = arguments.At(0);
  34. if (!iterationNumber.IsUndefined())
  35. {
  36. if (!iterationNumber.IsNumber())
  37. {
  38. ExceptionHelper.ThrowTypeError(_realm, "Invalid iteration count");
  39. }
  40. var n = TypeConverter.ToNumber(iterationNumber);
  41. if (!TypeConverter.IsIntegralNumber(n))
  42. {
  43. ExceptionHelper.ThrowTypeError(_realm, "Invalid iteration count");
  44. }
  45. if (n < 0)
  46. {
  47. ExceptionHelper.ThrowRangeError(_realm, "Invalid iteration count");
  48. }
  49. Thread.SpinWait((int) n);
  50. }
  51. else
  52. {
  53. Thread.SpinWait(1);
  54. }
  55. return Undefined;
  56. }
  57. }