buffer_utils.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. export const encoder = new TextEncoder();
  2. export const decoder = new TextDecoder();
  3. const MAX_INT32 = 2 ** 32;
  4. export function concat(...buffers) {
  5. const size = buffers.reduce((acc, { length }) => acc + length, 0);
  6. const buf = new Uint8Array(size);
  7. let i = 0;
  8. for (const buffer of buffers) {
  9. buf.set(buffer, i);
  10. i += buffer.length;
  11. }
  12. return buf;
  13. }
  14. function writeUInt32BE(buf, value, offset) {
  15. if (value < 0 || value >= MAX_INT32) {
  16. throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
  17. }
  18. buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);
  19. }
  20. export function uint64be(value) {
  21. const high = Math.floor(value / MAX_INT32);
  22. const low = value % MAX_INT32;
  23. const buf = new Uint8Array(8);
  24. writeUInt32BE(buf, high, 0);
  25. writeUInt32BE(buf, low, 4);
  26. return buf;
  27. }
  28. export function uint32be(value) {
  29. const buf = new Uint8Array(4);
  30. writeUInt32BE(buf, value);
  31. return buf;
  32. }
  33. export function encode(string) {
  34. const bytes = new Uint8Array(string.length);
  35. for (let i = 0; i < string.length; i++) {
  36. const code = string.charCodeAt(i);
  37. if (code > 127) {
  38. throw new TypeError('non-ASCII string encountered in encode()');
  39. }
  40. bytes[i] = code;
  41. }
  42. return bytes;
  43. }