Resolve "feat(Primitives): Have Bytes Primitive extends Uint8Array (if possible)"

This commit is contained in:
devperate
2025-04-28 02:49:25 +00:00
committed by Jim Hamill
parent 1d5e3131c8
commit d4398439c7
19 changed files with 296 additions and 269 deletions
+15 -11
View File
@@ -15,16 +15,19 @@ import {
/**
* Bytes Primitive.
*/
export class Bytes {
protected readonly bytes: Uint8Array;
export class Bytes extends Uint8Array {
/**
* Instantiate Bytes from a Uint8Array.
*
* @param bytes {Uint8Array} The bytes to use.
*/
protected constructor(bytes: Uint8Array) {
this.bytes = bytes;
super(bytes);
}
// Override the constructor to ensure correct inheritance
static from(uint8Array: Uint8Array): Bytes {
return new Bytes(uint8Array);
}
/**
@@ -119,11 +122,11 @@ export class Bytes {
* @returns Bytes as a Base64 string.
*/
public toBase64(): string {
return binToBase64(this.bytes);
return binToBase64(this);
}
public toBigInt(): bigint {
return binToBigIntUintLE(this.bytes);
return binToBigIntUintLE(this);
}
/**
@@ -132,7 +135,7 @@ export class Bytes {
* @returns Bytes as a hex string.
*/
public toHex(): string {
return binToHex(this.bytes);
return binToHex(this);
}
/**
@@ -141,7 +144,7 @@ export class Bytes {
* @returns Bytes as a UTF8 string.
*/
public toUtf8(): string {
return binToUtf8(this.bytes);
return binToUtf8(this);
}
/**
@@ -149,11 +152,12 @@ export class Bytes {
*
* @returns Bytes as a Uint8Array.
*/
public toBytes(): Uint8Array {
return this.bytes;
public toUint8Array(): Uint8Array {
// NOTE: We clone the instance of Uint8Array so that we don't accidentally mutate it.
return new Uint8Array([...this]);
}
public invert(): Bytes {
return new Bytes(Uint8Array.from([...this.bytes].reverse()));
return new Bytes(Uint8Array.from([...this].reverse()));
}
}