Add portable ctz, popcnt, rotl, rotr, nearest & copysign (#75)

Thank you!
This commit is contained in:
Max Graey
2018-04-15 01:35:43 +03:00
committed by Daniel Wirtz
parent 990fa850ff
commit d66f9d205c
2 changed files with 45 additions and 0 deletions

View File

@ -75,6 +75,27 @@ Object.defineProperties(
globalScope["clz"] = Math.clz32;
globalScope["ctz"] = function ctz(value) {
var c = Math.clz32(value & -value);
return value ? 31 - c : c;
};
globalScope["popcnt"] = function popcnt(value) {
value -= value >>> 1 & 0x55555555;
value = (value & 0x33333333) + (value >>> 2 & 0x33333333);
return (((value + (value >>> 4)) & 0x0F0F0F0F) * 0x01010101) >>> 24;
};
globalScope["rotl"] = function rotl(value, shift) {
shift &= 31;
return (value << shift) | (value >>> (32 - shift));
};
globalScope["rotr"] = function rotr(value, shift) {
shift &= 31;
return (value >>> shift) | (value << (32 - shift));
};
globalScope["abs"] = Math.abs;
globalScope["max"] = Math.max;
@ -85,6 +106,14 @@ globalScope["ceil"] = Math.ceil;
globalScope["floor"] = Math.floor;
// Adopt code from https://github.com/rfk/wasm-polyfill
globalScope["nearest"] = function nearest(value) {
if (Math.abs(value - Math.trunc(value)) === 0.5) {
return 2.0 * Math.round(value * 0.5);
}
return Math.round(value);
};
globalScope["select"] = function select(ifTrue, ifFalse, condition) {
return condition ? ifTrue : ifFalse;
};
@ -93,6 +122,10 @@ globalScope["sqrt"] = Math.sqrt;
globalScope["trunc"] = Math.trunc;
globalScope["copysign"] = function copysign(x, y) {
return Math.abs(x) * Math.sign(y);
};
globalScope["bswap"] = function bswap(value) {
var a = value >> 8 & 0x00FF00FF;
var b = (value & 0x00FF00FF) << 8;