21 lines
678 B
TypeScript
21 lines
678 B
TypeScript
export function parseRange(
|
|
header: string | null,
|
|
size: number,
|
|
): { start: number; end: number } | null {
|
|
if (!Number.isSafeInteger(size) || size <= 0) return null
|
|
if (header === null) return { start: 0, end: size - 1 }
|
|
const match = /^bytes=(\d*)-(\d*)$/.exec(header)
|
|
if (!match || (!match[1] && !match[2])) return null
|
|
const start = match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2]))
|
|
const end = match[1] && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1
|
|
if (
|
|
!Number.isSafeInteger(start) ||
|
|
!Number.isSafeInteger(end) ||
|
|
start > end ||
|
|
start >= size ||
|
|
end < 0
|
|
)
|
|
return null
|
|
return { start, end }
|
|
}
|