Skip to content

Instantly share code, notes, and snippets.

@skeeto
Created May 22, 2025 19:39
Show Gist options
  • Save skeeto/b3de82b3fca49f4bc50a9787fd7f9d60 to your computer and use it in GitHub Desktop.
Save skeeto/b3de82b3fca49f4bc50a9787fd7f9d60 to your computer and use it in GitHub Desktop.
Staz Wasm
#!/bin/sh
set -ex
clang --target=wasm32 -nostdlib -O2 -fno-builtin -Wl,--no-entry -o staz.wasm wasm.c
import random
import statistics
import struct
import wasm3
def load():
env = wasm3.Environment()
runtime = env.new_runtime(2**12)
with open("staz.wasm", "rb") as f:
runtime.load(env.parse_module(f.read()))
return (
lambda: runtime.get_memory(0),
runtime.find_function("alloc"),
runtime.find_function("freeall"),
runtime.find_function("deviation"),
)
getmemory, alloc, freeall, deviation = load()
rng = random.Random(1234)
nums = [rng.normalvariate() for _ in range(10**3)]
ptr = alloc(len(nums))
memory = getmemory()
for i, num in enumerate(nums):
struct.pack_into("<d", memory, ptr + 8*i, num)
print("want", statistics.stdev(nums))
print("got ", deviation(ptr, len(nums)))
freeall()
diff --git a/staz.h b/staz.h
index 650fbd0..9ce3854 100644
--- a/staz.h
+++ b/staz.h
@@ -13,16 +13,6 @@
#ifndef STAZ_H
#define STAZ_H
-#include <stdio.h>
-#include <stdlib.h>
-#include <math.h>
-#include <errno.h>
-#include <string.h>
-
-#ifdef __cplusplus
- #include <cstddef> // for size_t
-#endif
-
/**
* @brief Compute a root of customizable index
* @param i The index of the root to compute
#define inline
#define NULL (void *)0
#define NAN __builtin_nanf("")
#define memcpy __builtin_memcpy
#define isnan __builtin_isnan
#define sqrt __builtin_sqrt
#define pow __builtin_pow
#define fabs __builtin_fabs
#define qsort(a,b,c,d) __builtin_trap() // TODO
#define free(p)
#define fprintf(...)
typedef unsigned long size_t;
static int errno;
static void *malloc(size_t);
#include "staz.h"
extern char __heap_base[];
static size_t heap_used;
static size_t heap_cap;
static void *malloc(size_t len)
{
if (len > heap_cap - heap_used) {
size_t needed = len - (heap_cap - heap_used);
size_t npages = (needed + 0xffff) >> 16; // round up
if (__builtin_wasm_memory_grow(0, npages) == (size_t)-1) {
return 0; // out of memory
}
heap_cap += npages << 16;
}
void *r = __heap_base + heap_used; // TODO align
heap_used += len;
return r;
}
__attribute((export_name("alloc")))
double *wasm_alloc(size_t len)
{
if (len > (size_t)-1/sizeof(double)) {
return 0;
}
return malloc(len * sizeof(double));
}
__attribute((export_name("freeall")))
void wasm_freeall(void)
{
heap_used = 0;
}
__attribute((export_name("deviation")))
double wasm_deviation(double *p, size_t len)
{
return staz_deviation(D_STANDARD, p, len);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment