ArraySerializer.js 882 B

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