JsMap.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 JsMap : ObjectInstance
  7. {
  8. private readonly Realm _realm;
  9. internal readonly OrderedDictionary<JsValue, JsValue> _map;
  10. public JsMap(Engine engine, Realm realm) : base(engine)
  11. {
  12. _realm = realm;
  13. _map = new OrderedDictionary<JsValue, JsValue>(SameValueZeroComparer.Instance);
  14. }
  15. public override PropertyDescriptor GetOwnProperty(JsValue property)
  16. {
  17. if (CommonProperties.Size.Equals(property))
  18. {
  19. return new PropertyDescriptor(_map.Count, PropertyFlag.AllForbidden);
  20. }
  21. return base.GetOwnProperty(property);
  22. }
  23. protected override bool TryGetProperty(JsValue property, [NotNullWhen(true)] out PropertyDescriptor? descriptor)
  24. {
  25. if (CommonProperties.Size.Equals(property))
  26. {
  27. descriptor = new PropertyDescriptor(_map.Count, PropertyFlag.AllForbidden);
  28. return true;
  29. }
  30. return base.TryGetProperty(property, out descriptor);
  31. }
  32. internal void Clear()
  33. {
  34. _map.Clear();
  35. }
  36. internal bool Has(JsValue key)
  37. {
  38. return _map.ContainsKey(key);
  39. }
  40. internal bool MapDelete(JsValue key)
  41. {
  42. return _map.Remove(key);
  43. }
  44. internal void MapSet(JsValue key, JsValue value)
  45. {
  46. if (key is JsNumber number && number.IsNegativeZero())
  47. {
  48. key = JsNumber.PositiveZero;
  49. }
  50. _map[key] = value;
  51. }
  52. internal void ForEach(ICallable callable, JsValue thisArg)
  53. {
  54. var args = _engine._jsValueArrayPool.RentArray(3);
  55. args[2] = this;
  56. for (var i = 0; i < _map.Count; i++)
  57. {
  58. args[0] = _map[i];
  59. args[1] = _map.GetKey(i);
  60. callable.Call(thisArg, args);
  61. }
  62. _engine._jsValueArrayPool.ReturnArray(args);
  63. }
  64. internal JsValue MapGet(JsValue key)
  65. {
  66. if (!_map.TryGetValue(key, out var value))
  67. {
  68. return Undefined;
  69. }
  70. return value;
  71. }
  72. internal ObjectInstance Iterator()
  73. {
  74. return _realm.Intrinsics.MapIteratorPrototype.ConstructEntryIterator(this);
  75. }
  76. internal ObjectInstance Keys()
  77. {
  78. return _realm.Intrinsics.MapIteratorPrototype.ConstructKeyIterator(this);
  79. }
  80. internal ObjectInstance Values()
  81. {
  82. return _realm.Intrinsics.MapIteratorPrototype.ConstructValueIterator(this);
  83. }
  84. }