_utils.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. export * from './platform.js'
  2. const Buffer = /* @__PURE__ */ (() => globalThis.Buffer)()
  3. export function assert(condition, msg) {
  4. if (!condition) throw new Error(msg)
  5. }
  6. export function assertU8(arg) {
  7. if (arg && arg instanceof Uint8Array) return
  8. throw new TypeError('Expected an Uint8Array')
  9. }
  10. // On arrays in heap (<= 64) it's cheaper to copy into a pooled buffer than lazy-create the ArrayBuffer storage
  11. export const toBuf = (x) =>
  12. x.byteLength <= 64 && x.BYTES_PER_ELEMENT === 1
  13. ? Buffer.from(x)
  14. : Buffer.from(x.buffer, x.byteOffset, x.byteLength)
  15. export const E_STRING = 'Input is not a string'
  16. export const E_STRICT_UNICODE = 'Input is not well-formed Unicode'
  17. // Input is never pooled
  18. export function fromUint8(arr, format) {
  19. switch (format) {
  20. case 'uint8':
  21. if (arr.constructor !== Uint8Array) throw new Error('Unexpected')
  22. return arr
  23. case 'arraybuffer':
  24. if (arr.byteLength !== arr.buffer.byteLength) throw new Error('Unexpected')
  25. return arr.buffer
  26. case 'buffer':
  27. if (arr.length <= 64) return Buffer.from(arr)
  28. return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength)
  29. }
  30. throw new TypeError('Unexpected format')
  31. }
  32. // Input can be pooled
  33. export function fromBuffer(arr, format) {
  34. switch (format) {
  35. case 'uint8':
  36. // byteOffset check is slightly faster and covers most pooling, so it comes first
  37. if (arr.length <= 64 || arr.byteOffset !== 0 || arr.byteLength !== arr.buffer.byteLength) {
  38. return new Uint8Array(arr)
  39. }
  40. return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength)
  41. case 'arraybuffer':
  42. return arr.buffer.byteLength === arr.byteLength
  43. ? arr.buffer
  44. : arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)
  45. case 'buffer':
  46. if (arr.constructor !== Buffer) throw new Error('Unexpected')
  47. return arr
  48. }
  49. throw new TypeError('Unexpected format')
  50. }