Skip to content

Commit

Permalink
refactor: refactor uint8arrayTool to replace buffer shim
Browse files Browse the repository at this point in the history
  • Loading branch information
bruceeewong committed Jun 17, 2024
1 parent 7e5b048 commit e8ae8e4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
28 changes: 28 additions & 0 deletions packages/sdk/src/utils/__tests__/Uint8arrayTool.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Uint8arrayTool } from "../binary";

describe("Uint8arrayTool ", () => {
it("should be able to convert to hex", () => {
const bytes = new Uint8Array([0, 1, 2, 3, 4, 5]);
const hex = Uint8arrayTool.toHex(bytes);
expect(hex).toBe("000102030405");
});

it("should be able to ensure Uint8Array", () => {
const bytes = new Uint8Array([0, 1, 2, 3, 4, 5]);
const b64 = "AAECAwQF";
const arr = [0, 1, 2, 3, 4, 5];
expect(Uint8arrayTool.ensureUint8Array(bytes)).toBe(bytes);
expect(Uint8arrayTool.ensureUint8Array(b64)).toEqual(bytes);
expect(Uint8arrayTool.ensureUint8Array(arr)).toEqual(bytes);
});

it("should be able to compare bytes", () => {
const a = new Uint8Array([0, 1, 2, 3, 4, 5]);
const b = new Uint8Array([0, 1, 2, 3, 4, 5]);
const c = new Uint8Array([0, 1, 2, 3, 4, 6]);
const d = new Uint8Array([0, 1, 2, 3, 4]);
expect(Uint8arrayTool.bytesEqual(a, b)).toBe(true);
expect(Uint8arrayTool.bytesEqual(a, c)).toBe(false);
expect(Uint8arrayTool.bytesEqual(a, d)).toBe(false);
});
});
6 changes: 3 additions & 3 deletions packages/sdk/src/utils/binary/Uint8arrayTool.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { Buffer } from "buffer";
import { fromB64, toHEX } from "@mysten/sui/utils";

export class Uint8arrayTool {
static toHex(bytes: Uint8Array): string {
return Buffer.from(bytes).toString("hex");
return toHEX(bytes);
}

static ensureUint8Array(value: string | Uint8Array | number[]): Uint8Array {
if (typeof value === "string") {
return Uint8Array.from(Buffer.from(value, "base64"));
return fromB64(value);
} else if (value instanceof Uint8Array) {
return value;
} else {
Expand Down

0 comments on commit e8ae8e4

Please sign in to comment.