diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index 40571777..9ce5b2be 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -1241,6 +1241,120 @@ utils.writeU64BE = function writeU64BE(dst, num, off) { return 8; }; +utils.writeU64N = function writeU64N(dst, num, off) { + return utils.write64N(dst, num, off); +}; + +utils.writeU64NBE = function writeU64NBE(dst, num, off) { + return utils.write64NBE(dst, num, off); +}; + +utils.write64N = function write64N(dst, num, off) { + var neg, hi, lo, one, i, b; + + off = off >>> 0; + + if (num < 0) + neg = true; + + num = num < 0 ? -num : num; + + hi = num / 0x100000000 | 0; + lo = num % 0x100000000; + + dst[off + 0] = (lo >>> 0) & 0xff; + dst[off + 1] = (lo >>> 8) & 0xff; + dst[off + 2] = (lo >>> 16) & 0xff; + dst[off + 3] = (lo >>> 24) & 0xff; + dst[off + 4] = (hi >>> 0) & 0xff; + dst[off + 5] = (hi >>> 8) & 0xff; + dst[off + 6] = (hi >>> 16) & 0xff; + dst[off + 7] = (hi >>> 24) & 0xff; + + if (neg) { + one = 1; + for (i = off; i < off + 8; i++) { + b = (dst[i] ^ 0xff) + one; + dst[i] = b & 0xff; + one = b >>> 8; + } + } + + return 8; +}; + +utils.write64NBE = function write64NBE(dst, num, off) { + var neg, hi, lo, one, i, b; + + off = off >>> 0; + + if (num < 0) + neg = true; + + num = num < 0 ? -num : num; + + hi = num / 0x100000000 | 0; + lo = num % 0x100000000; + + dst[off + 7] = (lo >>> 0) & 0xff; + dst[off + 6] = (lo >>> 8) & 0xff; + dst[off + 5] = (lo >>> 16) & 0xff; + dst[off + 4] = (lo >>> 24) & 0xff; + dst[off + 3] = (hi >>> 0) & 0xff; + dst[off + 2] = (hi >>> 8) & 0xff; + dst[off + 1] = (hi >>> 16) & 0xff; + dst[off + 0] = (hi >>> 24) & 0xff; + + if (neg) { + one = 1; + for (i = off + 7; i >= off; i--) { + b = (dst[i] ^ 0xff) + one; + dst[i] = b & 0xff; + one = b >>> 8; + } + } + + return 8; +}; + +utils.readU64N = function readU64N(dst, off) { + off = off >>> 0; + var hi = utils.readU32(dst, off + 4); + var lo = utils.readU32(dst, off); + return (hi * 0x100000000) + lo; +}; + +utils.readU64NBE = function readU64NBE(dst, off) { + off = off >>> 0; + var hi = utils.readU32BE(dst, off); + var lo = utils.readU32BE(dst, off + 4); + return (hi * 0x100000000) + lo; +}; + +utils.read64N = function read64N(dst, off) { + off = off >>> 0; + var hi = utils.readU32(dst, off + 4); + var lo = utils.readU32(dst, off); + if (hi & 0x80000000) { + hi = ~hi + 1; + lo = ~lo + 1; + return -(hi * 0x100000000 + lo); + } + return (hi * 0x100000000) + lo; +}; + +utils.read64NBE = function read64NBE(dst, off) { + off = off >>> 0; + var hi = utils.readU32BE(dst, off); + var lo = utils.readU32BE(dst, off + 4); + if (hi & 0x80000000) { + hi = ~hi + 1; + lo = ~lo + 1; + return -(hi * 0x100000000 + lo); + } + return (hi * 0x100000000) + lo; +}; + utils.writeU256 = function writeU256(dst, num, off) { var i;