@roochnetwork/rooch-sdk
Version:
94 lines (93 loc) • 2.31 kB
JavaScript
import { Buffer } from "buffer";
import { base16, base32, base58, base58xmr, base64, base64url, hex, utf8 } from "@scure/base";
const CODERS = {
utf8,
hex,
base16,
base32,
base64,
base64url,
base58,
base58xmr
};
function bytesEqual(a, b) {
if (a === b)
return true;
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function isBytes(a) {
return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
}
const coderTypeError = "Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr";
const bytesToString = (type, bytes2) => {
if (!CODERS.hasOwnProperty(type))
throw new TypeError(coderTypeError);
if (!isBytes(bytes2))
throw new TypeError("bytesToString() expects Uint8Array");
return CODERS[type].encode(bytes2);
};
const str = bytesToString;
const stringToBytes = (type, str2) => {
if (!CODERS.hasOwnProperty(type))
throw new TypeError(coderTypeError);
return CODERS[type].decode(str2);
};
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
if (!isBytes(a))
throw new Error("Uint8Array expected");
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
function varintByteNum(input) {
if (input < 253) {
let buf = Buffer.alloc(1);
buf.writeUInt8(input);
return buf;
} else if (input < 65536) {
let buf = Buffer.alloc(1 + 2);
buf.writeUInt8(253);
buf.writeUInt16LE(input, 1);
return buf;
} else if (input < 4294967296) {
let buf = Buffer.alloc(1 + 4);
buf.writeUInt8(254);
buf.writeUInt32LE(input, 1);
return buf;
} else {
let buf = Buffer.alloc(1 + 8);
buf.writeUInt8(255);
buf.writeInt32LE(input & -1, 1);
buf.writeUInt32LE(Math.floor(input / 4294967296), 5);
return buf;
}
}
const bytes = stringToBytes;
export {
bytes,
bytesEqual,
bytesToString,
concatBytes,
isBytes,
str,
stringToBytes,
varintByteNum
};
//# sourceMappingURL=bytes.js.map