Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

79 lines · 2.0 KBRaw History
1const encoder = new TextEncoder();
2const decoder = new TextDecoder();
3
4export const utf8 = (s: string): Uint8Array => encoder.encode(s);
5export const fromUtf8 = (b: Uint8Array): string => decoder.decode(b);
6
7export function concat(parts: readonly Uint8Array[]): Uint8Array {
8 let len = 0;
9 for (const p of parts) len += p.length;
10 const out = new Uint8Array(len);
11 let off = 0;
12 for (const p of parts) {
13 out.set(p, off);
14 off += p.length;
15 }
16 return out;
17}
18
19const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
20
21export function toHex(b: Uint8Array): string {
22 let s = "";
23 for (let i = 0; i < b.length; i++) s += HEX[b[i]!];
24 return s;
25}
26
27export function fromHex(h: string): Uint8Array {
28 const out = new Uint8Array(h.length / 2);
29 for (let i = 0; i < out.length; i++) out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
30 return out;
31}
32
33export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
34 if (a.length !== b.length) return false;
35 for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
36 return true;
37}
38
39/** Growable byte buffer used when assembling packs and pkt-line streams. */
40export class ByteWriter {
41 private buf = new Uint8Array(1024);
42 private len = 0;
43
44 private ensure(extra: number) {
45 if (this.len + extra <= this.buf.length) return;
46 let cap = this.buf.length * 2;
47 while (cap < this.len + extra) cap *= 2;
48 const next = new Uint8Array(cap);
49 next.set(this.buf.subarray(0, this.len));
50 this.buf = next;
51 }
52
53 write(b: Uint8Array): void {
54 this.ensure(b.length);
55 this.buf.set(b, this.len);
56 this.len += b.length;
57 }
58
59 byte(v: number): void {
60 this.ensure(1);
61 this.buf[this.len++] = v;
62 }
63
64 uint32(v: number): void {
65 this.ensure(4);
66 this.buf[this.len++] = (v >>> 24) & 0xff;
67 this.buf[this.len++] = (v >>> 16) & 0xff;
68 this.buf[this.len++] = (v >>> 8) & 0xff;
69 this.buf[this.len++] = v & 0xff;
70 }
71
72 get length(): number {
73 return this.len;
74 }
75
76 bytes(): Uint8Array {
77 return this.buf.slice(0, this.len);
78 }
79}