Monorepo stuff

Signed-off-by: James Zuccon <zuccon@gmail.com>
This commit is contained in:
James Zuccon
2024-09-02 20:05:35 +10:00
parent f2210e631a
commit 2ac7af4069
62 changed files with 13227 additions and 149 deletions
+142
View File
@@ -0,0 +1,142 @@
import {
binToHex,
hexToBin,
isHex,
base64ToBin,
binToBase64,
isBase64,
binToUtf8,
utf8ToBin,
bigIntToBinUint64LE,
bigIntToBinUintLE,
binToBigIntUintLE,
} from '@bitauth/libauth';
/**
* Bytes Primitive.
*/
export class Bytes {
public readonly bytes: Uint8Array;
/**
* Instantiate Bytes from a Uint8Array.
*
* @param bytes {Uint8Array} The bytes to use.
*/
constructor(bytes: Uint8Array) {
this.bytes = bytes;
}
/**
* Instantiates bytes from a Base64 string.
*
* @param utf8 {string} The Base64 string.
*
* @throws {Error} If Base64 is invalid.
*
* @returns {Bytes} Instance of Bytes.
*/
public static fromBase64(base64: string): Bytes {
// If the Base64 is invalid, throw an error.
if (!isBase64(base64)) {
throw new Error('Invalid base64 string');
}
return new Bytes(base64ToBin(base64));
}
/**
* Instantiates bytes from a BigInt (LE encoded).
*
* @param number {number} The bigint number.
*
* @throws {Error} If number is invalid.
*
* @returns {Bytes} Instance of Bytes.
*/
public static fromBigInt(number: bigint): Bytes {
return new Bytes(bigIntToBinUintLE(number));
}
/**
* Instantiates bytes from a BigInt (64 Bit LE encoded).
*
* @param number {number} The bigint number.
*
* @throws {Error} If number is invalid.
*
* @returns {Bytes} Instance of Bytes.
*/
public static fromBigInt64(number: bigint): Bytes {
return new Bytes(bigIntToBinUint64LE(number));
}
/**
* Instantiates bytes from a hex string.
*
* @param hex {string} The hex string.
*
* @throws {Error} If hex is invalid.
*
* @returns {Bytes} Instance of Bytes.
*/
public static fromHex(hex: string): Bytes {
// If the hex is invalid, throw an error.
if (!isHex(hex)) {
throw new Error('Invalid hexidecimal string');
}
return new Bytes(hexToBin(hex));
}
/**
* Instantiates bytes from a UTF8 string.
*
* @param utf8 {string} The UTF8 string.
*
* @returns {Bytes} Instance of Bytes.
*/
public static fromUtf8(utf8: string): Bytes {
return new Bytes(utf8ToBin(utf8));
}
/**
* Return bytes as a Base64 string.
*
* @returns {string} 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 {string} Bytes as a hex string.
*/
public toHex(): string {
return binToHex(this.bytes);
}
/**
* Return bytes as a UTF8 string
*
* @returns {string} Bytes as a UTF8 string.
*/
public toUtf8(): string {
return binToUtf8(this.bytes);
}
/**
* Return bytes as a Uint8Array
*
* @returns {Uint8Array} Bytes as a Uint8Array.
*/
public toBytes(): Uint8Array {
return this.bytes;
}
}