All files / src/internal checks.ts

100% Statements 36/36
100% Branches 54/54
100% Functions 11/11
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230                              113x       762x 5x 5x 5x 5x                                           12895x   718x     1951x   25x   19x   65x   10098x   19x           601342x                                                     3787376x                   318x                                     445738x 161x   445577x                                 1761x 80x   1681x                                         76938x 76905x 76861x 18x                                 1620417x                                     210324x 325x                                 1584453x 28517x          
/**
 * Argument checks shared by every collection: element indexes, insertion positions and ranges,
 * with uniform error classes and messages.
 *
 * Each check keeps the passing path to one inline test; building a message happens only on
 * failure, in separate functions. Values are rendered into messages without running user code.
 *
 * @internal
 * @packageDocumentation
 */
 
import { IllegalArgumentError, IndexOutOfBoundsError, NullElementError } from '../errors/errors'
import { charCodeAt, jsonStringify, stringSlice, toText } from './intrinsics'
 
/** The longest rendering of a string, symbol or bigint in a message, in UTF-16 code units. */
const MAX_RENDERED = 40
 
/** Cuts `text` to `MAX_RENDERED` code units without splitting a surrogate pair. */
function cut(text: string): string {
  if (text.length <= MAX_RENDERED) return text
  let end = MAX_RENDERED
  const last = charCodeAt(text, end - 1)
  if (last >= 0xd800 && last <= 0xdbff) end -= 1
  return stringSlice(text, 0, end)
}
 
/**
 * Renders a value for an error message without running user code, including built-ins replaced
 * after the library loaded (it uses the copies in `intrinsics.ts` and the language's own string
 * conversion of primitives).
 *
 * Objects and functions are described by `typeof` only (no `toString`, getter, `Symbol.toStringTag`
 * or `Proxy` trap runs). Strings are cut to 40 code units without splitting a surrogate pair and
 * JSON-escaped, so quotes and control characters cannot forge log lines. Symbols and bigints are
 * cut the same way but not escaped; numbers, booleans, `null` and `undefined` are written as they
 * are.
 *
 * Time: O(1), except for a bigint or a symbol, which is converted to a string in full before it is
 * cut: linear in a symbol's description length, and more than linear in a bigint's digit count.
 *
 * @param value - Any value.
 * @returns A short, safe description.
 * @internal
 */
export function describeValue(value: unknown): string {
  switch (typeof value) {
    case 'string':
      return jsonStringify(cut(value))
    case 'number':
    case 'boolean':
      return `${value}`
    case 'bigint':
      return `${cut(`${value}`)}n`
    case 'symbol':
      return cut(toText(value))
    case 'undefined':
      return 'undefined'
    case 'object':
      return value === null ? 'null' : 'object'
    default:
      return typeof value
  }
}
 
/** True for a primitive number accepted by `Number.isSafeInteger` (including `-0`). */
function isSafeIndex(value: unknown): value is number {
  return typeof value === 'number' && Number.isSafeInteger(value)
}
 
/**
 * Something that names the API in its error messages: `errorLabel('get')` is `ArrayList.get`.
 * Passed instead of the label so that the label is built only when an error is thrown.
 *
 * @internal
 */
export interface Labelled {
  errorLabel(method: string): string
}
 
/**
 * Where an error happened: the label itself (`<Class>.<method>`), or the collection and the
 * method, from which the label is built only when it is needed.
 *
 * @internal
 */
export type Where = string | Labelled
 
/**
 * The label of `where`.
 *
 * @internal
 */
export function labelOf(where: Where, method: string): string {
  return typeof where === 'string' ? where : where.errorLabel(method)
}
 
function outOfBounds(
  where: Where,
  method: string,
  label: string,
  value: unknown,
  size: number,
): Error {
  return new IndexOutOfBoundsError(
    `${labelOf(where, method)}: ${label} ${describeValue(value)} is out of bounds for size ${size}`,
  )
}
 
/**
 * Checks an element index: a safe integer with `0 <= index < size`.
 *
 * Time: O(1).
 *
 * @param index - The index given by the caller; any value.
 * @param size - The collection's current size.
 * @param where - `<Class>.<method>`, or the collection, for the message.
 * @param method - The method, when `where` is the collection.
 * @returns The index, with `-0` turned into `0`.
 * @throws IndexOutOfBoundsError when the index is not a safe integer or is out of range.
 * @internal
 */
