/*! * Copyright (c) Microsoft Corporation and contributors. All rights reserved. * Licensed under the MIT License. */ import { UsageError } from "@fluidframework/telemetry-utils/internal"; /** * Validates that the provided index is a safe integer. * @throws If the index is invalid. * @param index - The index to validate. * @param apiName - The name of the API performing the validation. * @throws If the index is invalid. */ export function validateSafeInteger(index: number, apiName: string): void { if (!Number.isSafeInteger(index)) { throw new UsageError(`Expected a safe integer passed to ${apiName}, got ${index}.`); } } /** * Validates that the provided index is a 0 or greater safe integer. * @param index - The index to validate. * @param apiName - The name of the API performing the validation. * @throws If the index is invalid. */ export function validatePositiveIndex(index: number, apiName: string): void { validateSafeInteger(index, apiName); if (index < 0) { throw new UsageError(`Expected non-negative index passed to ${apiName}, got ${index}.`); } } /** * Validates that the provided index is a non-negative safe integer within the bounds of the provided array (or, optionally, 1 past its end). * @throws If the index is invalid. * @param index - The index to validate. * @param array - The array to validate against. * @param apiName - The name of the API performing the validation. * @param allowOnePastEnd - Whether to allow the index to be one past the end of the array. */ export function validateIndex( index: number, array: { readonly length: number }, apiName: string, allowOnePastEnd: boolean = false, ): void { validatePositiveIndex(index, apiName); if (allowOnePastEnd) { if (index > array.length) { throw new UsageError( `Index value passed to ${apiName} is out of bounds. Expected at most ${array.length}, got ${index}.`, ); } } else { if (index >= array.length) { throw new UsageError( `Index value passed to ${apiName} is out of bounds. Expected at most ${array.length - 1}, got ${index}.`, ); } } } /** * Validates that the provided range `[startIndex, endIndex)` is valid and within the bounds of the provided array. * @remarks * This is intended for ranges which are inclusive for the lower bound, and exclusive for the upper bound, * and permits 0 length ranges, even `[array.length, array.length)`. * @throws If the index is invalid. * @param startIndex - The index that starts the range (inclusive). * @param endIndex - The index that ends the range (exclusive). * @param array - The array to validate against. * @param apiName - The name of the API performing the validation. */ export function validateIndexRange( startIndex: number, endIndex: number, array: { readonly length: number }, apiName: string, ): void { if (startIndex > endIndex) { throw new UsageError( `Malformed range passed to ${apiName}. Start index ${startIndex} is greater than end index ${endIndex}.`, ); } validateIndex(startIndex, array, apiName, true); validateIndex(endIndex, array, apiName, true); } /** * A half-open `[start, end)` range of array indices. */ export interface IndexRange { /** Start index, inclusive. */ readonly start: number; /** End index, exclusive. */ readonly end: number; } /** * Replaces a range of an array without exceeding runtime function-argument limits. * * @param array - The array to modify. * @param startIndex - The index at which to start replacing, inclusive. * @param endIndex - The index at which to stop replacing, exclusive. * @param replacement - The items with which to replace the range. * * @remarks * Equivalent to `array.splice(startIndex, endIndex - startIndex, ...replacement)`. * Native `splice` is used for small replacements. Large replacements use `copyWithin` and indexed * assignment because spreading a large array into a function call can exceed the runtime's argument * limit. */ export function replaceArrayRange( array: T[], startIndex: number, endIndex: number, replacement: readonly T[], ): void { validateIndexRange(startIndex, endIndex, array, "replaceArrayRange"); // Benchmarks (see arrayUtilities.bench.ts) show native splice is faster up to ~250 replacement // items, while the argument-safe implementation is faster at 500 and above. Native splice must also // be avoided for very large replacements, where spreading `replacement` into arguments would exceed // the engine's argument limit. if (replacement.length < 500) { array.splice(startIndex, endIndex - startIndex, ...replacement); return; } replaceArrayRangeWithoutSpread(array, startIndex, endIndex, replacement); } /** * Argument-safe fallback for {@link replaceArrayRange} used for large replacements. * * @param array - The array to modify. * @param startIndex - The index at which to start replacing, inclusive. * @param endIndex - The index at which to stop replacing, exclusive. * @param replacement - The items with which to replace the range. * * @remarks * Equivalent to `array.splice(startIndex, endIndex - startIndex, ...replacement)`, but uses * `copyWithin` and indexed assignment instead of spreading `replacement` into a function call, which * can exceed the runtime's argument limit for large arrays. * * Assumes `[startIndex, endIndex)` is a valid range of `array`; callers are responsible for validating * (see {@link replaceArrayRange}). Exported separately so this path can be tested and benchmarked * directly (e.g. to re-evaluate the size cutoff in {@link replaceArrayRange}) rather than only through * the public function, which dispatches small replacements to native `splice`. */ export function replaceArrayRangeWithoutSpread( array: T[], startIndex: number, endIndex: number, replacement: readonly T[], ): void { // Preserve splice semantics when the replacement aliases the array being modified. const replacementItems = replacement === array ? [...replacement] : replacement; const originalLength = array.length; const replacedLength = endIndex - startIndex; const newLength = originalLength + replacementItems.length - replacedLength; // Extend before moving the suffix when growing; truncate after moving it when shrinking. if (newLength > originalLength) { array.length = newLength; } // copy the items after the replaced range to their new location array.copyWithin(startIndex + replacementItems.length, endIndex, originalLength); array.length = newLength; // overwrite the old copies (from above) with the inserted content, completing the splice for ( let replacementIndex = 0; replacementIndex < replacementItems.length; replacementIndex++ ) { // replacementIndex is within bounds by construction, so this cast to drop `T | undefined` is safe. // `?? oob()` must not be used here: it would mishandle array values that are legitimately `null` or // `undefined`. `for ... of replacementItems.entries()` reads cleaner but is measurably slower due // to per-element iterator-protocol overhead (see arrayUtilities.bench.ts; roughly 1.2x-4x slower // across the benchmarked sizes, growing with size), so an indexed loop is used instead. array[startIndex + replacementIndex] = replacementItems[replacementIndex] as T; } } /** * Walks `array` in order and collects the indices of every element for which `predicate` returns * `true` into contiguous `[start, end)` ranges. * @param array - The array (or array-like) to scan. * @param shouldInclude - Returns `true` for elements whose indices should be included. * @returns The collected ranges in ascending order. The returned array is empty if no elements match. */ export function collectContiguousRanges( array: { readonly length: number; readonly [index: number]: T }, shouldInclude: (item: T) => boolean, ): readonly IndexRange[] { const ranges: { start: number; end: number }[] = []; for (let i = 0; i < array.length; i++) { if (shouldInclude(array[i] as T)) { const last = ranges[ranges.length - 1]; if (last?.end === i) { last.end = i + 1; } else { ranges.push({ start: i, end: i + 1 }); } } } return ranges; }