Skip to main content

EXACT_INT_JS

Constant EXACT_INT_JS 

Source
pub const EXACT_INT_JS: &str = "const exactHeld = [], exactFree = [];
const exactValue = (t) => ((t & 1n) === 0n ? t >> 1n : exactHeld[Number(t >> 1n)]);
const exactWord = (v) => {
  if (v >= -(1n << 62n) && v < (1n << 62n)) return v << 1n;
  const h = exactFree.length > 0 ? exactFree.pop() : exactHeld.length;
  exactHeld[h] = v;
  return (BigInt(h) << 1n) | 1n;
};
const exactImports = {
  exact_box: (v) => exactWord(v),
  exact_narrow: (t) => { const v = exactValue(t); return v >= -(1n << 63n) && v < (1n << 63n) ? v : 0n; },
  exact_add: (a, b) => exactWord(exactValue(a) + exactValue(b)),
  exact_sub: (a, b) => exactWord(exactValue(a) - exactValue(b)),
  exact_mul: (a, b) => exactWord(exactValue(a) * exactValue(b)),
  exact_div: (a, b) => exactWord(exactValue(a) / exactValue(b)),
  exact_mod: (a, b) => exactWord(exactValue(a) % exactValue(b)),
  exact_floordiv: (a, b) => { const x = exactValue(a), y = exactValue(b), q = x / y; return exactWord(x % y !== 0n && (x < 0n) !== (y < 0n) ? q - 1n : q); },
  exact_pow: (a, e) => exactWord(exactValue(a) ** e),
  exact_cmp: (a, b) => { const x = exactValue(a), y = exactValue(b); return x < y ? -1 : x > y ? 1 : 0; },
  exact_f64: (t) => Number(exactValue(t)),
  exact_clone: (t) => exactWord(exactValue(t)),
  exact_drop: (t) => { const h = Number(t >> 1n); exactHeld[h] = undefined; exactFree.push(h); },
};";
Expand description

The host’s half of a module’s exact integers (exact_*, vm::wasm::module::exact), as JavaScript: a tagged word is BigInt, an even one the integer t >> 1, an odd one a slot of exactHeld that a dropped handle gives back to exactFree. The arithmetic is BigInt’s, which truncates a quotient and gives a remainder the dividend’s sign as the reference tier does; a floored quotient corrects the truncated one. Number of a BigInt is the nearest binary64, ties to even, as an Int widens to a Real. The node shim interpolates it and runtime.js carries the same text (exact_int_every_tier_lock).