UNPKG

ts-prims

Version:
43 lines 1.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Varint = exports.isInteger = exports.integerType = void 0; const prim_js_1 = require("./prim.js"); const width_1 = require("./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` */ const integerType = (w) => (w <= 7 ? Number : BigInt); exports.integerType = integerType; /** * 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 */ const isInteger = (pc, v) => (typeof v == 'bigint') || Number.isInteger(v) ? undefined : `${(0, prim_js_1.display)(v)} is not assignable to type '${pc.name}'.\n` + ` Not an integer.`; exports.isInteger = isInteger; /** * 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 */ const Varint = (w) => (0, prim_js_1.Prim)(`varint<${w}>`, (0, exports.integerType)(w), [exports.isInteger, (0, width_1.widthConstraint)(w)]); exports.Varint = Varint; //# sourceMappingURL=varint.js.map