opusdev/vector-similarity-api
1
1import { BSONValue } from './bson_value';2import { BSONError } from './error';3import type { EJSONOptions } from './extended_json';4import { type InspectFn, defaultInspect } from './parser/utils';5import type { Timestamp } from './timestamp';6import * as StringUtils from './utils/string_utils';7 8interface LongWASMHelpers {9 /** Gets the high bits of the last operation performed */10 get_high(this: void): number;11 div_u(12 this: void,13 lowBits: number,14 highBits: number,15 lowBitsDivisor: number,16 highBitsDivisor: number17 ): number;18 div_s(19 this: void,20 lowBits: number,21 highBits: number,22 lowBitsDivisor: number,23 highBitsDivisor: number24 ): number;25 rem_u(26 this: void,27 lowBits: number,28 highBits: number,29 lowBitsDivisor: number,30 highBitsDivisor: number31 ): number;32 rem_s(33 this: void,34 lowBits: number,35 highBits: number,36 lowBitsDivisor: number,37 highBitsDivisor: number38 ): number;39 mul(40 this: void,41 lowBits: number,42 highBits: number,43 lowBitsMultiplier: number,44 highBitsMultiplier: number45 ): number;46}47 48/**49 * wasm optimizations, to do native i64 multiplication and divide50 */51let wasm: LongWASMHelpers | undefined = undefined;52 53/* We do not want to have to include DOM types just for this check */54// eslint-disable-next-line @typescript-eslint/no-explicit-any55declare const WebAssembly: any;56 57try {58 wasm = new WebAssembly.Instance(59 new WebAssembly.Module(60 // prettier-ignore61 new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])62 ),63 {}64 ).exports as unknown as LongWASMHelpers;65} catch {66 // no wasm support67}68 69const TWO_PWR_16_DBL = 1 << 16;70const TWO_PWR_24_DBL = 1 << 24;71const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;72const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;73const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;74 75/** A cache of the Long representations of small integer values. */76const INT_CACHE: { [key: number]: Long } = {};77 78/** A cache of the Long representations of small unsigned integer values. */79const UINT_CACHE: { [key: number]: Long } = {};80 81const MAX_INT64_STRING_LENGTH = 20;82 83const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;84 85/** @public */86export interface LongExtended {87 $numberLong: string;88}89 90/**91 * A class representing a 64-bit integer92 * @public93 * @category BSONType94 * @remarks95 * The internal representation of a long is the two given signed, 32-bit values.96 * We use 32-bit pieces because these are the size of integers on which97 * Javascript performs bit-operations. For operations like addition and98 * multiplication, we split each number into 16 bit pieces, which can easily be99 * multiplied within Javascript's floating-point representation without overflow100 * or change in sign.101 * In the algorithms below, we frequently reduce the negative case to the102 * positive case by negating the input(s) and then post-processing the result.103 * Note that we must ALWAYS check specially whether those values are MIN_VALUE104 * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as105 * a positive number, it overflows back into a negative). Not handling this106 * case would often result in infinite recursion.107 * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.108 */109export class Long extends BSONValue {110 get _bsontype(): 'Long' {111 return 'Long';112 }113 114 /** An indicator used to reliably determine if an object is a Long or not. */115 get __isLong__(): boolean {116 return true;117 }118 119 /**120 * The high 32 bits as a signed value.121 */122 high: number;123 124 /**125 * The low 32 bits as a signed value.126 */127 low: number;128 129 /**130 * Whether unsigned or not.131 */132 unsigned: boolean;133 134 /**135 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.136 *137 * @param low - The low (signed) 32 bits of the long138 * @param high - The high (signed) 32 bits of the long139 * @param unsigned - Whether unsigned or not, defaults to signed140 */141 constructor(low: number, high?: number, unsigned?: boolean);142 /**143 * Constructs a 64 bit two's-complement integer, given a bigint representation.144 *145 * @param value - BigInt representation of the long value146 * @param unsigned - Whether unsigned or not, defaults to signed147 */148 constructor(value: bigint, unsigned?: boolean);149 /**150 * Constructs a 64 bit two's-complement integer, given a string representation.151 *152 * @param value - String representation of the long value153 * @param unsigned - Whether unsigned or not, defaults to signed154 */155 constructor(value: string, unsigned?: boolean);156 constructor(157 lowOrValue: number | bigint | string = 0,158 highOrUnsigned?: number | boolean,159 unsigned?: boolean160 ) {161 super();162 const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);163 const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;164 const res =165 typeof lowOrValue === 'string'166 ? Long.fromString(lowOrValue, unsignedBool)167 : typeof lowOrValue === 'bigint'168 ? Long.fromBigInt(lowOrValue, unsignedBool)169 : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };170 this.low = res.low;171 this.high = res.high;172 this.unsigned = res.unsigned;173 }174 175 static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);176 177 /** Maximum unsigned value. */178 static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);179 /** Signed zero */180 static ZERO = Long.fromInt(0);181 /** Unsigned zero. */182 static UZERO = Long.fromInt(0, true);183 /** Signed one. */184 static ONE = Long.fromInt(1);185 /** Unsigned one. */186 static UONE = Long.fromInt(1, true);187 /** Signed negative one. */188 static NEG_ONE = Long.fromInt(-1);189 /** Maximum signed value. */190 static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);191 /** Minimum signed value. */192 static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);193 194 /**195 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.196 * Each is assumed to use 32 bits.197 * @param lowBits - The low 32 bits198 * @param highBits - The high 32 bits199 * @param unsigned - Whether unsigned or not, defaults to signed200 * @returns The corresponding Long value201 */202 static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long {203 return new Long(lowBits, highBits, unsigned);204 }205 206 /**207 * Returns a Long representing the given 32 bit integer value.208 * @param value - The 32 bit integer in question209 * @param unsigned - Whether unsigned or not, defaults to signed210 * @returns The corresponding Long value211 */212 static fromInt(value: number, unsigned?: boolean): Long {213 let obj, cachedObj, cache;214 if (unsigned) {215 value >>>= 0;216 if ((cache = 0 <= value && value < 256)) {217 cachedObj = UINT_CACHE[value];218 if (cachedObj) return cachedObj;219 }220 obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);221 if (cache) UINT_CACHE[value] = obj;222 return obj;223 } else {224 value |= 0;225 if ((cache = -128 <= value && value < 128)) {226 cachedObj = INT_CACHE[value];227 if (cachedObj) return cachedObj;228 }229 obj = Long.fromBits(value, value < 0 ? -1 : 0, false);230 if (cache) INT_CACHE[value] = obj;231 return obj;232 }233 }234 235 /**236 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.237 * @param value - The number in question238 * @param unsigned - Whether unsigned or not, defaults to signed239 * @returns The corresponding Long value240 */241 static fromNumber(value: number, unsigned?: boolean): Long {242 if (isNaN(value)) return unsigned ? Long.UZERO : Long.ZERO;243 if (unsigned) {244 if (value < 0) return Long.UZERO;245 if (value >= TWO_PWR_64_DBL) return Long.MAX_UNSIGNED_VALUE;246 } else {247 if (value <= -TWO_PWR_63_DBL) return Long.MIN_VALUE;248 if (value + 1 >= TWO_PWR_63_DBL) return Long.MAX_VALUE;249 }250 if (value < 0) return Long.fromNumber(-value, unsigned).neg();251 return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);252 }253 254 /**255 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.256 * @param value - The number in question257 * @param unsigned - Whether unsigned or not, defaults to signed258 * @returns The corresponding Long value259 */260 static fromBigInt(value: bigint, unsigned?: boolean): Long {261 // eslint-disable-next-line no-restricted-globals262 const FROM_BIGINT_BIT_MASK = BigInt(0xffffffff);263 // eslint-disable-next-line no-restricted-globals264 const FROM_BIGINT_BIT_SHIFT = BigInt(32);265 return new Long(266 Number(value & FROM_BIGINT_BIT_MASK),267 Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK),268 unsigned269 );270 }271 272 /**273 * @internal274 * Returns a Long representation of the given string, written using the specified radix.275 * Throws an error if `throwsError` is set to true and any of the following conditions are true:276 * - the string contains invalid characters for the given radix277 * - the string contains whitespace278 * @param str - The textual representation of the Long279 * @param unsigned - Whether unsigned or not, defaults to signed280 * @param radix - The radix in which the text is written (2-36), defaults to 10281 * @returns The corresponding Long value282 */283 private static _fromString(str: string, unsigned: boolean, radix: number): Long {284 if (str.length === 0) throw new BSONError('empty string');285 if (radix < 2 || 36 < radix) throw new BSONError('radix');286 287 let p;288 if ((p = str.indexOf('-')) > 0) throw new BSONError('interior hyphen');289 else if (p === 0) {290 return Long._fromString(str.substring(1), unsigned, radix).neg();291 }292 293 // Do several (8) digits each time through the loop, so as to294 // minimize the calls to the very expensive emulated div.295 const radixToPower = Long.fromNumber(Math.pow(radix, 8));296 297 let result = Long.ZERO;298 for (let i = 0; i < str.length; i += 8) {299 const size = Math.min(8, str.length - i),300 value = parseInt(str.substring(i, i + size), radix);301 if (size < 8) {302 const power = Long.fromNumber(Math.pow(radix, size));303 result = result.mul(power).add(Long.fromNumber(value));304 } else {305 result = result.mul(radixToPower);306 result = result.add(Long.fromNumber(value));307 }308 }309 result.unsigned = unsigned;310 return result;311 }312 313 /**314 * Returns a signed Long representation of the given string, written using radix 10.315 * Will throw an error if the given text is not exactly representable as a Long.316 * Throws an error if any of the following conditions are true:317 * - the string contains invalid characters for the radix 10318 * - the string contains whitespace319 * - the value the string represents is too large or too small to be a Long320 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero321 * @param str - The textual representation of the Long322 * @returns The corresponding Long value323 */324 static fromStringStrict(str: string): Long;325 /**326 * Returns a Long representation of the given string, written using the radix 10.327 * Will throw an error if the given parameters are not exactly representable as a Long.328 * Throws an error if any of the following conditions are true:329 * - the string contains invalid characters for the given radix330 * - the string contains whitespace331 * - the value the string represents is too large or too small to be a Long332 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero333 * @param str - The textual representation of the Long334 * @param unsigned - Whether unsigned or not, defaults to signed335 * @returns The corresponding Long value336 */337 static fromStringStrict(str: string, unsigned?: boolean): Long;338 /**339 * Returns a signed Long representation of the given string, written using the specified radix.340 * Will throw an error if the given parameters are not exactly representable as a Long.341 * Throws an error if any of the following conditions are true:342 * - the string contains invalid characters for the given radix343 * - the string contains whitespace344 * - the value the string represents is too large or too small to be a Long345 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero346 * @param str - The textual representation of the Long347 * @param radix - The radix in which the text is written (2-36), defaults to 10348 * @returns The corresponding Long value349 */350 static fromStringStrict(str: string, radix?: boolean): Long;351 /**352 * Returns a Long representation of the given string, written using the specified radix.353 * Will throw an error if the given parameters are not exactly representable as a Long.354 * Throws an error if any of the following conditions are true:355 * - the string contains invalid characters for the given radix356 * - the string contains whitespace357 * - the value the string represents is too large or too small to be a Long358 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero359 * @param str - The textual representation of the Long360 * @param unsigned - Whether unsigned or not, defaults to signed361 * @param radix - The radix in which the text is written (2-36), defaults to 10362 * @returns The corresponding Long value363 */364 static fromStringStrict(str: string, unsigned?: boolean, radix?: number): Long;365 static fromStringStrict(str: string, unsignedOrRadix?: boolean | number, radix?: number): Long {366 let unsigned = false;367 if (typeof unsignedOrRadix === 'number') {368 // For goog.math.long compatibility369 (radix = unsignedOrRadix), (unsignedOrRadix = false);370 } else {371 unsigned = !!unsignedOrRadix;372 }373 radix ??= 10;374 375 if (str.trim() !== str) {376 throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);377 }378 if (!StringUtils.validateStringCharacters(str, radix)) {379 throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);380 }381 382 // remove leading zeros (for later string comparison and to make math faster)383 const cleanedStr = StringUtils.removeLeadingZerosAndExplicitPlus(str);384 385 // check roundtrip result386 const result = Long._fromString(cleanedStr, unsigned, radix);387 if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {388 throw new BSONError(389 `Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`390 );391 }392 return result;393 }394 395 /**396 * Returns a signed Long representation of the given string, written using radix 10.397 *398 * If the input string is empty, this function will throw a BSONError.399 *400 * If input string does not have valid signed 64-bit Long representation, this method will return a coerced value:401 * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively402 * - 'NaN' or '+/-Infinity' are coerced to Long.ZERO403 * - other invalid characters sequences have variable behavior404 *405 * @param str - The textual representation of the Long406 * @returns The corresponding Long value407 */408 static fromString(str: string): Long;409 /**410 * Returns a signed Long representation of the given string, written using the provided radix.411 *412 * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.413 *414 * If input parameters do not have valid signed 64-bit Long representation, this method will return a coerced value:415 * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively416 * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO417 * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO418 * - other invalid characters sequences have variable behavior419 * @param str - The textual representation of the Long420 * @param radix - The radix in which the text is written (2-36), defaults to 10421 * @returns The corresponding Long value422 */423 static fromString(str: string, radix?: number): Long;424 /**425 * Returns a Long representation of the given string, written using radix 10.426 *427 * If the input string is empty, this function will throw a BSONError.428 *429 * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:430 * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values431 * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO432 * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO433 * - other invalid characters sequences have variable behavior434 * @param str - The textual representation of the Long435 * @param unsigned - Whether unsigned or not, defaults to signed436 * @returns The corresponding Long value437 */438 static fromString(str: string, unsigned?: boolean): Long;439 /**440 * Returns a Long representation of the given string, written using the specified radix.441 *442 * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.443 *444 * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:445 * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values446 * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO447 * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO448 * - other invalid characters sequences have variable behavior449 * @param str - The textual representation of the Long450 * @param unsigned - Whether unsigned or not, defaults to signed451 * @param radix - The radix in which the text is written (2-36), defaults to 10452 * @returns The corresponding Long value453 */454 static fromString(str: string, unsigned?: boolean, radix?: number): Long;455 static fromString(str: string, unsignedOrRadix?: boolean | number, radix?: number): Long {456 let unsigned = false;457 if (typeof unsignedOrRadix === 'number') {458 // For goog.math.long compatibility459 (radix = unsignedOrRadix), (unsignedOrRadix = false);460 } else {461 unsigned = !!unsignedOrRadix;462 }463 radix ??= 10;464 if (str === 'NaN' && radix < 24) {465 // radix does not support n, so coerce to zero466 return Long.ZERO;467 } else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {468 // radix does not support y, so coerce to zero469 return Long.ZERO;470 }471 return Long._fromString(str, unsigned, radix);472 }473 474 /**475 * Creates a Long from its byte representation.476 * @param bytes - Byte representation477 * @param unsigned - Whether unsigned or not, defaults to signed478 * @param le - Whether little or big endian, defaults to big endian479 * @returns The corresponding Long value480 */481 static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long {482 return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);483 }484 485 /**486 * Creates a Long from its little endian byte representation.487 * @param bytes - Little endian byte representation488 * @param unsigned - Whether unsigned or not, defaults to signed489 * @returns The corresponding Long value490 */491 static fromBytesLE(bytes: number[], unsigned?: boolean): Long {492 return new Long(493 bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24),494 bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24),495 unsigned496 );497 }498 499 /**500 * Creates a Long from its big endian byte representation.501 * @param bytes - Big endian byte representation502 * @param unsigned - Whether unsigned or not, defaults to signed503 * @returns The corresponding Long value504 */505 static fromBytesBE(bytes: number[], unsigned?: boolean): Long {506 return new Long(507 (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7],508 (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3],509 unsigned510 );511 }512 513 /**514 * Tests if the specified object is a Long.515 */516 static isLong(value: unknown): value is Long {517 return (518 value != null &&519 typeof value === 'object' &&520 '__isLong__' in value &&521 value.__isLong__ === true522 );523 }524 525 /**526 * Converts the specified value to a Long.527 * @param unsigned - Whether unsigned or not, defaults to signed528 */529 static fromValue(530 val: number | string | { low: number; high: number; unsigned?: boolean },531 unsigned?: boolean532 ): Long {533 if (typeof val === 'number') return Long.fromNumber(val, unsigned);534 if (typeof val === 'string') return Long.fromString(val, unsigned);535 // Throws for non-objects, converts non-instanceof Long:536 return Long.fromBits(537 val.low,538 val.high,539 typeof unsigned === 'boolean' ? unsigned : val.unsigned540 );541 }542 543 /** Returns the sum of this and the specified Long. */544 add(addend: string | number | Long | Timestamp): Long {545 if (!Long.isLong(addend)) addend = Long.fromValue(addend);546 547 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.548 549 const a48 = this.high >>> 16;550 const a32 = this.high & 0xffff;551 const a16 = this.low >>> 16;552 const a00 = this.low & 0xffff;553 554 const b48 = addend.high >>> 16;555 const b32 = addend.high & 0xffff;556 const b16 = addend.low >>> 16;557 const b00 = addend.low & 0xffff;558 559 let c48 = 0,560 c32 = 0,561 c16 = 0,562 c00 = 0;563 c00 += a00 + b00;564 c16 += c00 >>> 16;565 c00 &= 0xffff;566 c16 += a16 + b16;567 c32 += c16 >>> 16;568 c16 &= 0xffff;569 c32 += a32 + b32;570 c48 += c32 >>> 16;571 c32 &= 0xffff;572 c48 += a48 + b48;573 c48 &= 0xffff;574 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);575 }576 577 /**578 * Returns the sum of this and the specified Long.579 * @returns Sum580 */581 and(other: string | number | Long | Timestamp): Long {582 if (!Long.isLong(other)) other = Long.fromValue(other);583 return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);584 }585 586 /**587 * Compares this Long's value with the specified's.588 * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater589 */590 compare(other: string | number | Long | Timestamp): 0 | 1 | -1 {591 if (!Long.isLong(other)) other = Long.fromValue(other);592 if (this.eq(other)) return 0;593 const thisNeg = this.isNegative(),594 otherNeg = other.isNegative();595 if (thisNeg && !otherNeg) return -1;596 if (!thisNeg && otherNeg) return 1;597 // At this point the sign bits are the same598 if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1;599 // Both are positive if at least one is unsigned600 return other.high >>> 0 > this.high >>> 0 ||601 (other.high === this.high && other.low >>> 0 > this.low >>> 0)602 ? -1603 : 1;604 }605 606 /** This is an alias of {@link Long.compare} */607 comp(other: string | number | Long | Timestamp): 0 | 1 | -1 {608 return this.compare(other);609 }610 611 /**612 * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.613 * @returns Quotient614 */615 divide(divisor: string | number | Long | Timestamp): Long {616 if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor);617 if (divisor.isZero()) throw new BSONError('division by zero');618 619 // use wasm support if present620 if (wasm) {621 // guard against signed division overflow: the largest622 // negative number / -1 would be 1 larger than the largest623 // positive number, due to two's complement.624 if (625 !this.unsigned &&626 this.high === -0x80000000 &&627 divisor.low === -1 &&628 divisor.high === -1629 ) {630 // be consistent with non-wasm code path631 return this;632 }633 const low = (this.unsigned ? wasm.div_u : wasm.div_s)(634 this.low,635 this.high,636 divisor.low,637 divisor.high638 );639 return Long.fromBits(low, wasm.get_high(), this.unsigned);640 }641 642 if (this.isZero()) return this.unsigned ? Long.UZERO : Long.ZERO;643 let approx, rem, res;644 if (!this.unsigned) {645 // This section is only relevant for signed longs and is derived from the646 // closure library as a whole.647 if (this.eq(Long.MIN_VALUE)) {648 if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) return Long.MIN_VALUE;649 // recall that -MIN_VALUE == MIN_VALUE650 else if (divisor.eq(Long.MIN_VALUE)) return Long.ONE;651 else {652 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.653 const halfThis = this.shr(1);654 approx = halfThis.div(divisor).shl(1);655 if (approx.eq(Long.ZERO)) {656 return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;657 } else {658 rem = this.sub(divisor.mul(approx));659 res = approx.add(rem.div(divisor));660 return res;661 }662 }663 } else if (divisor.eq(Long.MIN_VALUE)) return this.unsigned ? Long.UZERO : Long.ZERO;664 if (this.isNegative()) {665 if (divisor.isNegative()) return this.neg().div(divisor.neg());666 return this.neg().div(divisor).neg();667 } else if (divisor.isNegative()) return this.div(divisor.neg()).neg();668 res = Long.ZERO;669 } else {670 // The algorithm below has not been made for unsigned longs. It's therefore671 // required to take special care of the MSB prior to running it.672 if (!divisor.unsigned) divisor = divisor.toUnsigned();673 if (divisor.gt(this)) return Long.UZERO;674 if (divisor.gt(this.shru(1)))675 // 15 >>> 1 = 7 ; with divisor = 8 ; true676 return Long.UONE;677 res = Long.UZERO;678 }679 680 // Repeat the following until the remainder is less than other: find a681 // floating-point that approximates remainder / other *from below*, add this682 // into the result, and subtract it from the remainder. It is critical that683 // the approximate value is less than or equal to the real value so that the684 // remainder never becomes negative.685 // eslint-disable-next-line @typescript-eslint/no-this-alias686 rem = this;687 while (rem.gte(divisor)) {688 // Approximate the result of division. This may be a little greater or689 // smaller than the actual value.690 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));691 692 // We will tweak the approximate result by changing it in the 48-th digit or693 // the smallest non-fractional digit, whichever is larger.694 const log2 = Math.ceil(Math.log(approx) / Math.LN2);695 const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);696 // Decrease the approximation until it is smaller than the remainder. Note697 // that if it is too large, the product overflows and is negative.698 let approxRes = Long.fromNumber(approx);699 let approxRem = approxRes.mul(divisor);700 while (approxRem.isNegative() || approxRem.gt(rem)) {701 approx -= delta;702 approxRes = Long.fromNumber(approx, this.unsigned);703 approxRem = approxRes.mul(divisor);704 }705 706 // We know the answer can't be zero... and actually, zero would cause707 // infinite recursion since we would make no progress.708 if (approxRes.isZero()) approxRes = Long.ONE;709 710 res = res.add(approxRes);711 rem = rem.sub(approxRem);712 }713 return res;714 }715 716 /**This is an alias of {@link Long.divide} */717 div(divisor: string | number | Long | Timestamp): Long {718 return this.divide(divisor);719 }720 721 /**722 * Tests if this Long's value equals the specified's.723 * @param other - Other value724 */725 equals(other: string | number | Long | Timestamp): boolean {726 if (!Long.isLong(other)) other = Long.fromValue(other);727 if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)728 return false;729 return this.high === other.high && this.low === other.low;730 }731 732 /** This is an alias of {@link Long.equals} */733 eq(other: string | number | Long | Timestamp): boolean {734 return this.equals(other);735 }736 737 /** Gets the high 32 bits as a signed integer. */738 getHighBits(): number {739 return this.high;740 }741 742 /** Gets the high 32 bits as an unsigned integer. */743 getHighBitsUnsigned(): number {744 return this.high >>> 0;745 }746 747 /** Gets the low 32 bits as a signed integer. */748 getLowBits(): number {749 return this.low;750 }751 752 /** Gets the low 32 bits as an unsigned integer. */753 getLowBitsUnsigned(): number {754 return this.low >>> 0;755 }756 757 /** Gets the number of bits needed to represent the absolute value of this Long. */758 getNumBitsAbs(): number {759 if (this.isNegative()) {760 // Unsigned Longs are never negative761 return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();762 }763 const val = this.high !== 0 ? this.high : this.low;764 let bit: number;765 for (bit = 31; bit > 0; bit--) if ((val & (1 << bit)) !== 0) break;766 return this.high !== 0 ? bit + 33 : bit + 1;767 }768 769 /** Tests if this Long's value is greater than the specified's. */770 greaterThan(other: string | number | Long | Timestamp): boolean {771 return this.comp(other) > 0;772 }773 774 /** This is an alias of {@link Long.greaterThan} */775 gt(other: string | number | Long | Timestamp): boolean {776 return this.greaterThan(other);777 }778 779 /** Tests if this Long's value is greater than or equal the specified's. */780 greaterThanOrEqual(other: string | number | Long | Timestamp): boolean {781 return this.comp(other) >= 0;782 }783 784 /** This is an alias of {@link Long.greaterThanOrEqual} */785 gte(other: string | number | Long | Timestamp): boolean {786 return this.greaterThanOrEqual(other);787 }788 /** This is an alias of {@link Long.greaterThanOrEqual} */789 ge(other: string | number | Long | Timestamp): boolean {790 return this.greaterThanOrEqual(other);791 }792 793 /** Tests if this Long's value is even. */794 isEven(): boolean {795 return (this.low & 1) === 0;796 }797 798 /** Tests if this Long's value is negative. */799 isNegative(): boolean {800 return !this.unsigned && this.high < 0;801 }802 803 /** Tests if this Long's value is odd. */804 isOdd(): boolean {805 return (this.low & 1) === 1;806 }807 808 /** Tests if this Long's value is positive. */809 isPositive(): boolean {810 return this.unsigned || this.high >= 0;811 }812 813 /** Tests if this Long's value equals zero. */814 isZero(): boolean {815 return this.high === 0 && this.low === 0;816 }817 818 /** Tests if this Long's value is less than the specified's. */819 lessThan(other: string | number | Long | Timestamp): boolean {820 return this.comp(other) < 0;821 }822 823 /** This is an alias of {@link Long#lessThan}. */824 lt(other: string | number | Long | Timestamp): boolean {825 return this.lessThan(other);826 }827 828 /** Tests if this Long's value is less than or equal the specified's. */829 lessThanOrEqual(other: string | number | Long | Timestamp): boolean {830 return this.comp(other) <= 0;831 }832 833 /** This is an alias of {@link Long.lessThanOrEqual} */834 lte(other: string | number | Long | Timestamp): boolean {835 return this.lessThanOrEqual(other);836 }837 838 /** Returns this Long modulo the specified. */839 modulo(divisor: string | number | Long | Timestamp): Long {840 if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor);841 842 // use wasm support if present843 if (wasm) {844 const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(845 this.low,846 this.high,847 divisor.low,848 divisor.high849 );850 return Long.fromBits(low, wasm.get_high(), this.unsigned);851 }852 853 return this.sub(this.div(divisor).mul(divisor));854 }855 856 /** This is an alias of {@link Long.modulo} */857 mod(divisor: string | number | Long | Timestamp): Long {858 return this.modulo(divisor);859 }860 /** This is an alias of {@link Long.modulo} */861 rem(divisor: string | number | Long | Timestamp): Long {862 return this.modulo(divisor);863 }864 865 /**866 * Returns the product of this and the specified Long.867 * @param multiplier - Multiplier868 * @returns Product869 */870 multiply(multiplier: string | number | Long | Timestamp): Long {871 if (this.isZero()) return Long.ZERO;872 if (!Long.isLong(multiplier)) multiplier = Long.fromValue(multiplier);873 874 // use wasm support if present875 if (wasm) {876 const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);877 return Long.fromBits(low, wasm.get_high(), this.unsigned);878 }879 880 if (multiplier.isZero()) return Long.ZERO;881 if (this.eq(Long.MIN_VALUE)) return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;882 if (multiplier.eq(Long.MIN_VALUE)) return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;883 884 if (this.isNegative()) {885 if (multiplier.isNegative()) return this.neg().mul(multiplier.neg());886 else return this.neg().mul(multiplier).neg();887 } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg();888 889 // If both longs are small, use float multiplication890 if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))891 return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);892 893 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.894 // We can skip products that would overflow.895 896 const a48 = this.high >>> 16;897 const a32 = this.high & 0xffff;898 const a16 = this.low >>> 16;899 const a00 = this.low & 0xffff;900 901 const b48 = multiplier.high >>> 16;902 const b32 = multiplier.high & 0xffff;903 const b16 = multiplier.low >>> 16;904 const b00 = multiplier.low & 0xffff;905 906 let c48 = 0,907 c32 = 0,908 c16 = 0,909 c00 = 0;910 c00 += a00 * b00;911 c16 += c00 >>> 16;912 c00 &= 0xffff;913 c16 += a16 * b00;914 c32 += c16 >>> 16;915 c16 &= 0xffff;916 c16 += a00 * b16;917 c32 += c16 >>> 16;918 c16 &= 0xffff;919 c32 += a32 * b00;920 c48 += c32 >>> 16;921 c32 &= 0xffff;922 c32 += a16 * b16;923 c48 += c32 >>> 16;924 c32 &= 0xffff;925 c32 += a00 * b32;926 c48 += c32 >>> 16;927 c32 &= 0xffff;928 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;929 c48 &= 0xffff;930 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);931 }932 933 /** This is an alias of {@link Long.multiply} */934 mul(multiplier: string | number | Long | Timestamp): Long {935 return this.multiply(multiplier);936 }937 938 /** Returns the Negation of this Long's value. */939 negate(): Long {940 if (!this.unsigned && this.eq(Long.MIN_VALUE)) return Long.MIN_VALUE;941 return this.not().add(Long.ONE);942 }943 944 /** This is an alias of {@link Long.negate} */945 neg(): Long {946 return this.negate();947 }948 949 /** Returns the bitwise NOT of this Long. */950 not(): Long {951 return Long.fromBits(~this.low, ~this.high, this.unsigned);952 }953 954 /** Tests if this Long's value differs from the specified's. */955 notEquals(other: string | number | Long | Timestamp): boolean {956 return !this.equals(other);957 }958 959 /** This is an alias of {@link Long.notEquals} */960 neq(other: string | number | Long | Timestamp): boolean {961 return this.notEquals(other);962 }963 /** This is an alias of {@link Long.notEquals} */964 ne(other: string | number | Long | Timestamp): boolean {965 return this.notEquals(other);966 }967 968 /**969 * Returns the bitwise OR of this Long and the specified.970 */971 or(other: number | string | Long): Long {972 if (!Long.isLong(other)) other = Long.fromValue(other);973 return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);974 }975 976 /**977 * Returns this Long with bits shifted to the left by the given amount.978 * @param numBits - Number of bits979 * @returns Shifted Long980 */981 shiftLeft(numBits: number | Long): Long {982 if (Long.isLong(numBits)) numBits = numBits.toInt();983 if ((numBits &= 63) === 0) return this;984 else if (numBits < 32)985 return Long.fromBits(986 this.low << numBits,987 (this.high << numBits) | (this.low >>> (32 - numBits)),988 this.unsigned989 );990 else return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);991 }992 993 /** This is an alias of {@link Long.shiftLeft} */994 shl(numBits: number | Long): Long {995 return this.shiftLeft(numBits);996 }997 998 /**999 * Returns this Long with bits arithmetically shifted to the right by the given amount.1000 * @param numBits - Number of bits1001 * @returns Shifted Long1002 */1003 shiftRight(numBits: number | Long): Long {1004 if (Long.isLong(numBits)) numBits = numBits.toInt();1005 if ((numBits &= 63) === 0) return this;1006 else if (numBits < 32)1007 return Long.fromBits(1008 (this.low >>> numBits) | (this.high << (32 - numBits)),1009 this.high >> numBits,1010 this.unsigned1011 );1012 else return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);1013 }1014 1015 /** This is an alias of {@link Long.shiftRight} */1016 shr(numBits: number | Long): Long {1017 return this.shiftRight(numBits);1018 }1019 1020 /**1021 * Returns this Long with bits logically shifted to the right by the given amount.1022 * @param numBits - Number of bits1023 * @returns Shifted Long1024 */1025 shiftRightUnsigned(numBits: Long | number): Long {1026 if (Long.isLong(numBits)) numBits = numBits.toInt();1027 numBits &= 63;1028 if (numBits === 0) return this;1029 else {1030 const high = this.high;1031 if (numBits < 32) {1032 const low = this.low;1033 return Long.fromBits(1034 (low >>> numBits) | (high << (32 - numBits)),1035 high >>> numBits,1036 this.unsigned1037 );1038 } else if (numBits === 32) return Long.fromBits(high, 0, this.unsigned);1039 else return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);1040 }1041 }1042 1043 /** This is an alias of {@link Long.shiftRightUnsigned} */1044 shr_u(numBits: number | Long): Long {1045 return this.shiftRightUnsigned(numBits);1046 }1047 /** This is an alias of {@link Long.shiftRightUnsigned} */1048 shru(numBits: number | Long): Long {1049 return this.shiftRightUnsigned(numBits);1050 }1051 1052 /**1053 * Returns the difference of this and the specified Long.1054 * @param subtrahend - Subtrahend1055 * @returns Difference1056 */1057 subtract(subtrahend: string | number | Long | Timestamp): Long {1058 if (!Long.isLong(subtrahend)) subtrahend = Long.fromValue(subtrahend);1059 return this.add(subtrahend.neg());1060 }1061 1062 /** This is an alias of {@link Long.subtract} */1063 sub(subtrahend: string | number | Long | Timestamp): Long {1064 return this.subtract(subtrahend);1065 }1066 1067 /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */1068 toInt(): number {1069 return this.unsigned ? this.low >>> 0 : this.low;1070 }1071 1072 /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */1073 toNumber(): number {1074 if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);1075 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);1076 }1077 1078 /** Converts the Long to a BigInt (arbitrary precision). */1079 toBigInt(): bigint {1080 // eslint-disable-next-line no-restricted-globals -- This is allowed here as it is explicitly requesting a bigint1081 return BigInt(this.toString());1082 }1083 1084 /**1085 * Converts this Long to its byte representation.1086 * @param le - Whether little or big endian, defaults to big endian1087 * @returns Byte representation1088 */1089 toBytes(le?: boolean): number[] {1090 return le ? this.toBytesLE() : this.toBytesBE();1091 }1092 1093 /**1094 * Converts this Long to its little endian byte representation.1095 * @returns Little endian byte representation1096 */1097 toBytesLE(): number[] {1098 const hi = this.high,1099 lo = this.low;1100 return [1101 lo & 0xff,1102 (lo >>> 8) & 0xff,1103 (lo >>> 16) & 0xff,1104 lo >>> 24,1105 hi & 0xff,1106 (hi >>> 8) & 0xff,1107 (hi >>> 16) & 0xff,1108 hi >>> 241109 ];1110 }1111 1112 /**1113 * Converts this Long to its big endian byte representation.1114 * @returns Big endian byte representation1115 */1116 toBytesBE(): number[] {1117 const hi = this.high,1118 lo = this.low;1119 return [1120 hi >>> 24,1121 (hi >>> 16) & 0xff,1122 (hi >>> 8) & 0xff,1123 hi & 0xff,1124 lo >>> 24,1125 (lo >>> 16) & 0xff,1126 (lo >>> 8) & 0xff,1127 lo & 0xff1128 ];1129 }1130 1131 /**1132 * Converts this Long to signed.1133 */1134 toSigned(): Long {1135 if (!this.unsigned) return this;1136 return Long.fromBits(this.low, this.high, false);1137 }1138 1139 /**1140 * Converts the Long to a string written in the specified radix.1141 * @param radix - Radix (2-36), defaults to 101142 * @throws RangeError If `radix` is out of range1143 */1144 toString(radix?: number): string {1145 radix = radix || 10;1146 if (radix < 2 || 36 < radix) throw new BSONError('radix');1147 if (this.isZero()) return '0';1148 if (this.isNegative()) {1149 // Unsigned Longs are never negative1150 if (this.eq(Long.MIN_VALUE)) {1151 // We need to change the Long value before it can be negated, so we remove1152 // the bottom-most digit in this base and then recurse to do the rest.1153 const radixLong = Long.fromNumber(radix),1154 div = this.div(radixLong),1155 rem1 = div.mul(radixLong).sub(this);1156 return div.toString(radix) + rem1.toInt().toString(radix);1157 } else return '-' + this.neg().toString(radix);1158 }1159 1160 // Do several (6) digits each time through the loop, so as to1161 // minimize the calls to the very expensive emulated div.1162 const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);1163 // eslint-disable-next-line @typescript-eslint/no-this-alias1164 let rem: Long = this;1165 let result = '';1166 while (true) {1167 const remDiv = rem.div(radixToPower);1168 const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;1169 let digits = intval.toString(radix);1170 rem = remDiv;1171 if (rem.isZero()) {1172 return digits + result;1173 } else {1174 while (digits.length < 6) digits = '0' + digits;1175 result = '' + digits + result;1176 }1177 }1178 }1179 1180 /** Converts this Long to unsigned. */1181 toUnsigned(): Long {1182 if (this.unsigned) return this;1183 return Long.fromBits(this.low, this.high, true);1184 }1185 1186 /** Returns the bitwise XOR of this Long and the given one. */1187 xor(other: Long | number | string): Long {1188 if (!Long.isLong(other)) other = Long.fromValue(other);1189 return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);1190 }1191 1192 /** This is an alias of {@link Long.isZero} */1193 eqz(): boolean {1194 return this.isZero();1195 }1196 1197 /** This is an alias of {@link Long.lessThanOrEqual} */1198 le(other: string | number | Long | Timestamp): boolean {1199 return this.lessThanOrEqual(other);1200 }