# knotkit/hash

> Computes deterministic non-cryptographic XXH64 hashes, identical across browsers, Node.js, and Bun

## Use

```ts
import { xxh64 } from 'knotkit/hash'

const hash = xxh64()
const digest = hash.string('hello')

digest // 0x26c7_827d_889f_6da3n
hash.encodeHex(digest) // '26c7827d889f6da3'
// Uint8Array [0x26, 0xc7, 0x82, 0x7d, 0x88, 0x9f, 0x6d, 0xa3]
hash.encode(digest)
```

```ts
const seeded = xxh64(0x0123_4567_89ab_cdefn)

seeded.bytes(Uint8Array.of(1, 2, 3))
seeded.uint32(42)
seeded.uint64(42n)

const state = seeded.create()
state.update(new TextEncoder().encode('hel'))
state.update(new TextEncoder().encode('lo'))
state.digest() // same as seeded.string('hello')
```

## What it solves

* fingerprint bytes, text, or an unsigned integer the same way in every browser, Node.js, and Bun runtime
* shard keys across buckets or deduplicate records by a cheap fingerprint
* hash table keys without allocating or retaining a copy of the input
* reproduce earlier digests in a later process from a persisted algorithm version and seed
* hash a large payload chunk by chunk without holding it all in memory

## Worked example

Inputs swept6464Reset

* XXH64 of "Knotkit!" at seed 0: c5398de0ce53a5f6.
* Flipping each input bit in turn changed between 26 and 41 digest bits.
* Across 4,096 one-bit flips of 64 inputs: mean 32.0 changed bits, SD 4.1. A fair coin per bit gives 32 and 4.
* Use this deterministic fingerprint to identify bytes. Use a cryptographic hash for adversarial inputs.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/hash/demo.ts) against `knotkit/hash` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                    | Returns                               | Does                                                                                                                                                                |
| ------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`xxh64`](/reference/knotkit/hash/functions/xxh64/)                       | `ScalarHash<'xxh64', bigint, bigint>` | Frozen one-shot XXH64 value over bytes, text, \`uint32\`, and \`uint64\`, plus \`create()\` for an independent incremental byte state; the seed defaults to \`0n\`. |
| [`hashFromIdentity`](/reference/knotkit/hash/functions/hashfromidentity/) | `ScalarHash<'xxh64', bigint, bigint>` | Restore the current implementation matching a validated hash identity, so a persisted version and seed reproduce the same digests.                                  |

Cost per member. Open a row for every operation.

`xxh64` 14 members

| Member       | Cost |
| ------------ | ---- |
| `kind`       | O(1) |
| `version`    | O(1) |
| `seed`       | O(1) |
| `bytes`      | O(n) |
| `string`     | O(n) |
| `uint32`     | O(1) |
| `uint64`     | O(1) |
| `bytesInto`  | O(n) |
| `stringInto` | O(n) |
| `uint32Into` | O(1) |
| `uint64Into` | O(1) |
| `create`     | O(1) |
| `encode`     | O(1) |
| `encodeHex`  | O(1) |

## Errors

Every error this module throws is `HashInvalidInputError` or `HashParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `HashInvalidInputError`

  `INVALID_SEED`

* `HashParseError`

  `INVALID_BYTES` `INVALID_STRING` `INVALID_UINT32` `INVALID_UINT64` `INVALID_CHUNK` `INVALID_OUTPUT` `INVALID_DIGEST` `INPUT_TOO_LONG` `STATE_FINALIZED` `INVALID_SHAPE` `UNKNOWN_KIND` `UNSUPPORTED_VERSION`

## Save and restore

Serialization lives in a separate entrypoint, `knotkit/hash/wire`, so code that never saves a structure never loads a parser.

* Functions

  `serializeHashIdentity`, `deserializeHashIdentity`

* Formats

  json

* Compatibility

  identity-versioned; deserializeHashIdentity rejects an identity whose version is not HASH_IDENTITY_VERSION, which changes only when the digest mapping changes, never with a release, envelope v

## When not to use it

| If you need to…                                                         | Use instead                                                           |
| ----------------------------------------------------------------------- | --------------------------------------------------------------------- |
| hash a password, sign a message, or authenticate data with a secret     | crypto.subtle from Web Crypto                                         |
| resist collisions from an adversary who chooses the input               | SHA-256 through crypto.subtle in Web Crypto                           |
| count distinct values, or estimate their frequencies, in bounded memory | [`knotkit/scalar-sketch`](/modules/scalar-sketch/)                    |
| checksum a large artifact at maximum throughput                         | the xxhash-wasm package, which runs the same algorithm in WebAssembly |
| persist a whole data structure and re-read it later                     | the structure package's serialize function                            |

## Performance

Measured by the suite in [`packages/hash/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/hash/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/hashCopy prompt

```
Use knotkit/hash for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/hash'.

Exports:
- `xxh64` → `ScalarHash<'xxh64', bigint, bigint>`: Frozen one-shot XXH64 value over bytes, text, `uint32`, and `uint64`, plus `create()` for an independent incremental byte state; the seed defaults to `0n`.
- `hashFromIdentity` → `ScalarHash<'xxh64', bigint, bigint>`: Restore the current implementation matching a validated hash identity, so a persisted version and seed reproduce the same digests.

Use something else when:
- hash a password, sign a message, or authenticate data with a secret → crypto.subtle from Web Crypto
- resist collisions from an adversary who chooses the input → SHA-256 through crypto.subtle in Web Crypto
- count distinct values, or estimate their frequencies, in bounded memory → knotkit/scalar-sketch
- checksum a large artifact at maximum throughput → the xxhash-wasm package, which runs the same algorithm in WebAssembly
- persist a whole data structure and re-read it later → the structure package's serialize function

Errors are HashInvalidInputError or HashParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/hash/wire` (serializeHashIdentity, deserializeHashIdentity).

Full page: https://knotkit.jkomyno.dev/modules/hash.md
Types: node_modules/knotkit/hash/ and https://knotkit.jkomyno.dev/reference/knotkit/hash/
```

## See also

* [API reference](/reference/knotkit/hash/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/hash/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/hash/knotkit.capability.json)suggest a change to the source record
