Skip to content
File

Blob: src/worker/common/hex.ts

typescript48 lines
1/**
2 * Hex encoding/decoding utilities for Git object IDs
3 */
4 
5/**
6 * Convert bytes to lowercase hex string
7 * @param bytes - Uint8Array to convert
8 * @returns Lowercase hex string
9 */
10export function bytesToHex(bytes: Uint8Array): string {
11 return Array.from(bytes)
12 .map((b) => b.toString(16).padStart(2, "0"))
13 .join("");
14}
15 
16/**
17 * Convert hex string to bytes
18 * @param hex - Hex string (case insensitive)
19 * @returns Uint8Array of bytes
20 */
21export function hexToBytes(hex: string): Uint8Array {
22 if (hex.length % 2 !== 0) {
23 throw new Error("Invalid hex string: odd length");
24 }
25 const bytes = new Uint8Array(hex.length / 2);
26 for (let i = 0; i < hex.length; i += 2) {
27 bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
28 }
29 return bytes;
30}
31 
32/**
33 * Check if a string is a valid Git OID (40 hex chars)
34 * @param oid - String to check
35 * @returns true if valid Git OID
36 */
37export function isValidOid(oid: string): boolean {
38 return /^[0-9a-f]{40}$/i.test(oid);
39}
40 
41/**
42 * Get the zero OID (40 zeros)
43 * @returns "0000000000000000000000000000000000000000"
44 */
45export function zeroOid(): string {
46 return "0".repeat(40);
47}