_assert.js 1.5 KB

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