_assert.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. function number(n: number) {
  2. if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);
  3. }
  4. function bool(b: boolean) {
  5. if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);
  6. }
  7. // copied from utils
  8. export function isBytes(a: unknown): a is Uint8Array {
  9. return (
  10. a instanceof Uint8Array ||
  11. (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')
  12. );
  13. }
  14. function bytes(b: Uint8Array | undefined, ...lengths: number[]) {
  15. if (!isBytes(b)) throw new Error('Uint8Array expected');
  16. if (lengths.length > 0 && !lengths.includes(b.length))
  17. throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
  18. }
  19. type Hash = {
  20. (data: Uint8Array): Uint8Array;
  21. blockLen: number;
  22. outputLen: number;
  23. create: any;
  24. };
  25. function hash(h: Hash) {
  26. if (typeof h !== 'function' || typeof h.create !== 'function')
  27. throw new Error('Hash should be wrapped by utils.wrapConstructor');
  28. number(h.outputLen);
  29. number(h.blockLen);
  30. }
  31. function exists(instance: any, checkFinished = true) {
  32. if (instance.destroyed) throw new Error('Hash instance has been destroyed');
  33. if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');
  34. }
  35. function output(out: any, instance: any) {
  36. bytes(out);
  37. const min = instance.outputLen;
  38. if (out.length < min) {
  39. throw new Error(`digestInto() expects output buffer of length at least ${min}`);
  40. }
  41. }
  42. export { number, bool, bytes, hash, exists, output };
  43. const assert = { number, bool, bytes, hash, exists, output };
  44. export default assert;