Skip to content

Instantly share code, notes, and snippets.

@alireza-a
Created December 23, 2018 08:12
Show Gist options
  • Save alireza-a/d9a1a7206d5c12b9f64205e9e0faefc8 to your computer and use it in GitHub Desktop.
Save alireza-a/d9a1a7206d5c12b9f64205e9e0faefc8 to your computer and use it in GitHub Desktop.
A simple stack in WA
(module
(func $needs_more_space (result i32)
block (result i32) ;; available space
get_global 1
i32.const 128 ;; 128 bytes = 1024 bits
i32.const 64
i32.mul
i32.mul
end
block (result i32) ;; next index
get_global 0
i32.const 4 ;; wordsize is 4 bytes
i32.add
end
i32.lt_u
)
(func $is_empty (result i32)
get_global 0
i32.const 0
i32.eq
)
(func $head (result i32)
get_global 0
i32.const 4
i32.sub
)
(func $inc_ind
get_global 0
i32.const 4
i32.add
set_global 0
)
(func $dec_ind
get_global 0
i32.const 4
i32.sub
set_global 0
)
(func $push (param $v i32)
call $needs_more_space
if
i32.const 1
grow_memory
i32.const 1
i32.add
set_global 1
else
end
block
get_global 0
get_local $v
i32.store
end
call $inc_ind
)
(func $pop (result i32)
call $is_empty
if (result i32)
i32.const -1
else
call $head
i32.load
call $dec_ind
end
)
(global (mut i32) (i32.const 0)) ;; index
(global (mut i32) (i32.const 0)) ;; size
(memory 0)
(export "push" (func $push))
(export "pop" (func $pop))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment