JsSet.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Diagnostics.CodeAnalysis;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Native;
  6. internal sealed class JsSet : ObjectInstance
  7. {
  8. internal readonly OrderedSet<JsValue> _set;
  9. public JsSet(Engine engine) : this(engine, new OrderedSet<JsValue>(SameValueZeroComparer.Instance))
  10. {
  11. }
  12. public JsSet(Engine engine, OrderedSet<JsValue> set) : base(engine)
  13. {
  14. _set = set;
  15. _prototype = _engine.Realm.Intrinsics.Set.PrototypeObject;
  16. }
  17. public int Size => _set.Count;
  18. public JsValue? this[int index]
  19. {
  20. get { return index < _set._list.Count ? _set._list[index] : null; }
  21. }
  22. public override PropertyDescriptor GetOwnProperty(JsValue property)
  23. {
  24. if (CommonProperties.Size.Equals(property))
  25. {
  26. return new PropertyDescriptor(_set.Count, PropertyFlag.AllForbidden);
  27. }
  28. return base.GetOwnProperty(property);
  29. }
  30. protected override bool TryGetProperty(JsValue property, [NotNullWhen(true)] out PropertyDescriptor? descriptor)
  31. {
  32. if (CommonProperties.Size.Equals(property))
  33. {
  34. descriptor = new PropertyDescriptor(_set.Count, PropertyFlag.AllForbidden);
  35. return true;
  36. }
  37. return base.TryGetProperty(property, out descriptor);
  38. }
  39. internal void Add(JsValue value) => _set.Add(value);
  40. internal void Remove(JsValue value) => _set.Remove(value);
  41. internal void Clear() => _set.Clear();
  42. internal bool Has(JsValue key) => _set.Contains(key);
  43. internal bool SetDelete(JsValue key) => _set.Remove(key);
  44. internal void ForEach(ICallable callable, JsValue thisArg)
  45. {
  46. var args = _engine._jsValueArrayPool.RentArray(3);
  47. args[2] = this;
  48. for (var i = 0; i < _set._list.Count; i++)
  49. {
  50. var value = _set._list[i];
  51. args[0] = value;
  52. args[1] = value;
  53. callable.Call(thisArg, args);
  54. }
  55. _engine._jsValueArrayPool.ReturnArray(args);
  56. }
  57. internal ObjectInstance Entries() => _engine.Realm.Intrinsics.SetIteratorPrototype.ConstructEntryIterator(this);
  58. internal ObjectInstance Values() => _engine.Realm.Intrinsics.SetIteratorPrototype.ConstructValueIterator(this);
  59. }