export function checkIndex(index: unknown, size: number, where: Where, method = ''): number {
  if (!isSafeIndex(index) || index < 0 || index >= size) {
    throw outOfBounds(where, method, 'index', index, size)
  }
  return index + 0
}
 
/**
 * Checks an insertion position: a safe integer with `0 <= position <= size`.
 *
 * Time: O(1).
 *
 * @param position - The position given by the caller; any value.
 * @param size - The collection's current size.
 * @param where - `<Class>.<method>`, or the collection, for the message.
 * @param method - The method, when `where` is the collection.
 * @returns The position, with `-0` turned into `0`.
 * @throws IndexOutOfBoundsError when the position is not a safe integer or is out of range.
 * @internal
 */
export function checkPosition(position: unknown, size: number, where: Where, method = ''): number {
  if (!isSafeIndex(position) || position < 0 || position > size) {
    throw outOfBounds(where, method, 'position', position, size)
  }
  return position + 0
}
 
/**
 * Checks a half-open range `[from, to)` against a collection of `size` elements.
 *
 * Checked in order: `from` is a safe integer, `from >= 0`, `to` is a safe integer, `to <= size`
 * (each failure is an `IndexOutOfBoundsError` naming that bound), then `from <= to` (an
 * `IllegalArgumentError` naming both). `from === to` is a valid empty range.
 *
 * Time: O(1).
 *
 * @param from - Start of the range, inclusive; any value.
 * @param to - End of the range, exclusive; any value.
 * @param size - The collection's current size.
 * @param where - `<Class>.<method>`, for the message.
 * @throws IndexOutOfBoundsError when a bound is not a safe integer, `from < 0` or `to > size`.
 * @throws IllegalArgumentError when `from > to`.
 * @internal
 */
export function checkRange(from: unknown, to: unknown, size: number, where: string): void {
  if (!isSafeIndex(from) || from < 0) throw outOfBounds(where, '', 'from', from, size)
  if (!isSafeIndex(to) || to > size) throw outOfBounds(where, '', 'to', to, size)
  if (from > to) {
    throw new IllegalArgumentError(
      `${where}: from ${describeValue(from)} is greater than to ${describeValue(to)} for size ${size}`,
    )
  }
}
 
/**
 * Returns whether `value` can be iterated with `for…of`: not `null` or `undefined`, and with a
 * callable `Symbol.iterator`. Reading `Symbol.iterator` may run a getter or `Proxy` trap.
 *
 * Time: O(1) plus that read.
 *
 * @param value - Any value.
 * @returns `true` when `value` is iterable.
 * @internal
 */
export function isIterable(value: unknown): value is Iterable<unknown> {
  return (
    value !== null &&
    value !== undefined &&
    typeof (value as { [Symbol.iterator]?: unknown })[Symbol.iterator] === 'function'
  )
}
 
/**
 * Throws `TypeError` unless `value` is a function.
 *
 * Time: O(1).
 *
 * @param value - The argument given by the caller.
 * @param where - `<Class>.<method>`, for the message.
 * @param what - The parameter's name, for the message.
 * @throws TypeError when `value` is not a function.
 * @internal
 */
export function requireFunction(value: unknown, where: string, what: string): void {
  if (typeof value !== 'function') {
    throw new TypeError(`${where}: ${what} is not a function`)
  }
}
 
/**
 * Throws `NullElementError` when `value` is `null` or `undefined`, for collections that reject
 * them as elements.
 *
 * Time: O(1).
 *
 * @param value - The element given by the caller.
 * @param where - `<Class>.<method>`, or the collection, for the message.
 * @param method - The method, when `where` is the collection.
 * @throws NullElementError when `value` is `null` or `undefined`.
 * @internal
 */
export function requireElement(value: unknown, where: Where, method = ''): void {
  if (value === null || value === undefined) {
    throw new NullElementError(
      `${labelOf(where, method)}: ${value === null ? 'null' : 'undefined'} is not allowed as an element`,
    )
  }
}