From fb47caa0753864da1ca9ecc7d20ef82dcdec101d Mon Sep 17 00:00:00 2001 From: Beau Gunderson Date: Fri, 12 Dec 2014 16:58:31 -0800 Subject: [PATCH] =?UTF-8?q?possibleAddresses=20=E2=86=92=20possibleSubnets?= =?UTF-8?q?,=20add=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/ipv6.js | 15 +++++++++++---- test/functionality-v6-test.js | 10 ++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/lib/ipv6.js b/lib/ipv6.js index ff8aa9f8..8fdb8216 100644 --- a/lib/ipv6.js +++ b/lib/ipv6.js @@ -215,13 +215,20 @@ v6.Address.prototype.mask = function (optionalMask) { /* * Returns the number of possible subnets of a given size in the address */ -v6.Address.prototype.possibleAddresses = function (optionalSubnetSize) { +v6.Address.prototype.possibleSubnets = function (optionalSubnetSize) { if (optionalSubnetSize === undefined) { - optionalSubnetSize = 0; + optionalSubnetSize = 128; } - return addCommas(new BigInteger('2', 10).pow((v6.BITS - this.subnetMask) - - (v6.BITS - optionalSubnetSize)).toString(10)); + var availableBits = v6.BITS - this.subnetMask; + var subnetBits = Math.abs(optionalSubnetSize - v6.BITS); + var subnetPowers = availableBits - subnetBits; + + if (subnetPowers < 0) { + return '0'; + } + + return addCommas(new BigInteger('2', 10).pow(subnetPowers).toString(10)); }; /* diff --git a/test/functionality-v6-test.js b/test/functionality-v6-test.js index 346ac2f8..951b346c 100644 --- a/test/functionality-v6-test.js +++ b/test/functionality-v6-test.js @@ -98,6 +98,16 @@ describe('v6', function () { topic.isInSubnet(same).should.equal(true); }); + + it('calculates and formats the subnet size', function () { + topic.possibleSubnets().should.equal('18,446,744,073,709,551,616'); + topic.possibleSubnets(128).should.equal('18,446,744,073,709,551,616'); + topic.possibleSubnets(96).should.equal('4,294,967,296'); + topic.possibleSubnets(65).should.equal('2'); + topic.possibleSubnets(64).should.equal('1'); + topic.possibleSubnets(63).should.equal('0'); + topic.possibleSubnets(0).should.equal('0'); + }); }); describe('Small subnets', function () {