From 1b868b6a9dbd2c42ff05153e3c89553121249482 Mon Sep 17 00:00:00 2001 From: Matthew Zipkin Date: Tue, 2 Apr 2019 16:49:35 -0700 Subject: [PATCH 1/2] util: reverse buffers instead of strings --- lib/utils/util.js | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/lib/utils/util.js b/lib/utils/util.js index 7e3b4a28..0ab6d5c4 100644 --- a/lib/utils/util.js +++ b/lib/utils/util.js @@ -96,31 +96,19 @@ util.time = function time(date) { /** * Reverse a hex-string. - * @param {String} str - Hex string. + * @param {Buffer} * @returns {String} Reversed hex string. */ util.revHex = function revHex(buf) { assert(Buffer.isBuffer(buf)); - const str = buf.toString('hex'); - - let out = ''; - - for (let i = str.length - 2; i >= 0; i -= 2) - out += str[i] + str[i + 1]; - - return out; + return Buffer.from(buf).reverse().toString('hex'); }; util.fromRev = function fromRev(str) { assert(typeof str === 'string'); assert((str.length & 1) === 0); - let out = ''; - - for (let i = str.length - 2; i >= 0; i -= 2) - out += str[i] + str[i + 1]; - - return Buffer.from(out, 'hex'); + return Buffer.from(str, 'hex').reverse(); }; From fc7fd3cb4bd4481b2bfcbc7bb6f902fbdcd98393 Mon Sep 17 00:00:00 2001 From: Matthew Zipkin Date: Thu, 4 Apr 2019 23:59:30 -0700 Subject: [PATCH 2/2] bench: reverse hex string hash --- bench/hexstring.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 bench/hexstring.js diff --git a/bench/hexstring.js b/bench/hexstring.js new file mode 100644 index 00000000..c57e1319 --- /dev/null +++ b/bench/hexstring.js @@ -0,0 +1,17 @@ +'use strict'; + +const random = require('bcrypto/lib/random'); +const util = require('../lib/utils/util'); +const bench = require('./bench'); + +const hashes = []; + +for (let i = 0; i < 100000; i++) + hashes.push(random.randomBytes(32)); + +{ + const end = bench('hexstring'); + for (let i = 0; i < hashes.length; i++) + util.fromRev(util.revHex(hashes[i])); + end(100000); +}