MapInstance.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Native.Map
  6. {
  7. public class MapInstance : ObjectInstance
  8. {
  9. private readonly Realm _realm;
  10. internal readonly OrderedDictionary<JsValue, JsValue> _map;
  11. public MapInstance(Engine engine, Realm realm)
  12. : base(engine, objectClass: ObjectClass.Map)
  13. {
  14. _realm = realm;
  15. _map = new OrderedDictionary<JsValue, JsValue>();
  16. }
  17. public override PropertyDescriptor GetOwnProperty(JsValue property)
  18. {
  19. if (property == CommonProperties.Size)
  20. {
  21. return new PropertyDescriptor(_map.Count, PropertyFlag.None);
  22. }
  23. return base.GetOwnProperty(property);
  24. }
  25. protected override bool TryGetProperty(JsValue property, out PropertyDescriptor descriptor)
  26. {
  27. if (property == CommonProperties.Size)
  28. {
  29. descriptor = new PropertyDescriptor(_map.Count, PropertyFlag.None);
  30. return true;
  31. }
  32. return base.TryGetProperty(property, out descriptor);
  33. }
  34. internal void Clear()
  35. {
  36. _map.Clear();
  37. }
  38. internal bool Has(JsValue key)
  39. {
  40. return _map.ContainsKey(key);
  41. }
  42. internal bool MapDelete(JsValue key)
  43. {
  44. return _map.Remove(key);
  45. }
  46. internal void MapSet(JsValue key, JsValue value)
  47. {
  48. _map[key] = value;
  49. }
  50. internal void ForEach(ICallable callable, JsValue thisArg)
  51. {
  52. var args = _engine._jsValueArrayPool.RentArray(3);
  53. args[2] = this;
  54. for (var i = 0; i < _map.Count; i++)
  55. {
  56. args[0] = _map[i];
  57. args[1] = _map.GetKey(i);
  58. callable.Call(thisArg, args);
  59. }
  60. _engine._jsValueArrayPool.ReturnArray(args);
  61. }
  62. internal JsValue MapGet(JsValue key)
  63. {
  64. if (!_map.TryGetValue(key, out var value))
  65. {
  66. return Undefined;
  67. }
  68. return value;
  69. }
  70. internal ObjectInstance Iterator()
  71. {
  72. return _realm.Intrinsics.Iterator.Construct(this);
  73. }
  74. internal ObjectInstance Keys()
  75. {
  76. return _realm.Intrinsics.Iterator.Construct(_map.Keys);
  77. }
  78. internal ObjectInstance Values()
  79. {
  80. return _realm.Intrinsics.Iterator.Construct(_map.Values);
  81. }
  82. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  83. internal uint GetSize()
  84. {
  85. return (uint) _map.Count;
  86. }
  87. }
  88. }