urbit-ob

JavaScript utilities for phonemic base wrangling.
Log | Files | Refs | README

commit f960ef2d16084aee693e96dfd49fc3c251e86a91
parent 144d4c8cf6d606357a13e43822f0cf1028435b91
Author: Jared Tobin <jared@jtobin.io>
Date:   Wed, 10 Oct 2018 19:16:33 +1300

Preserve leading zeros for hex -> patq.

This mimics the behaviour of Node's 'Buffer', which preserves leading
zeros when moving to and from hex.

Diffstat:
Mpackage.json | 2+-
Msrc/index.js | 40+++++++++++++++++++++++++++++++++++++---
2 files changed, 38 insertions(+), 4 deletions(-)

diff --git a/package.json b/package.json @@ -1,6 +1,6 @@ { "name": "ob-js", - "version": "1.4.0", + "version": "1.4.1", "description": "Utilities for Hoon-style atom printing and conversion", "main": "dist/index.js", "scripts": { diff --git a/src/index.js b/src/index.js @@ -386,6 +386,8 @@ const patp = (n) => { : loop(sxz, zero, '')) } + + // bignum patq const patq = (n) => { const buff = n.toArrayLike(Buffer) @@ -415,9 +417,38 @@ const patq = (n) => { acc + (acc === '~' ? '' : '-') + alg(elem), '~') } -hex2patq = hex => patq(new bnjs(hex, 'hex')) -patq2hex = str => { + +/** + * Convert a hex-encoded string to @q. Preserves leading zero bytes. + * @param {string} str a hex-encoded string + * @return {string} a @q-encoded string + */ +const hex2patq = hex => { + const buf = Buffer.from(hex, 'hex') + const chunks = + isOdd(buf.length) + ? concat([[buf[0]]], chunk(buf.slice(1), 2)) + : chunk(buf, 2) + const splat = map(chunks, chunk => + isUndefined(chunk[1]) + ? getPrefix(0) + getSuffix(chunk[0]) + : getPrefix(chunk[0]) + getSuffix(chunk[1]) + ) + return hex.length === 0 + ? '~zod' + : splat.reduce((acc, elem) => + acc + (acc === '~' ? '' : '-') + elem, '~') +} + + + +/** + * Convert a @q-encoded string to hexadecimal. Preserves leading zero bytes. + * @param {string} str a @q-encoded string + * @return {string} a hex-encoded string + */ +const patq2hex = str => { const chunks = split(str.slice(1), '-') const splat = map(chunks, chunk => { let syls = splitAt(3, chunk) @@ -428,10 +459,13 @@ patq2hex = str => { dec2hex(getSuffixIndex(syls[1])) return hex }) - return splat.join('') + return str.length === 0 + ? '00' + : splat.join('') } + /** * Remove all leading zero bytes from a hex-encoded string. * @param {string} str a hex encoded string