Skip to content

Commit

Permalink
feat(stdlib)!: Add ability to set seed on Hash.hash
Browse files Browse the repository at this point in the history
  • Loading branch information
spotandjake committed Jan 2, 2024
1 parent 3c0ea18 commit 504dabf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
14 changes: 9 additions & 5 deletions stdlib/hash.gr
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@ include "runtime/bigint" as BI
include "sys/random"
include "result"

@unsafe
let seed = {
let random = Random.random()
coerceNumberToWasmI32(Result.unwrap(random))
Result.unwrap(random)
}

@unsafe
Expand All @@ -64,7 +63,7 @@ let m = 5n
let n = 0xe6546b64n

@unsafe
let mut h = seed
let mut h = coerceNumberToWasmI32(seed)

@unsafe
let hash32 = k => {
Expand Down Expand Up @@ -240,13 +239,18 @@ let rec hashOne = (val, depth) => {
* A generic hash function that produces an integer from any value. If `a == b` then `Hash.hash(a) == Hash.hash(b)`.
*
* @param anything: The value to hash
* @param seed: The seed to use
* @returns A hash for the given value
*
* @example Hash.hash(a) == Hash.hash(a)
* @example Hash.hash(a, seed=1) == -1015171190
*
* @since v0.1.0
* @history v0.6.0: Added ability to set the seed
*/
@unsafe
provide let hash = anything => {
h = seed
provide let hash = (anything, seed=seed) => {
h = coerceNumberToWasmI32(seed)

hashOne(WasmI32.fromGrain(anything), 0n)
finalize(0n)
Expand Down
26 changes: 22 additions & 4 deletions stdlib/hash.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,20 @@ Functions and constants included in the Hash module.

### Hash.**hash**

<details disabled>
<summary tabindex="-1">Added in <code>0.1.0</code></summary>
No other changes yet.
<details>
<summary>Added in <code>0.1.0</code></summary>
<table>
<thead>
<tr><th>version</th><th>changes</th></tr>
</thead>
<tbody>
<tr><td><code>next</code></td><td>Added ability to set the seed</td></tr>
</tbody>
</table>
</details>

```grain
hash : (anything: a) => Number
hash : (anything: a, ?seed: Number) => Number
```

A generic hash function that produces an integer from any value. If `a == b` then `Hash.hash(a) == Hash.hash(b)`.
Expand All @@ -35,10 +42,21 @@ Parameters:
|param|type|description|
|-----|----|-----------|
|`anything`|`a`|The value to hash|
|`seed`|`Option<Number>`|The seed to use|

Returns:

|type|description|
|----|-----------|
|`Number`|A hash for the given value|

Examples:

```grain
Hash.hash(a) == Hash.hash(a)
```

```grain
Hash.hash(a, seed=1) == -1015171190
```

0 comments on commit 504dabf

Please sign in to comment.