UNPKG

ts-prims

Version:
37 lines 1.43 kB
import { Prim, display } from './prim.js'; import { widthConstraint } from './width'; /** * Returns the constructor for the `varint` with the given Width `W`. * * @param w The width of the integer type, in the range `0 <= w <= 15` * @returns `Number` or `BigInt` */ export const integerType = (w) => (w <= 7 ? Number : BigInt); /** * Runtime constraint that checks whether the given value `v` is an integer. * * @param pc The prim constructor for the type `P` * @param v The value to check * @returns `undefined` if `v` is an integer, otherwise a `string` error message */ export const isInteger = (pc, v) => (typeof v == 'bigint') || Number.isInteger(v) ? undefined : `${display(v)} is not assignable to type '${pc.name}'.\n` + ` Not an integer.`; /** * Returns the prim constructor for the `varint` with the given Width `W`. * * This constructor function validates that the given value `v` is an * integer and that it is within the range of the width `w`. * * ```ts * type byte = varint<1> * const Byte = Varint(1) * let b: byte = Byte(250) // runtime error * // TypeError: 250 is not in range of 'varint<1>': -128 .. 127 * * @template W The width (type), inferred from param `w` * @param w The width (value) * @returns The prim constructor function */ export const Varint = (w) => Prim(`varint<${w}>`, integerType(w), [isInteger, widthConstraint(w)]); //# sourceMappingURL=varint.js.map