pokemon-showdown/cidr.js
Guangcong Luo b665660608 Refactor for more ES6 features
Now that nodejs/node#3072 is mostly fixed, we can finally start using
Node 4+ features.

This refactor:

- uses arrow functions where appropriate

  Note that arrow functions still aren't used in Mocha, where `this`
  is sometimes meaningful.

  This also removes the need for .bind() nearly everywhere, as well
  as the `self = this` trick.

- refactors Validator and Connection into ES6 classes

- no longer uses Array#forEach for iterating arrays

  We strongly prefer for (let i = 0; i < arr.length; i++) because of
  performance reasons. Most forEaches have been replaced with for..of,
  though, which is 5x slower than the long-form loop but 2x faster
  than forEach, which is good enough outside of most inner loops.

  The only exception is tournaments, which is due for a more invasive
  refactor soon anyway.
2016-02-10 17:40:21 -06:00

67 lines
1.4 KiB
JavaScript

/**
* CIDR checker
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This file controls support for checking to see if an IP matches a
* CIDR range.
*
* @license MIT license
*/
'use strict';
let ipToLong = exports.ipToLong = function (ip) {
let numIp = 0;
let parts = ip.split('.');
for (let i = 0, len = parts.length; i < len; i++) {
numIp *= 256;
numIp += Number(parts[i]);
}
return numIp;
};
let getPattern = exports.getPattern = function (cidr) {
if (!cidr) return null;
let index = cidr.indexOf('/');
if (index > 0) {
let subnet = ipToLong(cidr.substr(0, index));
let bits = parseInt(cidr.substr(index + 1));
let mask = -1 << (32 - bits);
return [subnet & mask, mask];
}
return [ipToLong(cidr), -1];
};
/**
* Returns a checker function for the passed CIDR range or array of
* ranges. The checker function returns boolean whether or not its
* passed IP is in the range.
*/
let checker = exports.checker = function (cidr) {
if (!cidr || !cidr.length) {
return () => false;
}
let patterns;
if (Array.isArray(cidr)) {
patterns = cidr.map(getPattern).filter(x => x);
} else {
patterns = [getPattern(cidr)];
}
return ip => {
let longip = ipToLong(ip);
for (let i = 0; i < patterns.length; ++i) {
let pattern = patterns[i];
if ((longip & pattern[1]) === pattern[0]) {
return true;
}
}
return false;
};
};
exports.check = function (cidr, ip) {
return checker(cidr)(ip);
};