ArraySerializer.js 930 B

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. class ArraySerializer {
  6. /**
  7. * Serializes this instance into the provided serializer context.
  8. * @template T
  9. * @param {T[]} array array
  10. * @param {import("./ObjectMiddleware").ObjectSerializerContext<(number | T)[]>} context context
  11. */
  12. serialize(array, context) {
  13. context.write(array.length);
  14. for (const item of array) context.write(item);
  15. }
  16. /**
  17. * Restores this instance from the provided deserializer context.
  18. * @template T
  19. * @param {import("./ObjectMiddleware").ObjectDeserializerContext<(number | T)[]>} context context
  20. * @returns {T[]} array
  21. */
  22. deserialize(context) {
  23. const length = /** @type {number} */ (context.read());
  24. /** @type {T[]} */
  25. const array = [];
  26. for (let i = 0; i < length; i++) {
  27. array.push(/** @type {T} */ (context.read()));
  28. }
  29. return array;
  30. }
  31. }
  32. module.exports = ArraySerializer;