Last active
September 20, 2018 00:09
-
-
Save JustinSDK/6f30e59628cb630132910550acbc0ced to your computer and use it in GitHub Desktop.
Wasm Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 說明:https://openhome.cc/Gossip/WebAssembly/Array.html | |
(module | |
(import "env" "log" (func $log (param i32))) | |
(memory 1) | |
;; 建立新陣列 | |
(func $arr (param $len i32) (result i32) | |
(local $offset i32) ;; 記錄陣列偏移量 | |
(set_local $offset (i32.load (i32.const 0))) ;; 取得偏移量 | |
(i32.store (get_local $offset) ;; 首個 i32 儲存陣列長度 | |
(get_local $len) | |
) | |
(i32.store (i32.const 0) ;; 在記憶體開頭記錄可用空間的偏移量 | |
(i32.add | |
(i32.add | |
(get_local $offset) | |
(i32.mul | |
(get_local $len) | |
(i32.const 4) | |
) | |
) | |
(i32.const 4) ;; 別忘了每個陣列首個 i32 是記錄長度 | |
) | |
) | |
(get_local $offset) ;; 建立的陣列偏移量 | |
) | |
;; 取得陣列長度 | |
(func $len (param $arr i32) (result i32) | |
(i32.load (get_local $arr)) | |
) | |
;; 在指定陣列索引時,計算出每個元素在記憶體中的偏移量 | |
(func $offset (param $arr i32) (param $i i32) (result i32) | |
;; 陣列偏移量 + 根據索引及型態計算而得的偏移量 | |
(i32.add | |
(i32.add (get_local $arr) (i32.const 4)) ;; 別忘了每個陣列首個 i32 是記錄長度 | |
(i32.mul (i32.const 4) (get_local $i)) ;; 一個 i32 元素是四個位元組 | |
) | |
) | |
;; 使用索引設定元素值 | |
(func $set (param $arr i32) (param $i i32) (param $value i32) | |
(i32.store | |
(call $offset (get_local $arr) (get_local $i)) | |
(get_local $value) | |
) | |
) | |
;; 使用索引取得元素值 | |
(func $get (param $arr i32) (param $i i32) (result i32) | |
(i32.load | |
(call $offset (get_local $arr) (get_local $i)) | |
) | |
) | |
(func $main | |
(local $a1 i32) | |
;; 因為記憶體首個 i32 記錄可用空間偏移量 | |
;; 第一個可用空間偏移量應為 4(位元組) | |
(i32.store (i32.const 0) (i32.const 4)) | |
(set_local $a1 (call $arr (i32.const 5))) ;; 建立長度為 5 的陣列,指定給 $a1 | |
(call $len (get_local $a1)) | |
call $log | |
;; 在 $a1 索引 1 存入 10 | |
(call $set (get_local $a1) (i32.const 1) (i32.const 10)) | |
;; 取得 $a1 索引 1 的值 | |
(call $get (get_local $a1) (i32.const 1)) | |
call $log | |
) | |
(start $main) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment