Apache License 2.0

技术解读

以下内容由 GitRead 中文社区 编辑团队基于项目 README 与官方资料整理, 结合中文开发者的常见使用场景补充技术选型建议。具体以项目官方文档为准。

GoogleChromeLabs/jsbi 深度技术分析

项目背景与痛点

在 JavaScript 生态系统中,处理大整数的操作一直是一个技术挑战。传统的 Number 类型在 JavaScript 中的表示范围有限,只能处理 53 位精度,无法满足一些对大整数计算需求较高的应用场景,比如加密算法、高精度计算等。因此,BigInt 提案应运而生,提供了原生支持大整数的能力。

然而,原生实现 BigInt 需要等浏览器对 ECMAScript 的新标准提供支持,而目前支持的范围还不全面。因此,我们需要一个可靠的解决方案,能够在没有原生支持的地方实现大整数计算。jsbi 正是这样一个解决方案,它通过纯 JavaScript 实现了 ECMAScript 的 BigInt 提案,覆盖了所有现代浏览器环境。

核心技术揭秘

jsbi 背后的核心技术在于如何用纯 JavaScript 实现高效的、跨浏览器的大整数运算。在技术实现上,它可以视为一个“迷你版”的大整数算法包,封装了所有大整数运算的基本操作,包括加法、减法、乘法、除法等。

深入 jsbi 的架构设计,最重要的是它如何管理和使用数据流来执行每一次计算。它的核心可以视为一个运算引擎,通过一系列内部函数的调用来完成复杂的数学操作。以下是一个简化的数据流图,展示了它是如何处理数据的:

graph TD subgraph "数据流" A[用户输入] --> B{"运算类型"} B -->|"加法"| C[加法运算] B -->|"减法"| D[减法运算] B -->|"乘法"| E[乘法运算] B -->|"除法"| F[除法运算] C --> G[结果输出] D --> H[结果输出] E --> I[结果输出] F --> J[结果输出] end

这样的设计不仅使得每一个运算操作都可扩展、可维护,而且保持了整体架构的模块化。在 jsbi 的实现中,我们看到其对各种边界条件的处理也非常谨慎,这是保证计算准确性的关键。

功能亮点与差异

与其他 JavaScript 大整数库(如 bignumber.js)相比,jsbi 的优势在于它提供了更高的兼容性,同时支持现代浏览器和 Node.js 环境。更重要的是,它是现代浏览器中 ECMA2020 BigInt 的纯 JS 实现,可以无缝替代,不仅减少了代码冗余,还简化了跨环境代码的实现。

功能方面,jsbi 支持所有的 BigInt 操作,包括 +、-、*、/、** 等标准运算符,完全符合 ECMA2020 的标准,同时还提供了 toString、toSource 等辅助方法,方便开发者进行进一步的开发与调试。

应用场景与落地建议

jsbi 可在需要进行跨平台大整数计算的领域使用,如加密、分布式系统中的防篡改算法等。它也适用于浏览器或移动端的 Web 应用,尤其是那些对 JavaScript 运行环境兼容性要求较高的应用。

在使用 jsbi 时,需要注意以下几点:

  • 由于是纯 JavaScript 实现,性能可能相较于原生版本稍有不足,所以在性能敏感的场景建议优先考虑原生支持的 BigInt。
  • 特殊的运算(如负数幂运算或浮点数运算)可能需要特别处理,根据文档或社区的反馈进行优化。

综合评价

jsbi 作为 JavaScript 生态中的一个优秀补充,其最大的优点在于它提供了跨平台的大整数计算能力,填补了目前浏览器环境不完全支持原生 BigInt 的空白。它在设计上的模块化和高兼容性使得开发者更容易迁移到使用 BigInt 的新标准上。虽然在极端的性能需求下可能略显不足,但总体来说,这是一个值得推荐的开源项目。

关于

GitHub 原始描述(英文)

JSBI is a pure-JavaScript implementation of the official ECMAScript BigInt proposal.

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

简要分析

热度分
1120
价值分
599
活跃状态
活跃

语言占比

JavaScript
Python
TypeScript

README

JSBI — pure-JavaScript BigInts Build status jsbi on npm

JSBI is a pure-JavaScript implementation of the ECMAScript BigInt proposal, which officially became a part of the JavaScript language in ES2020.

Installation

npm install jsbi --save

Usage

import JSBI from './jsbi.mjs';

const max = JSBI.BigInt(Number.MAX_SAFE_INTEGER);
console.log(String(max));
// → '9007199254740991'
const other = JSBI.BigInt('2');
const result = JSBI.add(max, other);
console.log(String(result));
// → '9007199254740993'

Note: explicitly call toString on any JSBI instances when console.log()ing them to see their numeric representation (e.g. String(max) or max.toString()). Without it (e.g. console.log(max)), you’ll instead see the object that represents the value.

Use babel-plugin-transform-jsbi-to-bigint to transpile JSBI code into native BigInt code.

Refer to the detailed instructions below for more information.

Why?

Native BigInts are already shipping in modern browsers (at the time of this writing, Google Chrome 67+, Opera 54+, Firefox 68+, Edge 79+, Safari 14+) and Node.js (v10.4+), but some users are still running older browsers — which means you can’t use them yet if you want your code to run everywhere.

To use BigInts in code that you want to run everywhere, you need a library. But there’s a difficulty: the BigInt proposal changes the behavior of operators (like +, >=, etc.) to work on BigInts. These changes are impossible to polyfill directly; and they are also making it infeasible (in most cases) to transpile BigInt code to fallback code using Babel or similar tools. The reason is that such a transpilation would have to replace every single operator in the program with a call to some function that performs type checks on its inputs, which would incur an unacceptable performance penalty.

The solution is to do it the other way round: write code using a library’s syntax, and transpile it to native BigInt code when available. JSBI is designed for exactly this purpose: it provides a BigInt “polyfill” implementation that behaves exactly like the upcoming native BigInts, but with a syntax that you can ship on all browsers, today.

Its advantages over other, existing big-integer libraries are:

  • it behaves exactly like native BigInts do where they are available, so to eventually migrate to those, you can mechanically update your code’s syntax; no re-thinking of its logic will be required.
  • strong focus on performance. On average, JSBI is performance-competitive with the native implementation that Google Chrome is currently shipping. (Note: we expect this statement to gradually become outdated as browsers invest in additional optimizations.)

How?

Except for mechanical differences in syntax, you use JSBI-BigInts just like you would use native BigInts. Some things even look the same, after you replace BigInt with JSBI.BigInt:

Operation native BigInts JSBI
Creation from String a = BigInt('456') a = JSBI.BigInt('456')
Creation from Number a = BigInt(789) a = JSBI.BigInt(789)
Conversion to String a.toString(radix) a.toString(radix)
Conversion to Number Number(a) JSBI.toNumber(a)
Truncation BigInt.asIntN(64, a) JSBI.asIntN(64, a)
BigInt.asUintN(64, a) JSBI.asUintN(64, a)
Type check typeof a === 'bigint' a instanceof JSBI

Most operators are replaced by static functions:

Operation native BigInts JSBI
Addition c = a + b c = JSBI.add(a, b)
Subtraction c = a - b c = JSBI.subtract(a, b)
Multiplication c = a * b c = JSBI.multiply(a, b)
Division c = a / b c = JSBI.divide(a, b)
Remainder c = a % b c = JSBI.remainder(a, b)
Exponentiation c = a ** b c = JSBI.exponentiate(a, b)
Negation b = -a b = JSBI.unaryMinus(a)
Bitwise negation b = ~a b = JSBI.bitwiseNot(a)
Left shifting c = a << b c = JSBI.leftShift(a, b)
Right shifting c = a >> b c = JSBI.signedRightShift(a, b)
Bitwise “and” c = a & b c = JSBI.bitwiseAnd(a, b)
Bitwise “or” c = a | b c = JSBI.bitwiseOr(a, b)
Bitwise “xor” c = a ^ b c = JSBI.bitwiseXor(a, b)
Comparison to other BigInts a === b JSBI.equal(a, b)
a !== b JSBI.notEqual(a, b)
a < b JSBI.lessThan(a, b)
a <= b JSBI.lessThanOrEqual(a, b)
a > b JSBI.greaterThan(a, b)
a >= b JSBI.greaterThanOrEqual(a, b)

The functions above operate only on BigInts. (They don’t perform type checks in the current implementation, because such checks are a waste of time when we assume that you know what you’re doing. Don’t try to call them with other inputs, or you’ll get “interesting” failures!)

Some operations are particularly interesting when you give them inputs of mixed types, e.g. comparing a BigInt to a Number, or concatenating a string with a BigInt. They are implemented as static functions named after the respective native operators:

Operation native BigInts JSBI
Abstract equality comparison x == y JSBI.EQ(x, y)
Generic “not equal” x != y JSBI.NE(x, y)
Generic “less than” x < y JSBI.LT(x, y)
Generic “less than or equal” x <= y JSBI.LE(x, y)
Generic “greater than” x > y JSBI.GT(x, y)
Generic “greater than or equal” x >= y JSBI.GE(x, y)
Generic addition x + y JSBI.ADD(x, y)

The variable names x and y here indicate that the variables can refer to anything, for example: JSBI.GT(101.5, BigInt('100')) or str = JSBI.ADD('result: ', BigInt('0x2A')).

Unfortunately, there are also a few things that are not supported at all:

Unsupported operation native BigInts JSBI
literals a = 123n; N/A ☹
increment a++ N/A ☹
a + 1n JSBI.add(a, JSBI.BigInt('1'))
decrement a-- N/A ☹
a - 1n JSBI.subtract(a, JSBI.BigInt('1'))

It is impossible to replicate the exact behavior of the native ++ and -- operators in a polyfill/library. Since JSBI is intended to be transpiled away eventually, it doesn’t provide a similar-but-different alternative. You can use JSBI.add() and JSBI.subtract() instead.

Since version 4.2.0, polyfills for DataView operations are included (where dv is a DataView, i is an index, le is an optional boolean indicating little endian mode, and x is a BigInt or a JSBI instance, respectively):

native BigInts/DataViews JSBI
dv.getBigInt64(i, le) JSBI.DataViewGetBigInt64(dv, i, le)
dv.setBigInt64(i, x, le) JSBI.DataViewSetBigInt64(dv, i, x, le)
dv.getBigUint64(i, le) JSBI.DataViewGetBigUint64(dv, i, le)
dv.setBigUint64(i, x, le) JSBI.DataViewSetBigUint64(dv, i, x, le)

When?

Now! The JSBI library is ready for use today.

Once BigInts are natively supported everywhere, use babel-plugin-transform-jsbi-to-bigint to transpile your JSBI code into native BigInt code once and for all.

View our issue tracker to learn more about out our future plans for JSBI, and please join the discussion!

A more vague future plan is to use the JSBI library (or an extension to it) as a staging ground for additional BigInt-related functionality. The official proposal is intentionally somewhat minimal, and leaves further “library functions” for follow-up proposals. Examples are a combined exp+mod function, and bit manipulation functions.

Development

  1. Clone this repository and cd into the local directory.

  2. Use the Node.js version specified in .nvmrc:

    nvm use
    
  3. Install development dependencies:

    npm install
    
  4. Run the tests:

    npm test
    

    See npm run for the list of commands.

For maintainers

How to publish a new release

  1. On the main branch, bump the version number in package.json:

    npm version patch -m 'Release v%s'
    

    Instead of patch, use minor or major as needed.

    Note that this produces a Git commit + tag.

  2. Push the release commit and tag:

    git push && git push --tags
    

    Our CI then automatically publishes the new release to npm.

评论

暂无评论