From 84b53a049d49a6112c61e3fcff22ad30fcee114b Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Sun, 18 May 2014 10:37:00 -0500 Subject: [PATCH] util: perhaps a more clever way of U64 writes using bn.js. Signed-off-by: Fedor Indutny --- lib/bcoin/utils.js | 42 ++++++++++-------------------------------- 1 file changed, 10 insertions(+), 32 deletions(-) diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index 9cf9c168..ba505641 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -180,23 +180,12 @@ utils.writeU64 = function writeU64(dst, num, off) { if (!off) off = 0; - var num = new bn(num); + num = new bn(num).maskn(64).toArray(); + while (num.length < 8) num.unshift(0); - var left = num.shrn(32).toArray(); - while (left.length < 4) left.unshift(0); - - var right = num.maskn(32).toArray(); - while (right.length < 4) right.unshift(0); - - dst[off] = right[3]; - dst[off + 1] = right[2]; - dst[off + 2] = right[1]; - dst[off + 3] = right[0]; - - dst[off + 4] = left[3]; - dst[off + 5] = left[2]; - dst[off + 6] = left[1]; - dst[off + 7] = left[0]; + num.reverse().forEach(function(ch) { + dst[off++] = ch; + }); return 8; }; @@ -223,23 +212,12 @@ utils.writeU64BE = function writeU64BE(dst, num, off) { if (!off) off = 0; - var num = new bn(num); + num = new bn(num).maskn(64).toArray(); + while (num.length < 8) num.unshift(0); - var left = num.shrn(32).toArray(); - while (left.length < 4) left.unshift(0); - - var right = num.maskn(32).toArray(); - while (right.length < 4) right.unshift(0); - - dst[off] = left[0]; - dst[off + 1] = left[1]; - dst[off + 2] = left[2]; - dst[off + 3] = left[3]; - - dst[off + 4] = right[0]; - dst[off + 5] = right[1]; - dst[off + 6] = right[2]; - dst[off + 7] = right[3]; + num.forEach(function(ch) { + dst[off++] = ch; + }); return 8; };