ArraySerializer.js 1016 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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 ArraySerializer {
  8. /**
  9. * Serializes this instance into the provided serializer context.
  10. * @template T
  11. * @param {T[]} array array
  12. * @param {ObjectSerializerContext} context context
  13. */
  14. serialize(array, context) {
  15. context.write(array.length);
  16. for (const item of array) context.write(item);
  17. }
  18. /**
  19. * Restores this instance from the provided deserializer context.
  20. * @template T
  21. * @param {ObjectDeserializerContext} context context
  22. * @returns {T[]} array
  23. */
  24. deserialize(context) {
  25. /** @type {number} */
  26. const length = context.read();
  27. /** @type {T[]} */
  28. const array = [];
  29. for (let i = 0; i < length; i++) {
  30. array.push(context.read());
  31. }
  32. return array;
  33. }
  34. }
  35. module.exports = ArraySerializer;