Remove duplicate code

This commit is contained in:
2026-10-13 11:57:43 -03:00
parent dfc6a6d77b
commit 5165698fe3
50 changed files with 307 additions and 812 deletions
+6 -8
View File
@@ -6,6 +6,7 @@
import { AIR, ID_MASK } from "$/common/constants.ts";
import type { RawChunk } from "$/common/generation.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { sha256 } from "$/common/utils.ts";
export const FIXTURE = new URL("./fixtures/worldgen_golden.json", import.meta.url);
export const SEEDS = ["golden-1", "golden-2", "golden-3"];
@@ -40,12 +41,12 @@ export function raw_hash(raw: RawChunk, name: (value: number) => string): Promis
for (let i = 0; i < raw.spills.length; i += 4) {
spills.push(raw.spills[i], raw.spills[i + 1], raw.spills[i + 2], name(raw.spills[i + 3]));
}
return sha256(blocks_text(raw.blocks, name), JSON.stringify(spills), raw.biomes.join(","));
return hash(blocks_text(raw.blocks, name), JSON.stringify(spills), raw.biomes.join(","));
}
// what the fixture's "final" is: the chunk with its neighbors' spills
export function final_hash(blocks: Uint32Array, name: (value: number) => string): Promise<string> {
return sha256(blocks_text(blocks, name));
return hash(blocks_text(blocks, name));
}
// the blocks as a palette of names in the order they first appear, then each block's place in it
@@ -63,7 +64,8 @@ function blocks_text(blocks: Uint32Array, name: (value: number) => string): (str
return [JSON.stringify([...palette.keys()].map(name)), new Uint8Array(indices.buffer)];
}
async function sha256(...parts: (string | Uint8Array | (string | Uint8Array)[])[]) {
// the sha-256 of the parts one after another, strings each on their own line
function hash(...parts: (string | Uint8Array | (string | Uint8Array)[])[]) {
const bytes = parts.flat().map((part) => typeof part === "string" ? new TextEncoder().encode(part + "\n") : part);
const all = new Uint8Array(bytes.reduce((sum, part) => sum + part.length, 0));
let offset = 0;
@@ -71,9 +73,5 @@ async function sha256(...parts: (string | Uint8Array | (string | Uint8Array)[])[
all.set(part, offset);
offset += part.length;
}
let hex = "";
for (const byte of new Uint8Array(await crypto.subtle.digest("SHA-256", all))) {
hex += byte.toString(16).padStart(2, "0");
}
return hex;
return sha256(all);
}