util.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. exports.stringToBytes = string => [...string].map(character => character.charCodeAt(0));
  3. const uint8ArrayUtf8ByteString = (array, start, end) => {
  4. return String.fromCharCode(...array.slice(start, end));
  5. };
  6. exports.readUInt64LE = (buffer, offset = 0) => {
  7. let n = buffer[offset];
  8. let mul = 1;
  9. let i = 0;
  10. while (++i < 8) {
  11. mul *= 0x100;
  12. n += buffer[offset + i] * mul;
  13. }
  14. return n;
  15. };
  16. exports.tarHeaderChecksumMatches = buffer => { // Does not check if checksum field characters are valid
  17. if (buffer.length < 512) { // `tar` header size, cannot compute checksum without it
  18. return false;
  19. }
  20. const MASK_8TH_BIT = 0x80;
  21. let sum = 256; // Intitalize sum, with 256 as sum of 8 spaces in checksum field
  22. let signedBitSum = 0; // Initialize signed bit sum
  23. for (let i = 0; i < 148; i++) {
  24. const byte = buffer[i];
  25. sum += byte;
  26. signedBitSum += byte & MASK_8TH_BIT; // Add signed bit to signed bit sum
  27. }
  28. // Skip checksum field
  29. for (let i = 156; i < 512; i++) {
  30. const byte = buffer[i];
  31. sum += byte;
  32. signedBitSum += byte & MASK_8TH_BIT; // Add signed bit to signed bit sum
  33. }
  34. const readSum = parseInt(uint8ArrayUtf8ByteString(buffer, 148, 154), 8); // Read sum in header
  35. // Some implementations compute checksum incorrectly using signed bytes
  36. return (
  37. // Checksum in header equals the sum we calculated
  38. readSum === sum ||
  39. // Checksum in header equals sum we calculated plus signed-to-unsigned delta
  40. readSum === (sum - (signedBitSum << 1))
  41. );
  42. };
  43. exports.uint8ArrayUtf8ByteString = uint8ArrayUtf8ByteString;