[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[tor-commits] [snowflake/master] Bug 31203: Rewrite Parse.byteCount to fix bugs.



commit fac361c4a172f17fe3d103f4dae1ab811d0cfd6f
Author: David Fifield <david@xxxxxxxxxxxxxxx>
Date:   Thu Jul 18 17:34:23 2019 -0600

    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".
---
 proxy/util.js | 34 ++++++++++++++--------------------
 1 file changed, 14 insertions(+), 20 deletions(-)

diff --git a/proxy/util.js b/proxy/util.js
index dfc16f5..387f0a1 100644
--- a/proxy/util.js
+++ b/proxy/util.js
@@ -108,32 +108,26 @@ class Parse {
   // Parse a count of bytes. A suffix of 'k', 'm', or 'g' (or uppercase)
   // does what you would think. Returns null on error.
   static byteCount(spec) {
-    var UNITS, count, matches, units;
-    UNITS = {
-      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) {
+    let matches = spec.match(/^(\d+(?:\.\d*)?)(\w*)$/);
+    if (matches === null) {
       return null;
     }
-    count = Number(matches[1]);
+    let count = Number(matches[1]);
     if (isNaN(count)) {
       return null;
     }
-    if ('' === matches[2]) {
-      units = 1;
-    } else {
-      units = UNITS[matches[2]];
-      if (null === units) {
-        return null;
-      }
+    const UNITS = new Map([
+      ['', 1],
+      ['k', 1024],
+      ['m', 1024*1024],
+      ['g', 1024*1024*1024],
+    ]);
+    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

_______________________________________________
tor-commits mailing list
tor-commits@xxxxxxxxxxxxxxxxxxxx
https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits