assert.js 922 B

1234567891011121314151617181920212223242526
  1. export function assertEmptyRest(rest) {
  2. if (Object.keys(rest).length > 0) throw new TypeError('Unexpected extra options')
  3. }
  4. // eslint-disable-next-line sonarjs/no-nested-template-literals
  5. const makeMessage = (name, extra) => `Expected${name ? ` ${name} to be` : ''} an Uint8Array${extra}`
  6. const TypedArray = Object.getPrototypeOf(Uint8Array)
  7. export function assertTypedArray(arr) {
  8. if (arr instanceof TypedArray) return
  9. throw new TypeError('Expected a TypedArray instance')
  10. }
  11. export function assertUint8(arr, options) {
  12. if (!options) {
  13. // fast path
  14. if (arr instanceof Uint8Array) return
  15. throw new TypeError('Expected an Uint8Array')
  16. }
  17. const { name, length, ...rest } = options
  18. assertEmptyRest(rest)
  19. if (arr instanceof Uint8Array && (length === undefined || arr.length === length)) return
  20. throw new TypeError(makeMessage(name, length === undefined ? '' : ` of size ${Number(length)}`))
  21. }