Skip to content

Commit

Permalink
fix(stdlib): Avoid WASI random_get in Hash stdlib during module start…
Browse files Browse the repository at this point in the history
…up (#2078)
  • Loading branch information
ospencer authored Mar 28, 2024
1 parent 6fd1603 commit 7eadfb0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
18 changes: 15 additions & 3 deletions stdlib/hash.gr
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,15 @@ from "wasi/random" include Random
from "result" include Result

@unsafe
let seed = {
let mut seed = 0n

@unsafe
let initalize = () => {
// Delay initialization to the first call to `hash` to prevent WASI calls
// during startup
let random = Random.random()
coerceNumberToWasmI32(Result.unwrap(random))
seed = coerceNumberToWasmI32(Result.unwrap(random))
seed
}

@unsafe
Expand Down Expand Up @@ -239,6 +245,8 @@ let rec hashOne = (val, depth) => {
*
* @param anything: The value to hash
* @returns A hash for the given value
*
* @throws Failure(String): If WASI random_get fails
*
* @example assert Hash.hash(1) == Hash.hash(1)
* @example assert Hash.hash("Hello World") == Hash.hash("Hello World")
Expand All @@ -247,7 +255,11 @@ let rec hashOne = (val, depth) => {
*/
@unsafe
provide let hash = anything => {
h = seed
h = if (WasmI32.eqz(seed)) {
initalize()
} else {
seed
}

hashOne(WasmI32.fromGrain(anything), 0n)
finalize(0n)
Expand Down
6 changes: 6 additions & 0 deletions stdlib/hash.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ Returns:
|----|-----------|
|`Number`|A hash for the given value|

Throws:

`Failure(String)`

* If WASI random_get fails

Examples:

```grain
Expand Down

0 comments on commit 7eadfb0

Please sign in to comment.