calculateEffectiveBoundaries.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.js';
  8. import { assert } from 'workbox-core/_private/assert.js';
  9. import '../_version.js';
  10. /**
  11. * @param {Blob} blob A source blob.
  12. * @param {number} [start] The offset to use as the start of the
  13. * slice.
  14. * @param {number} [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 && end > blobSize) || (start && 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 !== undefined && end !== undefined) {
  39. effectiveStart = start;
  40. // Range values are inclusive, so add 1 to the value.
  41. effectiveEnd = end + 1;
  42. }
  43. else if (start !== undefined && end === undefined) {
  44. effectiveStart = start;
  45. effectiveEnd = blobSize;
  46. }
  47. else if (end !== undefined && start === undefined) {
  48. effectiveStart = blobSize - end;
  49. effectiveEnd = blobSize;
  50. }
  51. return {
  52. start: effectiveStart,
  53. end: effectiveEnd,
  54. };
  55. }
  56. export { calculateEffectiveBoundaries };