Files
xo-stack/packages/primitives/src/bytes.ts
T
2025-02-02 06:21:25 +00:00

160 lines
3.1 KiB
TypeScript

import {
binToHex,
hexToBin,
isHex,
base64ToBin,
binToBase64,
isBase64,
binToUtf8,
utf8ToBin,
bigIntToBinUint64LE,
bigIntToBinUintLE,
binToBigIntUintLE,
} from '@bitauth/libauth';
/**
* Bytes Primitive.
*/
export class Bytes {
protected readonly bytes: Uint8Array;
/**
* Instantiate Bytes from a Uint8Array.
*
* @param bytes {Uint8Array} The bytes to use.
*/
protected constructor(bytes: Uint8Array) {
this.bytes = bytes;
}
/**
* Instantiates bytes from an Uint8Array.
*
* @param bytes The bytes as a Uint8Array.
*
* @throws {Error} If Base64 is invalid.
*
* @returns Instance of Bytes.
*/
public static fromBytes(bytes: Uint8Array): Bytes {
return new this(bytes);
}
/**
* Instantiates bytes from a Base64 string.
*
* @param base64 The Base64 string.
*
* @throws {Error} If Base64 is invalid.
*
* @returns Instance of Bytes.
*/
public static fromBase64(base64: string): Bytes {
// If the Base64 is invalid, throw an error.
if (!isBase64(base64)) {
throw new Error(`Cannot decode invalid base64 '${base64}'`);
}
return new this(base64ToBin(base64));
}
/**
* Instantiates bytes from a BigInt (LE encoded).
*
* @param number The bigint number.
*
* @throws {Error} If number is invalid.
*
* @returns Instance of Bytes.
*/
public static fromBigInt(number: bigint): Bytes {
return new this(bigIntToBinUintLE(number));
}
/**
* Instantiates bytes from a BigInt (64 Bit LE encoded).
*
* @param number The bigint number.
*
* @throws {Error} If number is invalid.
*
* @returns Instance of Bytes.
*/
public static fromBigInt64(number: bigint): Bytes {
return new this(bigIntToBinUint64LE(number));
}
/**
* Instantiates bytes from a hex string.
*
* @param hex The hex string.
*
* @throws {Error} If hex is invalid.
*
* @returns Instance of Bytes.
*/
public static fromHex(hex: string): Bytes {
// If the hex is invalid, throw an error.
if (!isHex(hex)) {
throw new Error(`Cannot decode invalid hex '${hex}'`);
}
return new this(hexToBin(hex));
}
/**
* Instantiates bytes from a UTF8 string.
*
* @param utf8 The UTF8 string.
*
* @returns Instance of Bytes.
*/
public static fromUtf8(utf8: string): Bytes {
return new this(utf8ToBin(utf8));
}
/**
* Return bytes as a Base64 string.
*
* @returns Bytes as a Base64 string.
*/
public toBase64(): string {
return binToBase64(this.bytes);
}
public toBigInt(): bigint {
return binToBigIntUintLE(this.bytes);
}
/**
* Return bytes as a hex string.
*
* @returns Bytes as a hex string.
*/
public toHex(): string {
return binToHex(this.bytes);
}
/**
* Return bytes as a UTF8 string
*
* @returns Bytes as a UTF8 string.
*/
public toUtf8(): string {
return binToUtf8(this.bytes);
}
/**
* Return bytes as a Uint8Array
*
* @returns Bytes as a Uint8Array.
*/
public toBytes(): Uint8Array {
return this.bytes;
}
public invert(): Bytes {
return new Bytes(Uint8Array.from([...this.bytes].reverse()));
}
}