JsWeakMap.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. namespace Jint.Native;
  5. internal sealed class JsWeakMap : ObjectInstance
  6. {
  7. private readonly ConditionalWeakTable<JsValue, JsValue> _table;
  8. public JsWeakMap(Engine engine) : base(engine)
  9. {
  10. _table = new ConditionalWeakTable<JsValue, JsValue>();
  11. }
  12. internal bool WeakMapHas(JsValue key)
  13. {
  14. return _table.TryGetValue(key, out _);
  15. }
  16. internal bool WeakMapDelete(JsValue key)
  17. {
  18. return _table.Remove(key);
  19. }
  20. internal void WeakMapSet(JsValue key, JsValue value)
  21. {
  22. if (!key.CanBeHeldWeakly(_engine.GlobalSymbolRegistry))
  23. {
  24. ExceptionHelper.ThrowTypeError(_engine.Realm, "WeakMap key must be an object, got " + key);
  25. }
  26. #if SUPPORTS_WEAK_TABLE_ADD_OR_UPDATE
  27. _table.AddOrUpdate(key, value);
  28. #else
  29. _table.Remove(key);
  30. _table.Add(key, value);
  31. #endif
  32. }
  33. internal JsValue WeakMapGet(JsValue key)
  34. {
  35. if (!_table.TryGetValue(key, out var value))
  36. {
  37. return Undefined;
  38. }
  39. return value;
  40. }
  41. }