@moon7/bits
Version:
Type-safe bitwise operations for JavaScript and TypeScript with named bit collections
92 lines (91 loc) • 2.92 kB
JavaScript
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["moon7-bits"] = {}));
})(this, function(exports2) {
"use strict";
const ALL = -1 >>> 0;
const NONE = 0;
function bitMask(i) {
return 1 << i >>> 0;
}
function checkMask(bits, mask) {
return (bits & mask) !== 0;
}
function applyMask(bits, mask) {
return (bits | mask) >>> 0;
}
function clearMask(bits, mask) {
return bits & ~mask;
}
function toggleMask(bits, mask) {
return (bits ^ mask) >>> 0;
}
function getBit(bits, index) {
return checkMask(bits, bitMask(index));
}
function setBit(bits, index, value) {
return value ? setBitOn(bits, index) : setBitOff(bits, index);
}
function setBitOn(bits, index) {
return applyMask(bits, bitMask(index));
}
function setBitOff(bits, index) {
return clearMask(bits, bitMask(index));
}
function toggleBit(bits, index) {
return toggleMask(bits, bitMask(index));
}
function toBinaryString(bits, length = 32) {
return bits.toString(2).padStart(length, "0");
}
function toFormattedBinaryString(bits, length = 32) {
var _a;
const str = toBinaryString(bits, length);
return ((_a = str.match(/.{1,8}/g)) == null ? void 0 : _a.map((x) => {
var _a2;
return (_a2 = x.match(/.{1,4}/g)) == null ? void 0 : _a2.join(" ");
}).join(" - ")) ?? "";
}
function countBits(bits) {
let count = 0;
let value = bits;
while (value) {
count += value & 1;
value >>>= 1;
}
return count;
}
function isSingleBit(bits) {
return bits !== 0 && (bits & bits - 1) === 0;
}
function defineBitFlags(definition) {
const result = { ...definition };
result.mask = (name) => bitMask(result[name]);
return result;
}
function defineBitEnum(...names) {
const result = {};
names.forEach((name, index) => result[name] = index);
result.mask = (name) => bitMask(result[name]);
return result;
}
exports2.ALL = ALL;
exports2.NONE = NONE;
exports2.applyMask = applyMask;
exports2.bitMask = bitMask;
exports2.checkMask = checkMask;
exports2.clearMask = clearMask;
exports2.countBits = countBits;
exports2.defineBitEnum = defineBitEnum;
exports2.defineBitFlags = defineBitFlags;
exports2.getBit = getBit;
exports2.isSingleBit = isSingleBit;
exports2.setBit = setBit;
exports2.setBitOff = setBitOff;
exports2.setBitOn = setBitOn;
exports2.toBinaryString = toBinaryString;
exports2.toFormattedBinaryString = toFormattedBinaryString;
exports2.toggleBit = toggleBit;
exports2.toggleMask = toggleMask;
Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
});
//# sourceMappingURL=index.umd.cjs.map