Bug 31203: Rewrite Parse.byteCount to fix bugs.

There were two problems having to do with looking up in the UNITS
object. (1) It was checking for undefined keys by comparing to null,
rather than undefined. (2) It was finding Object.prototype keys like
"toString".
This commit is contained in:
David Fifield 2019-07-18 17:34:23 -06:00
parent abdda1c8bf
commit fac361c4a1

View file

@ -108,32 +108,26 @@ class Parse {
// Parse a count of bytes. A suffix of 'k', 'm', or 'g' (or uppercase) // Parse a count of bytes. A suffix of 'k', 'm', or 'g' (or uppercase)
// does what you would think. Returns null on error. // does what you would think. Returns null on error.
static byteCount(spec) { static byteCount(spec) {
var UNITS, count, matches, units; let matches = spec.match(/^(\d+(?:\.\d*)?)(\w*)$/);
UNITS = { if (matches === null) {
k: 1024,
m: 1024 * 1024,
g: 1024 * 1024 * 1024,
K: 1024,
M: 1024 * 1024,
G: 1024 * 1024 * 1024
};
matches = spec.match(/^(\d+(?:\.\d*)?)(\w*)$/);
if (null === matches) {
return null; return null;
} }
count = Number(matches[1]); let count = Number(matches[1]);
if (isNaN(count)) { if (isNaN(count)) {
return null; return null;
} }
if ('' === matches[2]) { const UNITS = new Map([
units = 1; ['', 1],
} else { ['k', 1024],
units = UNITS[matches[2]]; ['m', 1024*1024],
if (null === units) { ['g', 1024*1024*1024],
return null; ]);
} let unit = matches[2].toLowerCase();
if (!UNITS.has(unit)) {
return null;
} }
return count * Number(units); let multiplier = UNITS.get(unit);
return count * multiplier;
} }
// Parse a connection-address out of the "c=" Connection Data field of a // Parse a connection-address out of the "c=" Connection Data field of a