/* * Copyright (C) Sapphirecode - All Rights Reserved * This file is part of encoding-helper which is released under MIT. * See file 'LICENSE' for full license details. * Created by Timo Hocker , May 2020 */ /* eslint-disable no-magic-numbers */ 'use strict'; const b58 = require ('b58'); function get_buffer (str, encoding) { if (encoding === 'base58') return b58.decode (str); return Buffer.from (str, encoding); } /** * encode a string to base64 * * @param {string} str string to encode * @param {string} encoding encoding the string is in * @returns {string} base64 */ function to_b64 (str, encoding = '') { const buf = get_buffer (str, encoding); return buf.toString ('base64'); } /** * encode a string to base58 * * @param {string} str string to encode * @param {string} encoding encoding the string is in * @returns {string} base58 */ function to_b58 (str, encoding = '') { const buf = get_buffer (str, encoding); return b58.encode (buf); } /** * encode a string to utf-8 * * @param {string} str string to encode * @param {string} encoding encoding the string is in * @returns {string} utf-8 */ function to_utf8 (str, encoding) { const buf = get_buffer (str, encoding); return buf.toString ('utf-8'); } /** * encode a string to hex * * @param {string} str string to encode * @param {string} encoding encoding the string is in * @returns {string} hex */ function to_hex (str, encoding = '') { const buf = get_buffer (str, encoding); return buf.toString ('hex'); } /** * encode a number to hex * * @param {number} n number to encode * @param {number} padding minumum length of output * @returns {string} hex */ function num_to_hex (n, padding = 0) { const res = n.toString (16); if (res.length < padding) return '0'.repeat (padding - res.length) + res; return res; } /** * decode a number from hex * * @param {string} h hex to decode * @returns {number} number */ function hex_to_num (h) { return parseInt (h, 16); } module.exports = { to_b64, to_b58, to_hex, to_utf8, num_to_hex, hex_to_num };