ip-bigint
Advanced tools
Comparing version 3.0.0 to 3.0.1
26
index.js
@@ -5,16 +5,16 @@ "use strict"; | ||
const max4 = module.exports.max4 = BigInt(2) ** BigInt(32) - BigInt(1); | ||
const max6 = module.exports.max6 = BigInt(2) ** BigInt(128) - BigInt(1); | ||
const max4 = module.exports.max4 = 2n ** 32n - 1n; | ||
const max6 = module.exports.max6 = 2n ** 128n - 1n; | ||
module.exports.parse = ip => { | ||
const version = isIP.version(ip); | ||
if (![4, 6].includes(version)) throw new Error(`Invalid IP address: ${ip}`); | ||
if (!version) throw new Error(`Invalid IP address: ${ip}`); | ||
let number = BigInt(0); | ||
let exp = BigInt(0); | ||
let number = 0n; | ||
let exp = 0n; | ||
if (version === 4) { | ||
for (const n of ip.split(".").map(Number).reverse()) { | ||
number += BigInt(n) * (BigInt(2) ** BigInt(exp)); | ||
exp += BigInt(8); | ||
number += BigInt(n) * (2n ** BigInt(exp)); | ||
exp += 8n; | ||
} | ||
@@ -53,4 +53,4 @@ return {number, version}; | ||
for (const n of parts.map(part => part ? `0x${part}` : `0`).map(Number).reverse()) { | ||
number += BigInt(n) * (BigInt(2) ** BigInt(exp)); | ||
exp += BigInt(16); | ||
number += BigInt(n) * (2n ** BigInt(exp)); | ||
exp += 16n; | ||
} | ||
@@ -67,10 +67,10 @@ | ||
if (![4, 6].includes(version)) throw new Error(`Invalid version: ${version}`); | ||
if (!(BigInt(0) < number < (version === 4 ? max4 : max6))) throw new Error(`Invalid number: ${number}`); | ||
if (number < 0n || number > (version === 4 ? max4 : max6)) throw new Error(`Invalid number: ${number}`); | ||
let step = version === 4 ? BigInt(24) : BigInt(112); | ||
let step = version === 4 ? 24n : 112n; | ||
let remain = number; | ||
const parts = []; | ||
while (step > BigInt(0)) { | ||
const divisor = BigInt(2) ** BigInt(step); | ||
while (step > 0n) { | ||
const divisor = 2n ** BigInt(step); | ||
parts.push(remain / divisor); | ||
@@ -77,0 +77,0 @@ remain = number % divisor; |
{ | ||
"name": "ip-bigint", | ||
"version": "3.0.0", | ||
"version": "3.0.1", | ||
"description": "Convert IPv4 and IPv6 addresses to native BigInt and vice-versa", | ||
@@ -21,7 +21,7 @@ "author": "silverwind <me@silverwind.io>", | ||
"devDependencies": { | ||
"eslint": "7.7.0", | ||
"eslint-config-silverwind": "18.0.3", | ||
"jest": "26.4.1", | ||
"updates": "10.3.5", | ||
"versions": "8.4.3" | ||
"eslint": "7.21.0", | ||
"eslint-config-silverwind": "29.0.0", | ||
"jest": "26.6.3", | ||
"updates": "11.4.3", | ||
"versions": "8.4.5" | ||
}, | ||
@@ -28,0 +28,0 @@ "keywords": [ |
5778