Skip to content

Commit

Permalink
refactor: fnv1a52
Browse files Browse the repository at this point in the history
  • Loading branch information
kwaa committed Oct 14, 2023
1 parent 5918bbc commit 30a97bb
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 10 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
"crypto-js": "^4.1.1",
"eslint": "^8.51.0",
"jsdom": "^22.1.0",
"ohash": "^1.1.3",
"tsup": "^7.2.0",
"tsx": "^3.13.0",
"vite": "^4.4.11",
Expand Down
7 changes: 0 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/fingerprint.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// eslint-disable-next-line n/no-unpublished-import
import { murmurHash } from 'ohash'
import { fnv1a52 } from '~/lib/fnv1a52.ts'

/** {@link https://browserleaks.com/canvas#how-does-it-work} */
export const getFingerprint = () => {
Expand All @@ -25,7 +25,7 @@ export const getFingerprint = () => {
// TODO: test
ctx.clearRect(0, 0, canvas.width, canvas.height)

return murmurHash(fingerprint, 256)
return fnv1a52(fingerprint)
}
catch {
return
Expand Down
46 changes: 46 additions & 0 deletions src/lib/fnv1a52.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* eslint-disable tsdoc/syntax */
/**
* FNV-1a Hash implementation
* @author Travis Webb (tjwebb) <me@traviswebb.com>
*
* Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js
*
* Simplified, optimized and add modified for 52 bit, which provides a larger hash space
* and still making use of Javascript's 53-bit integer space.
*/
export const fnv1a52 = (str: string) => {
const len = str.length
let i = 0,
t0 = 0,
v0 = 0x23_25,
t1 = 0,
v1 = 0x84_22,
t2 = 0,
v2 = 0x9C_E4,
t3 = 0,
v3 = 0xCB_F2

while (i < len) {
v0 ^= str.codePointAt(i++)!
t0 = v0 * 435
t1 = v1 * 435
t2 = v2 * 435
t3 = v3 * 435
t2 += v0 << 8
t3 += v1 << 8
t1 += t0 >>> 16
v0 = t0 & 65_535
t2 += t1 >>> 16
v1 = t1 & 65_535
v3 = (t3 + (t2 >>> 16)) & 65_535
v2 = t2 & 65_535
}

return (
(v3 & 15) * 281_474_976_710_656
+ v2 * 4_294_967_296
+ v1 * 65_536
+ (v0 ^ (v3 >> 4))
)
}
/* eslint-enable tsdoc/syntax */

0 comments on commit 30a97bb

Please sign in to comment.