Skip to content

Instantly share code, notes, and snippets.

@ymyzk
Last active July 20, 2019 14:49
Show Gist options
  • Save ymyzk/0405793cb3df537c7bd8b8aacb8aa577 to your computer and use it in GitHub Desktop.
Save ymyzk/0405793cb3df537c7bd8b8aacb8aa577 to your computer and use it in GitHub Desktop.
Bubble Sort in WebAssembly

Bubble Sort in WebAssembly

  1. python3 server.py
  2. Open http://localhost:8000 with Chrome, Edge, or Firefox
  3. Open the console in your browser
const MAX_NUM = 1 << 16;
const SIZE = 32;
const memory = new WebAssembly.Memory({ initial: 1 });
const importObject = {
js: {
mem: memory,
},
};
WebAssembly
.instantiateStreaming(fetch('bubble.wasm'), importObject)
.then(results => {
const { instance } = results;
// Generate an array with random integers
let l = new Int32Array(memory.buffer, 0, SIZE);
for (let i = 0; i < SIZE; i++) {
l[i] = Math.floor(Math.random() * (MAX_NUM + 1));
}
// Run bubble sort
console.log("Input", l);
instance.exports.sort(0, l.length);
console.log("Output", l);
});
asm` jsmemsort
hf At!A!@@  N  Aj!@@  N  (! (!  J@  6  6 Aj! Aj!
(module
(import "js" "mem" (memory 1))
(func (export "sort") (param $offset i32) (param $size i32)
(local $i i32)
(local $j i32)
(local $limit i32)
(local $x i32)
(local $y i32)
(set_local $limit (i32.shl (get_local $size) (i32.const 2)))
(set_local $i (i32.const 0))
(block $exit (loop $loop
(br_if $exit (i32.ge_s (get_local $i) (get_local $limit)))
(set_local $j (i32.add (get_local $i) (i32.const 4)))
(block $exit2 (loop $loop2
(br_if $exit2 (i32.ge_s (get_local $j) (get_local $limit)))
(set_local $x (i32.load (get_local $i)))
(set_local $y (i32.load (get_local $j)))
(if (i32.gt_s (get_local $x) (get_local $y)) (then
(i32.store (get_local $i) (get_local $y))
(i32.store (get_local $j) (get_local $x))
))
(set_local $j (i32.add (get_local $j) (i32.const 4)))
(br $loop2)
))
(set_local $i (i32.add (get_local $i) (i32.const 4)))
(br $loop)
)
)
)
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bubble Sort in WebAssembly</title>
</head>
<body>
<h1>Bubble Sort in WebAssembly</h1>
<script src="bubble.js"></script>
</body>
</html>
#!/usr/bin/env python3
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
Handler.extensions_map[".wasm"] = "application/wasm"
if __name__ == "__main__":
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment