TExcelTAD
Home › WebAssembly › Mini Project: Prime Sieve & Image Filter

Mini Project: Prime Sieve & Image Filter

In this project you'll write two classic WebAssembly workloads by hand in WAT, then drive them from JavaScript the way a real web app would:

  1. a Sieve of Eratosthenes that finds prime numbers using a byte array in linear memory,
  2. an image filter kernel that converts RGBA pixels to grayscale (and brightens them with SIMD),
  3. a JavaScript host that fills memory, calls the kernels and reads the results back.

Each step is a complete, runnable program. Along the way you'll use loops, memory, bulk memory, data segments, SIMD and the JavaScript API.

Step 1: The sieve idea

To find all primes below n, start with every number marked "maybe prime". For each i from 2 while i * i < n, if i is still marked, cross out its multiples starting at i * i. Whatever stays marked is prime.

We store one flag byte per number: the flag for number k lives at address k. memory.fill marks them all in one instruction.

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (memory 1)

  (func $sieve (param $n i32)
    (local $i i32) (local $j i32)
    (memory.fill (i32.const 0) (i32.const 1) (local.get $n))     ;; flags[0..n) = 1
    (local.set $i (i32.const 2))
    (block $done (loop $outer
      (br_if $done (i32.gt_u (i32.mul (local.get $i) (local.get $i)) (local.get $n)))
      (if (i32.load8_u (local.get $i))                            ;; i is prime?
        (then
          (local.set $j (i32.mul (local.get $i) (local.get $i)))
          (block $d2 (loop $cross
            (br_if $d2 (i32.ge_u (local.get $j) (local.get $n)))
            (i32.store8 (local.get $j) (i32.const 0))               ;; j is not prime
            (local.set $j (i32.add (local.get $j) (local.get $i)))
            (br $cross)))))
      (local.set $i (i32.add (local.get $i) (i32.const 1)))
      (br $outer))))

  (func (export "main")
    (local $k i32)
    (call $sieve (i32.const 50))
    (local.set $k (i32.const 2))
    (loop $print
      (if (i32.load8_u (local.get $k)) (then (call $log (local.get $k))))
      (local.set $k (i32.add (local.get $k) (i32.const 1)))
      (br_if $print (i32.lt_u (local.get $k) (i32.const 50))))))
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Step 2: Counting primes and printing a report

Printing hundreds of numbers isn't useful. Let's count primes below several limits and print a text report with console.str, formatting the numbers ourselves (the utoa routine from Data Segments & Strings). The flags live from address 1024 so that the text buffers at the start of memory stay intact.

wat · try it yourself
(module
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (global $FLAGS i32 (i32.const 1024))
  (data (i32.const 0) "primes below ")
  (data (i32.const 16) ": ")

  (func $count_primes (param $n i32) (result i32)
    (local $i i32) (local $j i32) (local $count i32)
    (memory.fill (global.get $FLAGS) (i32.const 1) (local.get $n))
    (local.set $i (i32.const 2))
    (block $done (loop $outer
      (br_if $done (i32.gt_u (i32.mul (local.get $i) (local.get $i)) (local.get $n)))
      (if (i32.load8_u (i32.add (global.get $FLAGS) (local.get $i)))
        (then
          (local.set $j (i32.mul (local.get $i) (local.get $i)))
          (block $d2 (loop $cross
            (br_if $d2 (i32.ge_u (local.get $j) (local.get $n)))
            (i32.store8 (i32.add (global.get $FLAGS) (local.get $j)) (i32.const 0))
            (local.set $j (i32.add (local.get $j) (local.get $i)))
            (br $cross)))))
      (local.set $i (i32.add (local.get $i) (i32.const 1)))
      (br $outer)))
    (local.set $i (i32.const 2))
    (block $done (loop $tally
      (br_if $done (i32.ge_u (local.get $i) (local.get $n)))
      (local.set $count (i32.add (local.get $count)
        (i32.load8_u (i32.add (global.get $FLAGS) (local.get $i)))))
      (local.set $i (i32.add (local.get $i) (i32.const 1)))
      (br $tally)))
    (local.get $count))

  ;; write the digits of $n ending at $end; returns the start address
  (func $utoa (param $n i32) (param $end i32) (result i32)
    (loop $digit
      (local.set $end (i32.sub (local.get $end) (i32.const 1)))
      (i32.store8 (local.get $end) (i32.add (i32.const 48) (i32.rem_u (local.get $n) (i32.const 10))))
      (local.set $n (i32.div_u (local.get $n) (i32.const 10)))
      (br_if $digit (local.get $n)))
    (local.get $end))

  ;; build "primes below N: C" at address 64 and print it
  (func $report (param $n i32)
    (local $s i32) (local $len i32) (local $at i32)
    (memory.copy (i32.const 64) (i32.const 0) (i32.const 13))
    (local.set $at (i32.const 77))
    (local.set $s (call $utoa (local.get $n) (i32.const 200)))
    (local.set $len (i32.sub (i32.const 200) (local.get $s)))
    (memory.copy (local.get $at) (local.get $s) (local.get $len))
    (local.set $at (i32.add (local.get $at) (local.get $len)))
    (memory.copy (local.get $at) (i32.const 16) (i32.const 2))
    (local.set $at (i32.add (local.get $at) (i32.const 2)))
    (local.set $s (call $utoa (call $count_primes (local.get $n)) (i32.const 200)))
    (local.set $len (i32.sub (i32.const 200) (local.get $s)))
    (memory.copy (local.get $at) (local.get $s) (local.get $len))
    (local.set $at (i32.add (local.get $at) (local.get $len)))
    (call $print (i32.const 64) (i32.sub (local.get $at) (i32.const 64))))

  (func (export "main")
    (call $report (i32.const 10))
    (call $report (i32.const 100))
    (call $report (i32.const 1000))
    (call $report (i32.const 10000))
    (call $report (i32.const 60000))))
primes below 10: 4
primes below 100: 25
primes below 1000: 168
primes below 10000: 1229
primes below 60000: 6057

The flags for n = 60000 end at address 61024, still inside the single 64 KiB page. For bigger limits you'd grow memory first, or store one bit per number instead of a byte.

Step 3: A grayscale kernel

Images on the web are arrays of RGBA bytes: red, green, blue, alpha for each pixel. A grayscale filter replaces R, G and B with a weighted brightness. With integer weights that add up to 256, the division becomes a shift:

text
gray = (77 * R + 150 * G + 29 * B) >> 8

Here are four test pixels (red, green, blue, white) in a data segment:

wat · try it yourself
(module
  (import "console" "log" (func $log4 (param i32 i32 i32 i32)))
  (memory 1)
  (data (i32.const 0) "\ff\00\00\ff" "\00\ff\00\ff" "\00\00\ff\ff" "\ff\ff\ff\ff")

  (func $grayscale (param $p i32) (param $count i32)
    (local $g i32)
    (block $done (loop $next
      (br_if $done (i32.eqz (local.get $count)))
      (local.set $g (i32.shr_u
        (i32.add (i32.add
          (i32.mul (i32.load8_u (local.get $p)) (i32.const 77))
          (i32.mul (i32.load8_u offset=1 (local.get $p)) (i32.const 150)))
          (i32.mul (i32.load8_u offset=2 (local.get $p)) (i32.const 29)))
        (i32.const 8)))
      (i32.store8 (local.get $p) (local.get $g))
      (i32.store8 offset=1 (local.get $p) (local.get $g))
      (i32.store8 offset=2 (local.get $p) (local.get $g))   ;; alpha (offset 3) is untouched
      (local.set $p (i32.add (local.get $p) (i32.const 4)))
      (local.set $count (i32.sub (local.get $count) (i32.const 1)))
      (br $next))))

  (func $show (param $p i32)
    (call $log4 (i32.load8_u (local.get $p)) (i32.load8_u offset=1 (local.get $p))
                 (i32.load8_u offset=2 (local.get $p)) (i32.load8_u offset=3 (local.get $p))))

  (func (export "main")
    (call $grayscale (i32.const 0) (i32.const 4))
    (call $show (i32.const 0))
    (call $show (i32.const 4))
    (call $show (i32.const 8))
    (call $show (i32.const 12))))
76 76 76 255
149 149 149 255
28 28 28 255
255 255 255 255

Green looks brightest to the human eye, so it gets the largest weight. White stays (almost) white: 77 + 150 + 29 = 256, and 255 × 256 >> 8 = 255.

Step 4: Brightening 4 pixels at a time with SIMD

A brightness filter adds a constant to every colour byte. With i8x16.add_sat_u one instruction processes 16 bytes (4 pixels) and clamps at 255 instead of wrapping. To leave alpha alone we add a vector whose alpha lanes are 0:

wat · try it yourself
(module
  (import "console" "log" (func $log4 (param i32 i32 i32 i32)))
  (memory 1)
  ;; 8 pixels: a dark-to-light ramp
  (data (i32.const 0)
    "\10\10\10\ff" "\30\30\30\ff" "\50\50\50\ff" "\70\70\70\ff"
    "\90\90\90\ff" "\b0\b0\b0\ff" "\d0\d0\d0\ff" "\f0\f0\f0\ff")

  (func $brighten (param $p i32) (param $pixels i32) (param $amount i32)
    (local $add v128)
    ;; amount in R, G, B lanes; 0 in every alpha lane
    (local.set $add (v128.and
      (i8x16.splat (local.get $amount))
      (v128.const i32x4 0x00ffffff 0x00ffffff 0x00ffffff 0x00ffffff)))
    (block $done (loop $next
      (br_if $done (i32.lt_s (local.get $pixels) (i32.const 4)))      ;; 4 pixels per step
      (v128.store (local.get $p) (i8x16.add_sat_u (v128.load (local.get $p)) (local.get $add)))
      (local.set $p (i32.add (local.get $p) (i32.const 16)))
      (local.set $pixels (i32.sub (local.get $pixels) (i32.const 4)))
      (br $next))))

  (func (export "main")
    (local $i i32)
    (call $brighten (i32.const 0) (i32.const 8) (i32.const 0x40))
    (loop $show
      (call $log4 (i32.load8_u (local.get $i)) (i32.load8_u offset=1 (local.get $i))
                   (i32.load8_u offset=2 (local.get $i)) (i32.load8_u offset=3 (local.get $i)))
      (local.set $i (i32.add (local.get $i) (i32.const 4)))
      (br_if $show (i32.lt_u (local.get $i) (i32.const 32))))))
80 80 80 255
112 112 112 255
144 144 144 255
176 176 176 255
208 208 208 255
240 240 240 255
255 255 255 255
255 255 255 255

Little-endian strikes again: in the i32x4 constant 0x00ffffff, the 00 byte is the highest one, which is stored last, at the alpha position. The last two pixels hit the 255 ceiling instead of wrapping around.

Step 5: Driving the kernels from JavaScript

Now the real-world setup. The final module exports its memory plus sieve(n) (flags at address 0, returns the count) and grayscale(ptr, count), written exactly as in steps 2 and 3. JavaScript:

  • calls sieve and reads the prime flags directly from memory,
  • builds a small "image" (a colour gradient) in Wasm memory with a Uint8Array view,
  • runs grayscale on it and renders the result as ASCII art.
wat
(module
  (memory (export "memory") 1)
  (func (export "sieve") (param $n i32) (result i32) …)          ;; step 1 + counting, flags at 0
  (func (export "grayscale") (param $p i32) (param $count i32) …))   ;; step 3
js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x0b, 0x02, 0x60, 0x01, 0x7f, 0x01, 0x7f, 0x60, 0x02, 0x7f, 0x7f, 0x00,
  0x03, 0x03, 0x02, 0x00, 0x01,
  0x05, 0x03, 0x01, 0x00, 0x01,
  0x07, 0x1e, 0x03, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x05, 0x73,
  0x69, 0x65, 0x76, 0x65, 0x00, 0x00, 0x09, 0x67, 0x72, 0x61, 0x79, 0x73, 0x63, 0x61,
  0x6c, 0x65, 0x00, 0x01,
  0x0a, 0xd4, 0x01, 0x02, 0x7c, 0x01, 0x03, 0x7f, 0x41, 0x00, 0x41, 0x01, 0x20, 0x00,
  0xfc, 0x0b, 0x00, 0x41, 0x02, 0x21, 0x01, 0x02, 0x40, 0x03, 0x40, 0x20, 0x01, 0x20,
  0x01, 0x6c, 0x20, 0x00, 0x4b, 0x0d, 0x01, 0x20, 0x01, 0x2d, 0x00, 0x00, 0x04, 0x40,
  0x20, 0x01, 0x20, 0x01, 0x6c, 0x21, 0x02, 0x02, 0x40, 0x03, 0x40, 0x20, 0x02, 0x20,
  0x00, 0x4f, 0x0d, 0x01, 0x20, 0x02, 0x41, 0x00, 0x3a, 0x00, 0x00, 0x20, 0x02, 0x20,
  0x01, 0x6a, 0x21, 0x02, 0x0c, 0x00, 0x0b, 0x0b, 0x0b, 0x20, 0x01, 0x41, 0x01, 0x6a,
  0x21, 0x01, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x02, 0x21, 0x01, 0x02, 0x40, 0x03, 0x40,
  0x20, 0x01, 0x20, 0x00, 0x4f, 0x0d, 0x01, 0x20, 0x03, 0x20, 0x01, 0x2d, 0x00, 0x00,
  0x6a, 0x21, 0x03, 0x20, 0x01, 0x41, 0x01, 0x6a, 0x21, 0x01, 0x0c, 0x00, 0x0b, 0x0b,
  0x20, 0x03, 0x0b, 0x55, 0x01, 0x01, 0x7f, 0x02, 0x40, 0x03, 0x40, 0x20, 0x01, 0x45,
  0x0d, 0x01, 0x20, 0x00, 0x2d, 0x00, 0x00, 0x41, 0xcd, 0x00, 0x6c, 0x20, 0x00, 0x2d,
  0x00, 0x01, 0x41, 0x96, 0x01, 0x6c, 0x6a, 0x20, 0x00, 0x2d, 0x00, 0x02, 0x41, 0x1d,
  0x6c, 0x6a, 0x41, 0x08, 0x76, 0x21, 0x02, 0x20, 0x00, 0x20, 0x02, 0x3a, 0x00, 0x00,
  0x20, 0x00, 0x20, 0x02, 0x3a, 0x00, 0x01, 0x20, 0x00, 0x20, 0x02, 0x3a, 0x00, 0x02,
  0x20, 0x00, 0x41, 0x04, 0x6a, 0x21, 0x00, 0x20, 0x01, 0x41, 0x01, 0x6b, 0x21, 0x01,
  0x0c, 0x00, 0x0b, 0x0b, 0x0b,
]);

const { instance } = await WebAssembly.instantiate(bytes);
const { memory, sieve, grayscale } = instance.exports;

// 1. primes: call once, then read the flag bytes straight from memory
const count = sieve(100);
const flags = new Uint8Array(memory.buffer, 0, 100);
const primes = [];
for (let k = 2; k < 100; k++) if (flags[k]) primes.push(k);
console.log(`${count} primes below 100:`, primes.join(' '));
console.log('primes below 30000:', sieve(30000));

// 2. image: a 16 x 6 gradient, red increasing left to right, blue top to bottom
const width = 16, height = 6, IMAGE = 32768;            // pixels live above the sieve's flags
const pixels = new Uint8Array(memory.buffer, IMAGE, width * height * 4);
for (let y = 0; y < height; y++) {
  for (let x = 0; x < width; x++) {
    const i = (y * width + x) * 4;
    pixels[i] = x * 17;            // R: 0..255
    pixels[i + 1] = 40;            // G
    pixels[i + 2] = y * 51;        // B: 0..255
    pixels[i + 3] = 255;           // A
  }
}
grayscale(IMAGE, width * height);

// 3. render: map brightness 0..255 to characters
const shades = ' .:-=+*#%@';
for (let y = 0; y < height; y++) {
  let row = '';
  for (let x = 0; x < width; x++) {
    const gray = pixels[(y * width + x) * 4];
    row += shades[Math.floor((gray * shades.length) / 256)];
  }
  console.log(row);
}
console.log('top-left gray:', pixels[0], 'bottom-right gray:', pixels[(width * height - 1) * 4]);
25 primes below 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
primes below 30000: 3245
 .....:::::-----
.....:::::-----=
....:::::-----==
...:::::-----===
..::::------====
:::::-----=====+
top-left gray: 23 bottom-right gray: 129

In a browser you'd take the same pixels view, wrap it as new ImageData(new Uint8ClampedArray(memory.buffer, IMAGE, width * height * 4), width, height) and draw it on a canvas with putImageData, with no copying of the pixel data at all.

Ideas to extend the project

  • Bit-packed sieve: store 8 numbers per byte (i32.shr_u/i32.and to find the bit) and grow memory for limits above 500,000.
  • SIMD grayscale: process 4 pixels per iteration with i16x8 multiplies.
  • Convolution: a 3×3 box blur reading neighbouring pixels (watch the image edges!).
  • Workers: compile the module once, send it to a Web Worker and run the filter off the main thread.
  • Toolchains: rewrite the kernels in C or Rust, compile them to Wasm, and compare the generated WAT with yours.

Test yourself

Why does the sieve start crossing out multiples of i at i * i?

  1. Because i * i is always prime
  2. Smaller multiples k * i with k < i were already crossed out when processing k's prime factors
  3. To avoid a trap
  4. It's required by memory.fill

In the grayscale formula, why do the weights 77 + 150 + 29 add up to 256?

  1. So that >> 8 divides by 256 and white stays 255
  2. Because there are 256 pixels
  3. To match the alpha channel
  4. It's a SIMD requirement

How does JavaScript read the results of grayscale without copying?

  1. The function returns an array
  2. Through a Uint8Array view on memory.buffer
  3. With JSON
  4. By calling memory.read()