parseBuffer.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const parseUIntLE = function(buffer, offset, size) {
  2. let result;
  3. switch(size) {
  4. case 1:
  5. result = buffer.readUInt8(offset);
  6. break;
  7. case 2:
  8. result = buffer.readUInt16LE(offset);
  9. break;
  10. case 4:
  11. result = buffer.readUInt32LE(offset);
  12. break;
  13. case 8:
  14. result = Number(buffer.readBigUInt64LE(offset));
  15. break;
  16. default:
  17. throw new Error('Unsupported UInt LE size!');
  18. }
  19. return result;
  20. };
  21. /**
  22. * Parses sequential unsigned little endian numbers from the head of the passed buffer according to
  23. * the specified format passed. If the buffer is not large enough to satisfy the full format,
  24. * null values will be assigned to the remaining keys.
  25. * @param {*} buffer The buffer to sequentially extract numbers from.
  26. * @param {*} format Expected format to follow when extrcting values from the buffer. A list of list entries
  27. * with the following structure:
  28. * [
  29. * [
  30. * <key>, // Name of the key to assign the extracted number to.
  31. * <size> // The size in bytes of the number to extract. possible values are 1, 2, 4, 8.
  32. * ],
  33. * ...
  34. * ]
  35. * @returns An object with keys set to their associated extracted values.
  36. */
  37. const parse = function(buffer, format) {
  38. const result = {};
  39. let offset = 0;
  40. for(const [key, size] of format) {
  41. if(buffer.length >= offset + size) {
  42. result[key] = parseUIntLE(buffer, offset, size);
  43. }
  44. else {
  45. result[key] = null;
  46. }
  47. offset += size;
  48. }
  49. return result;
  50. };
  51. module.exports = {
  52. parse
  53. };