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