Line data Source code
1 1 : import { UINT32_MAX } from "./constants.ts"; 2 : 3 : /** 4 : * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul 5 : */ 6 1 : export const imul: (a: number, b: number) => number = (() => { 7 2 : try { 8 2 : if ((Math as any).imul(UINT32_MAX, 5) === -5) { 9 2 : return (Math as any).imul; 10 2 : } 11 2 : } catch (_) { 12 : // nothing to do here 13 0 : } 14 0 : const UINT16_MAX = 0xffff; 15 0 : return (a: number, b: number) => { 16 0 : const ah = (a >>> 16) & UINT16_MAX; 17 0 : const al = a & UINT16_MAX; 18 0 : const bh = (b >>> 16) & UINT16_MAX; 19 0 : const bl = b & UINT16_MAX; 20 : // the shift by 0 fixes the sign on the high part 21 : // the final |0 converts the unsigned value into a signed value 22 0 : return (al * bl + (((ah * bl + al * bh) << 16) >>> 0)) | 0; 23 0 : }; 24 1 : })();