Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions clients/passkeys-browser/test/helpers/buffer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// SPDX-License-Identifier: MIT
import { describe, expect, it } from "vitest";
import { BufferUint8 } from "./buffer";

describe("BufferUint8", () => {
it("returns empty bytes when nothing is written", () => {
const buf = new BufferUint8();
expect(buf.bytes()).toEqual(new Uint8Array(0));
});

it("set appends a Uint8Array", () => {
const buf = new BufferUint8();
buf.uint8array(new Uint8Array([1, 2, 3]));
expect(buf.bytes()).toEqual(new Uint8Array([1, 2, 3]));
});

it("uint8 appends a single byte", () => {
const buf = new BufferUint8();
buf.uint8(0x45);
expect(buf.bytes()).toEqual(new Uint8Array([0x45]));
});

it("uint16 appends two bytes big-endian", () => {
const buf = new BufferUint8();
buf.uint16(0x0102);
expect(buf.bytes()).toEqual(new Uint8Array([0x01, 0x02]));
});

it("skip appends zero bytes", () => {
const buf = new BufferUint8();
buf.uint8(0xAA).skip(2).uint8(0xBB);
expect(buf.bytes()).toEqual(new Uint8Array([0xAA, 0x00, 0x00, 0xBB]));
});

it("methods are chainable", () => {
const data = new Uint8Array([10, 20]);
const result = new BufferUint8()
.uint8array(data)
.uint8(0x45)
.skip(4)
.uint16(data.length)
.uint8array(data)
.bytes();

expect(result).toEqual(new Uint8Array([10, 20, 0x45, 0, 0, 0, 0, 0, 2, 10, 20]));
});

it("bytes() can be called multiple times and returns equal results", () => {
const buf = new BufferUint8().uint8(1).uint8(2);
expect(buf.bytes()).toEqual(buf.bytes());
});
});
41 changes: 41 additions & 0 deletions clients/passkeys-browser/test/helpers/buffer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: MIT
export class BufferUint8 {
private readonly chunks: Uint8Array[];

constructor() {
this.chunks = [];
}

uint8array(data: Uint8Array): this {
this.chunks.push(data);
return this;
}

uint8(value: number): this {
this.chunks.push(new Uint8Array([value]));
return this;
}

uint16(value: number): this {
const buf = new Uint8Array(2);
new DataView(buf.buffer).setUint16(0, value);
this.chunks.push(buf);
return this;
}

skip(count: number): this {
this.chunks.push(new Uint8Array(count));
return this;
}

bytes(): Uint8Array {
const size = this.chunks.reduce((n, c) => n + c.length, 0);
const out = new Uint8Array(size);
let off = 0;
for (const chunk of this.chunks) {
out.set(chunk, off);
off += chunk.length;
}
return out;
}
}
Loading