SetObjectSerializer.js 890 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. /** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  6. /** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  7. class SetObjectSerializer {
  8. /**
  9. * @template T
  10. * @param {Set<T>} obj set
  11. * @param {ObjectSerializerContext} context context
  12. */
  13. serialize(obj, context) {
  14. context.write(obj.size);
  15. for (const value of obj) {
  16. context.write(value);
  17. }
  18. }
  19. /**
  20. * @template T
  21. * @param {ObjectDeserializerContext} context context
  22. * @returns {Set<T>} date
  23. */
  24. deserialize(context) {
  25. /** @type {number} */
  26. let size = context.read();
  27. /** @type {Set<T>} */
  28. const set = new Set();
  29. for (let i = 0; i < size; i++) {
  30. set.add(context.read());
  31. }
  32. return set;
  33. }
  34. }
  35. module.exports = SetObjectSerializer;