Skip to content

Commit

Permalink
Merge pull request #360 from katywings/fix-hashing
Browse files Browse the repository at this point in the history
fix: hash chunks with djb2
  • Loading branch information
nksaraf authored Sep 3, 2024
2 parents f62ce9e + f0a1c26 commit 3925cf3
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/tough-timers-admire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"vinxi": patch
---

fix: hash chunks with djb2
30 changes: 21 additions & 9 deletions packages/vinxi/lib/chunks.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { readFileSync } from "fs";
import { join } from "vinxi/lib/path";

import { viteManifestPath } from "./manifest-path.js";
import { join } from "./path.js";

const CHUNK_PREFIX = "c_";

Expand Down Expand Up @@ -57,19 +57,31 @@ export const chunksServerVirtualModule =
`;
};

const hashes = new Map();
const regexReturnCharacters = /\r/g;

/**
* djb2 hashing
*
* @param {string} str
* @returns
* @param {string} input
* @returns {string}
*
* Source: https://github.com/sveltejs/svelte/blob/0203eb319b5d86138236158e3ae6ecf29e26864c/packages/svelte/src/utils.js#L7
* Source License: MIT
*/
export function hash(str) {
let hash = 0;
export function hash(input) {
const cachedResult = hashes.get(input);
if (cachedResult) return cachedResult;

for (let i = 0; i < str.length; i++) {
hash += str.charCodeAt(i);
}
let str = input.replace(regexReturnCharacters, "");
let hash = 5381;
let i = str.length;

while (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
const result = (hash >>> 0).toString(36);
hashes.set(input, result);

return hash;
return result;
}

/**
Expand Down
9 changes: 9 additions & 0 deletions packages/vinxi/lib/chunks.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { describe, expect, it } from "vitest";

import { hash } from "./chunks";

describe("hash", () => {
it("should create different hashes for abc and cba", () => {
expect(hash("abc")).not.toEqual(hash("cba"));
});
});

0 comments on commit 3925cf3

Please sign in to comment.