MapObjectSerializer.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. class MapObjectSerializer {
  6. /**
  7. * Serializes this instance into the provided serializer context.
  8. * @template K, V
  9. * @param {Map<K, V>} obj map
  10. * @param {import("./ObjectMiddleware").ObjectSerializerContext<(number | K | V)[]>} context context
  11. */
  12. serialize(obj, context) {
  13. context.write(obj.size);
  14. for (const key of obj.keys()) {
  15. context.write(key);
  16. }
  17. for (const value of obj.values()) {
  18. context.write(value);
  19. }
  20. }
  21. /**
  22. * Restores this instance from the provided deserializer context.
  23. * @template K, V
  24. * @param {import("./ObjectMiddleware").ObjectDeserializerContext<(number | K | V)[]>} context context
  25. * @returns {Map<K, V>} map
  26. */
  27. deserialize(context) {
  28. const size = /** @type {number} */ (context.read());
  29. /** @type {Map<K, V>} */
  30. const map = new Map();
  31. /** @type {K[]} */
  32. const keys = [];
  33. for (let i = 0; i < size; i++) {
  34. keys.push(/** @type {K} */ (context.read()));
  35. }
  36. for (let i = 0; i < size; i++) {
  37. map.set(keys[i], /** @type {V} */ (context.read()));
  38. }
  39. return map;
  40. }
  41. }
  42. module.exports = MapObjectSerializer;