calculateEffectiveBoundaries.mjs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
  8. import {assert} from 'workbox-core/_private/assert.mjs';
  9. import '../_version.mjs';
  10. /**
  11. * @param {Blob} blob A source blob.
  12. * @param {number|null} start The offset to use as the start of the
  13. * slice.
  14. * @param {number|null} end The offset to use as the end of the slice.
  15. * @return {Object} An object with `start` and `end` properties, reflecting
  16. * the effective boundaries to use given the size of the blob.
  17. *
  18. * @private
  19. */
  20. function calculateEffectiveBoundaries(blob, start, end) {
  21. if (process.env.NODE_ENV !== 'production') {
  22. assert.isInstance(blob, Blob, {
  23. moduleName: 'workbox-range-requests',
  24. funcName: 'calculateEffectiveBoundaries',
  25. paramName: 'blob',
  26. });
  27. }
  28. const blobSize = blob.size;
  29. if (end > blobSize || start < 0) {
  30. throw new WorkboxError('range-not-satisfiable', {
  31. size: blobSize,
  32. end,
  33. start,
  34. });
  35. }
  36. let effectiveStart;
  37. let effectiveEnd;
  38. if (start === null) {
  39. effectiveStart = blobSize - end;
  40. effectiveEnd = blobSize;
  41. } else if (end === null) {
  42. effectiveStart = start;
  43. effectiveEnd = blobSize;
  44. } else {
  45. effectiveStart = start;
  46. // Range values are inclusive, so add 1 to the value.
  47. effectiveEnd = end + 1;
  48. }
  49. return {
  50. start: effectiveStart,
  51. end: effectiveEnd,
  52. };
  53. }
  54. export {calculateEffectiveBoundaries};