Compare commits
20
Commits
v2.0.2
..
57296ed303
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57296ed303 | ||
|
|
7bbd8f6eb3 | ||
|
|
ab5ab2b81b | ||
|
|
f53f344fb3 | ||
|
|
f8f8636cc3 | ||
|
|
13b522f6a0 | ||
|
|
05cd2d79df | ||
|
|
bc52a250a4 | ||
|
|
830c0a7586 | ||
|
|
c94a7902c0 | ||
|
|
8ccb45748d | ||
|
|
63a375995c | ||
|
|
2351faf2d7 | ||
|
|
a446bbd923 | ||
|
|
f1407fd045 | ||
|
|
ce635cc2b1 | ||
|
|
f5d2528e20 | ||
|
|
6f78825876 | ||
|
|
a878da42a3 | ||
|
|
bd720f06fb |
@@ -1,14 +1,16 @@
|
||||
.PHONY: build clean test
|
||||
.PHONY: build clean test dev-init
|
||||
|
||||
build: clean
|
||||
@echo "======================== Building Binary ======================="
|
||||
minify wfa.js > dist/wfa.js
|
||||
GOOS=js GOARCH=wasm CGO_ENABLED=0 tinygo build -panic=trap -no-debug -opt=2 -target=wasm -o dist/wfa.wasm .
|
||||
mkdir -p dist
|
||||
cp wfa.js dist/wfa.js
|
||||
GOOS=js GOARCH=wasm CGO_ENABLED=0 go build -ldflags="-s -w" -trimpath -o dist/wfa.wasm .
|
||||
gzip dist/wfa.wasm
|
||||
|
||||
clean:
|
||||
@echo "======================== Cleaning Project ======================"
|
||||
go clean
|
||||
rm -f dist/wfa.wasm dist/wfa.js cover.prof cpu.prof mem.prof test.test
|
||||
rm -f dist/* cover.prof cpu.prof mem.prof test.test
|
||||
|
||||
test:
|
||||
@echo "======================== Running Tests ========================="
|
||||
@@ -24,3 +26,6 @@ test:
|
||||
@rm -f mem.prof
|
||||
|
||||
@rm -f test.test
|
||||
|
||||
dev-init:
|
||||
go get -t wfa/test
|
||||
@@ -1,11 +1,13 @@
|
||||
# Using WFA-JS
|
||||
|
||||
Download `wfa.js` and `wfa.wasm`from [releases](https://git.tronnet.net/tronnet/WFA-JS/releases) to your project. Add to your script:
|
||||
Download `wfa.js` and `wfa.wasm`from [releases](https://git.tronnet.net/alu/WFA-JS/releases) to your project. Add to your script:
|
||||
|
||||
```
|
||||
import wfa from "./wfa.js"
|
||||
await wfa("<path to wasm>")
|
||||
console.log(wfAlign(...))
|
||||
let result = wfAlign(...)
|
||||
operations = DecodeCIGAR(result.CIGAR)
|
||||
// ...
|
||||
```
|
||||
|
||||
Where `<path to wasm>` is the path from the site root ie. `./scripts/wfa.wasm`. This will depend on your project structure.
|
||||
@@ -1,15 +1,15 @@
|
||||
module wfa
|
||||
|
||||
go 1.23.2
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
github.com/schollz/progressbar/v3 v3.17.0
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c
|
||||
github.com/schollz/progressbar/v3 v3.19.1
|
||||
golang.org/x/exp v0.0.0-20260611194520-c48552f49976
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
golang.org/x/sys v0.26.0 // indirect
|
||||
golang.org/x/term v0.25.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/term v0.44.0 // indirect
|
||||
)
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<script src="wfa.js" type="module"></script>
|
||||
<script type="module">
|
||||
import wfaInit from "./wfa.js";
|
||||
wfaInit("dist/wfa.wasm.gz");
|
||||
window.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelector("#submit").addEventListener("click", () => {
|
||||
a = document.querySelector("#a").value
|
||||
b = document.querySelector("#b").value
|
||||
const penalties = {
|
||||
m: 0,
|
||||
x: 1,
|
||||
o: 0,
|
||||
e: 1
|
||||
};
|
||||
const { score, CIGAR } = wfa.wfAlign(a, b, penalties, true);
|
||||
const alignment = wfa.DecodeCIGAR(CIGAR);
|
||||
document.querySelector("#result").innerText = `${score}, ${CIGAR}, ${alignment}`;
|
||||
})
|
||||
});
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<label>A: </label><input type="text" id="a">
|
||||
<label>B: </label><input type="text" id="b">
|
||||
<button id="submit" type="button">Submit</button>
|
||||
<p><span>Result: </span><span id="result"></span></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,46 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall/js"
|
||||
wfa "wfa/pkg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
c := make(chan bool)
|
||||
js.Global().Set("wfAlign", js.FuncOf(wfAlign))
|
||||
js.Global().Set("DecodeCIGAR", js.FuncOf(DecodeCIGAR))
|
||||
js.Global().Get("wfa").Set("wfAlign", js.FuncOf(wfAlign))
|
||||
js.Global().Get("wfa").Set("DecodeCIGAR", js.FuncOf(DecodeCIGAR))
|
||||
<-c
|
||||
}
|
||||
|
||||
func wfAlign(this js.Value, args []js.Value) interface{} {
|
||||
if len(args) != 4 {
|
||||
fmt.Println("invalid number of args, requires 4: s1, s2, penalties, doCIGAR")
|
||||
return nil
|
||||
resultMap := map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": "invalid number of args, requires 4: s1, s2, penalties, doCIGAR",
|
||||
}
|
||||
return js.ValueOf(resultMap)
|
||||
}
|
||||
|
||||
if args[0].Type() != js.TypeString {
|
||||
fmt.Println("s1 should be a string")
|
||||
return nil
|
||||
resultMap := map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": "s1 should be a string",
|
||||
}
|
||||
return js.ValueOf(resultMap)
|
||||
}
|
||||
|
||||
s1 := args[0].String()
|
||||
|
||||
if args[1].Type() != js.TypeString {
|
||||
fmt.Println("s2 should be a string")
|
||||
return nil
|
||||
resultMap := map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": "s2 should be a string",
|
||||
}
|
||||
return js.ValueOf(resultMap)
|
||||
}
|
||||
|
||||
s2 := args[1].String()
|
||||
|
||||
if args[2].Type() != js.TypeObject {
|
||||
fmt.Println("penalties should be a map with key values m, x, o, e")
|
||||
return nil
|
||||
resultMap := map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": "penalties should be a map with key values m, x, o, e",
|
||||
}
|
||||
return js.ValueOf(resultMap)
|
||||
}
|
||||
|
||||
if args[2].Get("m").IsUndefined() || args[2].Get("x").IsUndefined() || args[2].Get("o").IsUndefined() || args[2].Get("e").IsUndefined() {
|
||||
fmt.Println("penalties should be a map with key values m, x, o, e")
|
||||
return nil
|
||||
resultMap := map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": "penalties should be a map with key values m, x, o, e",
|
||||
}
|
||||
return js.ValueOf(resultMap)
|
||||
}
|
||||
|
||||
m := args[2].Get("m").Int()
|
||||
@@ -56,8 +70,11 @@ func wfAlign(this js.Value, args []js.Value) interface{} {
|
||||
}
|
||||
|
||||
if args[3].Type() != js.TypeBoolean {
|
||||
fmt.Println("doCIGAR should be a boolean")
|
||||
return nil
|
||||
resultMap := map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": "doCIGAR should be a boolean",
|
||||
}
|
||||
return js.ValueOf(resultMap)
|
||||
}
|
||||
|
||||
doCIGAR := args[3].Bool()
|
||||
@@ -65,8 +82,10 @@ func wfAlign(this js.Value, args []js.Value) interface{} {
|
||||
// Call the actual func.
|
||||
result := wfa.WFAlign(s1, s2, penalties, doCIGAR)
|
||||
resultMap := map[string]interface{}{
|
||||
"ok": true,
|
||||
"score": result.Score,
|
||||
"CIGAR": result.CIGAR,
|
||||
"error": "",
|
||||
}
|
||||
|
||||
return js.ValueOf(resultMap)
|
||||
@@ -74,12 +93,12 @@ func wfAlign(this js.Value, args []js.Value) interface{} {
|
||||
|
||||
func DecodeCIGAR(this js.Value, args []js.Value) interface{} {
|
||||
if len(args) != 1 {
|
||||
fmt.Println("invalid number of args, requires 1: CIGAR")
|
||||
println("invalid number of args, requires 1: CIGAR")
|
||||
return nil
|
||||
}
|
||||
|
||||
if args[0].Type() != js.TypeString {
|
||||
fmt.Println("CIGAR should be a string")
|
||||
println("CIGAR should be a string")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+10
-29
@@ -6,50 +6,31 @@ type PositiveSlice[T any] struct {
|
||||
defaultValue T
|
||||
}
|
||||
|
||||
func (a *PositiveSlice[T]) TranslateIndex(idx int) int {
|
||||
return idx
|
||||
}
|
||||
|
||||
func (a *PositiveSlice[T]) Valid(idx int) bool {
|
||||
actualIdx := a.TranslateIndex(idx)
|
||||
return 0 <= actualIdx && actualIdx < len(a.valid) && a.valid[actualIdx]
|
||||
return 0 <= idx && idx < len(a.valid) && a.valid[idx]
|
||||
}
|
||||
|
||||
func (a *PositiveSlice[T]) Get(idx int) T {
|
||||
actualIdx := a.TranslateIndex(idx)
|
||||
if 0 <= actualIdx && actualIdx < len(a.valid) && a.valid[actualIdx] { // idx is in the slice
|
||||
return a.data[actualIdx]
|
||||
if 0 <= idx && idx < len(a.valid) && a.valid[idx] { // idx is in the slice
|
||||
return a.data[idx]
|
||||
} else { // idx is out of the slice
|
||||
return a.defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
func (a *PositiveSlice[T]) Set(idx int, value T) {
|
||||
actualIdx := a.TranslateIndex(idx)
|
||||
if actualIdx < 0 || actualIdx >= len(a.valid) { // idx is outside the slice
|
||||
// expand data array to actualIdx
|
||||
newData := make([]T, 2*actualIdx+1)
|
||||
if idx >= len(a.valid) { // idx is outside the slice
|
||||
// expand data array to 2*idx
|
||||
newData := make([]T, 2*idx+1)
|
||||
copy(newData, a.data)
|
||||
a.data = newData
|
||||
|
||||
// expand valid array to actualIdx
|
||||
newValid := make([]bool, 2*actualIdx+1)
|
||||
// expand valid array to 2*idx
|
||||
newValid := make([]bool, 2*idx+1)
|
||||
copy(newValid, a.valid)
|
||||
a.valid = newValid
|
||||
}
|
||||
|
||||
a.data[actualIdx] = value
|
||||
a.valid[actualIdx] = true
|
||||
}
|
||||
|
||||
func (a *PositiveSlice[T]) Preallocate(hi int) {
|
||||
size := hi
|
||||
|
||||
// expand data array to actualIdx
|
||||
newData := make([]T, size+1)
|
||||
a.data = newData
|
||||
|
||||
// expand valid array to actualIdx
|
||||
newValid := make([]bool, size+1)
|
||||
a.valid = newValid
|
||||
a.data[idx] = value
|
||||
a.valid[idx] = true
|
||||
}
|
||||
|
||||
+9
-7
@@ -1,3 +1,5 @@
|
||||
//go:build debug
|
||||
|
||||
package wfa
|
||||
|
||||
import (
|
||||
@@ -12,11 +14,13 @@ func (w *WavefrontComponent) String(score int) string {
|
||||
max_hi := math.MinInt
|
||||
|
||||
for i := 0; i <= score; i++ {
|
||||
if w.lo.Valid(i) && w.lo.Get(i) < min_lo {
|
||||
min_lo = w.lo.Get(i)
|
||||
valid := w.W.Valid(i)
|
||||
lo, hi := UnpackWavefrontLoHi(w.W.Get(i).lohi)
|
||||
if valid && lo < min_lo {
|
||||
min_lo = lo
|
||||
}
|
||||
if w.hi.Valid(i) && w.hi.Get(i) > max_hi {
|
||||
max_hi = w.hi.Get(i)
|
||||
if valid && hi > max_hi {
|
||||
max_hi = hi
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,9 +44,7 @@ func (w *WavefrontComponent) String(score int) string {
|
||||
|
||||
for i := 0; i <= score; i++ {
|
||||
s = s + "["
|
||||
lo := w.lo.Get(i)
|
||||
hi := w.hi.Get(i)
|
||||
// print out wavefront matrix
|
||||
lo, hi := UnpackWavefrontLoHi(w.W.Get(i).lohi)
|
||||
for k := min_lo; k <= max_hi; k++ {
|
||||
valid, val, _ := UnpackWavefrontValue(w.W.Get(i).Get(k))
|
||||
if valid {
|
||||
|
||||
+42
-52
@@ -1,5 +1,9 @@
|
||||
package wfa
|
||||
|
||||
type Integer interface {
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Score int
|
||||
CIGAR string
|
||||
@@ -25,49 +29,60 @@ const (
|
||||
End
|
||||
)
|
||||
|
||||
// bitpacked wavefront values with 1 valid bit, 3 traceback bits, and 28 bits for the diag distance
|
||||
// technically this restricts to solutions within 268 million score but that should be sufficient for most cases
|
||||
type WavefrontValue uint32
|
||||
// bitpacked wavefront lo/hi values with 32 bits each
|
||||
type WavefrontLoHi uint64
|
||||
|
||||
// TODO: add 64 bit packed value in case more than 268 million score is needed
|
||||
func PackWavefrontLoHi(lo int, hi int) WavefrontLoHi {
|
||||
loBM := int64(int32(lo)) & 0x0000_0000_FFFF_FFFF
|
||||
hiBM := int64(int64(hi) << 32)
|
||||
return WavefrontLoHi(hiBM | loBM)
|
||||
}
|
||||
|
||||
func UnpackWavefrontLoHi(lohi WavefrontLoHi) (int, int) {
|
||||
loBM := int(int32(lohi & 0x0000_0000_FFFF_FFFF))
|
||||
hiBM := int(int32(lohi & 0xFFFF_FFFF_0000_0000 >> 32))
|
||||
return loBM, hiBM
|
||||
}
|
||||
|
||||
// bitpacked wavefront values with 1 valid bit, 3 traceback bits, and 60 bits for the diag distance
|
||||
type WavefrontValue uint64
|
||||
|
||||
// PackWavefrontValue: packs a diag value and traceback into a WavefrontValue
|
||||
func PackWavefrontValue(value uint32, traceback Traceback) WavefrontValue {
|
||||
valueBM := value & 0x0FFF_FFFF
|
||||
tracebackBM := uint32(traceback&0x0000_0007) << 28
|
||||
return WavefrontValue(0x8000_0000 | valueBM | tracebackBM)
|
||||
func PackWavefrontValue(value uint64, traceback Traceback) WavefrontValue {
|
||||
validBM := uint64(0x8000_0000_0000_0000)
|
||||
tracebackBM := uint64(traceback&0x0000_0007) << 60
|
||||
valueBM := uint64(value) & 0x0FFF_FFFF_FFFF_FFFF
|
||||
return WavefrontValue(validBM | tracebackBM | valueBM)
|
||||
}
|
||||
|
||||
// UnpackWavefrontValue: opens a WavefrontValue into a valid bool, diag value and traceback
|
||||
func UnpackWavefrontValue(wfv WavefrontValue) (bool, uint32, Traceback) {
|
||||
valueBM := uint32(wfv & 0x0FFF_FFFF)
|
||||
tracebackBM := uint8(wfv & 0x7000_0000 >> 28)
|
||||
validBM := wfv&0x8000_0000 != 0
|
||||
func UnpackWavefrontValue(wfv WavefrontValue) (bool, uint64, Traceback) {
|
||||
validBM := wfv&0x8000_0000_0000_0000 != 0
|
||||
tracebackBM := uint8(wfv & 0x7000_0000_0000_0000 >> 60)
|
||||
valueBM := uint64(wfv & 0x0000_0000_FFFF_FFFF)
|
||||
return validBM, valueBM, Traceback(tracebackBM)
|
||||
}
|
||||
|
||||
// Wavefront: stores a single wavefront, stores wavefront's lo value and hi is naturally lo + len(data)
|
||||
type Wavefront struct { // since wavefronts store diag distance, they should never be negative, and traceback data can be stored as uint8
|
||||
data []WavefrontValue
|
||||
lo int
|
||||
lohi WavefrontLoHi
|
||||
}
|
||||
|
||||
// NewWavefront: returns a new wavefront with size accomodating lo and hi (inclusive)
|
||||
func NewWavefront(lo int, hi int) *Wavefront {
|
||||
a := &Wavefront{}
|
||||
|
||||
a.lo = lo
|
||||
size := a.TranslateIndex(hi)
|
||||
|
||||
newData := make([]WavefrontValue, size+1)
|
||||
a.data = newData
|
||||
a.lohi = PackWavefrontLoHi(lo, hi)
|
||||
size := hi - lo
|
||||
a.data = make([]WavefrontValue, size+1)
|
||||
|
||||
return a
|
||||
}
|
||||
|
||||
// TranslateIndex: utility function for getting the data index given a diagonal
|
||||
func (a *Wavefront) TranslateIndex(diagonal int) int {
|
||||
return diagonal - a.lo
|
||||
lo := int(int32(a.lohi & 0x0000_0000_FFFF_FFFF))
|
||||
return diagonal - lo
|
||||
}
|
||||
|
||||
// Get: returns WavefrontValue for given diagonal
|
||||
@@ -95,27 +110,17 @@ func (a *Wavefront) Set(diagonal int, value WavefrontValue) {
|
||||
|
||||
// WavefrontComponent: each M/I/D wavefront matrix including the wavefront data, lo and hi
|
||||
type WavefrontComponent struct {
|
||||
lo *PositiveSlice[int] // lo for each wavefront
|
||||
hi *PositiveSlice[int] // hi for each wavefront
|
||||
W *PositiveSlice[*Wavefront] // wavefront diag distance and traceback for each wavefront
|
||||
W *PositiveSlice[*Wavefront] // wavefront diag distance and traceback for each wavefront
|
||||
}
|
||||
|
||||
// NewWavefrontComponent: returns initialized WavefrontComponent
|
||||
func NewWavefrontComponent(preallocateSize int) WavefrontComponent {
|
||||
func NewWavefrontComponent() *WavefrontComponent {
|
||||
// new wavefront component = {
|
||||
// lo = [0]
|
||||
// hi = [0]
|
||||
// W = []
|
||||
// }
|
||||
w := WavefrontComponent{
|
||||
lo: &PositiveSlice[int]{
|
||||
data: []int{0},
|
||||
valid: []bool{true},
|
||||
},
|
||||
hi: &PositiveSlice[int]{
|
||||
data: []int{0},
|
||||
valid: []bool{true},
|
||||
},
|
||||
w := &WavefrontComponent{
|
||||
W: &PositiveSlice[*Wavefront]{
|
||||
defaultValue: &Wavefront{
|
||||
data: []WavefrontValue{0},
|
||||
@@ -123,42 +128,27 @@ func NewWavefrontComponent(preallocateSize int) WavefrontComponent {
|
||||
},
|
||||
}
|
||||
|
||||
w.lo.Preallocate(preallocateSize)
|
||||
w.hi.Preallocate(preallocateSize)
|
||||
w.W.Preallocate(preallocateSize)
|
||||
|
||||
return w
|
||||
}
|
||||
|
||||
// GetVal: get value for wavefront=score, diag=k => returns ok, value, traceback
|
||||
func (w *WavefrontComponent) GetVal(score int, k int) (bool, uint32, Traceback) {
|
||||
func (w *WavefrontComponent) GetVal(score int, k int) (bool, uint64, Traceback) {
|
||||
return UnpackWavefrontValue(w.W.Get(score).Get(k))
|
||||
}
|
||||
|
||||
// SetVal: set value, traceback for wavefront=score, diag=k
|
||||
func (w *WavefrontComponent) SetVal(score int, k int, val uint32, tb Traceback) {
|
||||
func (w *WavefrontComponent) SetVal(score int, k int, val uint64, tb Traceback) {
|
||||
w.W.Get(score).Set(k, PackWavefrontValue(val, tb))
|
||||
}
|
||||
|
||||
// GetLoHi: get lo and hi for wavefront=score
|
||||
func (w *WavefrontComponent) GetLoHi(score int) (bool, int, int) {
|
||||
// if lo[score] and hi[score] are valid
|
||||
if w.lo.Valid(score) && w.hi.Valid(score) {
|
||||
// return lo[score] hi[score]
|
||||
return true, w.lo.Get(score), w.hi.Get(score)
|
||||
} else {
|
||||
return false, 0, 0
|
||||
}
|
||||
lo, hi := UnpackWavefrontLoHi(w.W.Get(score).lohi)
|
||||
return w.W.Valid(score), lo, hi
|
||||
}
|
||||
|
||||
// SetLoHi: set lo and hi for wavefront=score
|
||||
func (w *WavefrontComponent) SetLoHi(score int, lo int, hi int) {
|
||||
// lo[score] = lo
|
||||
w.lo.Set(score, lo)
|
||||
// hi[score] = hi
|
||||
w.hi.Set(score, hi)
|
||||
|
||||
// preemptively setup w.W
|
||||
b := NewWavefront(lo, hi)
|
||||
w.W.Set(score, b)
|
||||
}
|
||||
|
||||
+45
-45
@@ -1,23 +1,18 @@
|
||||
package wfa
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
const MaxInt = int(^uint(0) >> 1)
|
||||
const MinInt = -MaxInt - 1
|
||||
|
||||
// convert an unsigned into to string
|
||||
func UIntToString(num uint) string { // num assumed to be positive
|
||||
var builder strings.Builder
|
||||
str := []rune{}
|
||||
|
||||
for num > 0 {
|
||||
digit := num % 10
|
||||
builder.WriteRune(rune('0' + digit))
|
||||
str = append(str, rune('0'+digit))
|
||||
num /= 10
|
||||
}
|
||||
|
||||
// Reverse the string as we built it in reverse order
|
||||
str := []rune(builder.String())
|
||||
for i, j := 0, len(str)-1; i < j; i, j = i+1, j-1 {
|
||||
str[i], str[j] = str[j], str[i]
|
||||
}
|
||||
@@ -25,8 +20,9 @@ func UIntToString(num uint) string { // num assumed to be positive
|
||||
return string(str)
|
||||
}
|
||||
|
||||
// decode runlength encoded string such as CIGARs
|
||||
func RunLengthDecode(encoded string) string {
|
||||
decoded := strings.Builder{}
|
||||
decoded := []rune{}
|
||||
length := len(encoded)
|
||||
i := 0
|
||||
|
||||
@@ -42,45 +38,30 @@ func RunLengthDecode(encoded string) string {
|
||||
if i < length {
|
||||
char := encoded[i]
|
||||
for j := 0; j < runLength; j++ {
|
||||
decoded.WriteByte(char)
|
||||
decoded = append(decoded, rune(char))
|
||||
}
|
||||
i++ // Move past the character
|
||||
}
|
||||
}
|
||||
|
||||
return decoded.String()
|
||||
return string(decoded)
|
||||
}
|
||||
|
||||
func SafeMin[T constraints.Integer](values []T, idx int) T {
|
||||
// given the min index, return the item in values at that index
|
||||
func SafeMin[T Integer](values []T, idx int) T {
|
||||
return values[idx]
|
||||
}
|
||||
|
||||
func SafeMax[T constraints.Integer](values []T, idx int) T {
|
||||
// given the max index, return the item in values at that index
|
||||
func SafeMax[T Integer](values []T, idx int) T {
|
||||
return values[idx]
|
||||
}
|
||||
|
||||
func SafeArgMax[T constraints.Integer](valids []bool, values []T) (bool, int) {
|
||||
hasValid := false
|
||||
maxIndex := 0
|
||||
maxValue := math.MinInt
|
||||
for i := 0; i < len(valids); i++ {
|
||||
if valids[i] && int(values[i]) > maxValue {
|
||||
hasValid = true
|
||||
maxIndex = i
|
||||
maxValue = int(values[i])
|
||||
}
|
||||
}
|
||||
if hasValid {
|
||||
return true, maxIndex
|
||||
} else {
|
||||
return false, 0
|
||||
}
|
||||
}
|
||||
|
||||
func SafeArgMin[T constraints.Integer](valids []bool, values []T) (bool, int) {
|
||||
// given array of values and corresponding array of valid flags, find the min of value which is valid or return false if there does not exist any
|
||||
func SafeArgMin[T Integer](valids []bool, values []T) (bool, int) {
|
||||
hasValid := false
|
||||
minIndex := 0
|
||||
minValue := math.MaxInt
|
||||
minValue := MaxInt
|
||||
for i := 0; i < len(valids); i++ {
|
||||
if valids[i] && int(values[i]) < minValue {
|
||||
hasValid = true
|
||||
@@ -95,7 +76,23 @@ func SafeArgMin[T constraints.Integer](valids []bool, values []T) (bool, int) {
|
||||
}
|
||||
}
|
||||
|
||||
func NextLoHi(M WavefrontComponent, I WavefrontComponent, D WavefrontComponent, score int, penalties Penalty) (int, int) {
|
||||
// given array of values and corresponding array of valid flags, find the max of value which is valid or return false if there does not exist any
|
||||
func SafeArgMax[T Integer](valids []bool, values []T) (bool, int) {
|
||||
hasValid := false
|
||||
maxIndex := 0
|
||||
maxValue := MinInt
|
||||
for i := range valids {
|
||||
if valids[i] && int(values[i]) > maxValue {
|
||||
hasValid = true
|
||||
maxIndex = i
|
||||
maxValue = int(values[i])
|
||||
}
|
||||
}
|
||||
return hasValid, maxIndex
|
||||
}
|
||||
|
||||
// set the lext lo and hi bounds for wavefronts M, I, D
|
||||
func NextLoHi(M *WavefrontComponent, I *WavefrontComponent, D *WavefrontComponent, score int, penalties Penalty) (int, int) {
|
||||
x := penalties.X
|
||||
o := penalties.O
|
||||
e := penalties.E
|
||||
@@ -125,35 +122,38 @@ func NextLoHi(M WavefrontComponent, I WavefrontComponent, D WavefrontComponent,
|
||||
return lo, hi
|
||||
}
|
||||
|
||||
func NextI(M WavefrontComponent, I WavefrontComponent, score int, k int, penalties Penalty) {
|
||||
// set the traceback and diag value for the next I wavefront
|
||||
func NextI(M *WavefrontComponent, I *WavefrontComponent, score int, k int, penalties Penalty) {
|
||||
o := penalties.O
|
||||
e := penalties.E
|
||||
|
||||
a_ok, a, _ := M.GetVal(score-o-e, k-1)
|
||||
b_ok, b, _ := I.GetVal(score-e, k-1)
|
||||
|
||||
ok, nextITraceback := SafeArgMax([]bool{a_ok, b_ok}, []uint32{a, b})
|
||||
nextIVal := SafeMax([]uint32{a, b}, nextITraceback) + 1 // important that the +1 is here
|
||||
ok, nextITraceback := SafeArgMax([]bool{a_ok, b_ok}, []uint64{a, b})
|
||||
nextIVal := SafeMax([]uint64{a, b}, nextITraceback) + 1 // important that the +1 is here
|
||||
if ok {
|
||||
I.SetVal(score, k, nextIVal, []Traceback{OpenIns, ExtdIns}[nextITraceback])
|
||||
}
|
||||
}
|
||||
|
||||
func NextD(M WavefrontComponent, D WavefrontComponent, score int, k int, penalties Penalty) {
|
||||
// set the traceback and diag value for the next D wavefront
|
||||
func NextD(M *WavefrontComponent, D *WavefrontComponent, score int, k int, penalties Penalty) {
|
||||
o := penalties.O
|
||||
e := penalties.E
|
||||
|
||||
a_ok, a, _ := M.GetVal(score-o-e, k+1)
|
||||
b_ok, b, _ := D.GetVal(score-e, k+1)
|
||||
|
||||
ok, nextDTraceback := SafeArgMax([]bool{a_ok, b_ok}, []uint32{a, b})
|
||||
nextDVal := SafeMax([]uint32{a, b}, nextDTraceback)
|
||||
ok, nextDTraceback := SafeArgMax([]bool{a_ok, b_ok}, []uint64{a, b})
|
||||
nextDVal := SafeMax([]uint64{a, b}, nextDTraceback)
|
||||
if ok {
|
||||
D.SetVal(score, k, nextDVal, []Traceback{OpenDel, ExtdDel}[nextDTraceback])
|
||||
}
|
||||
}
|
||||
|
||||
func NextM(M WavefrontComponent, I WavefrontComponent, D WavefrontComponent, score int, k int, penalties Penalty) {
|
||||
// set the traceback and diag value for the next M wavefront
|
||||
func NextM(M *WavefrontComponent, I *WavefrontComponent, D *WavefrontComponent, score int, k int, penalties Penalty) {
|
||||
x := penalties.X
|
||||
|
||||
a_ok, a, _ := M.GetVal(score-x, k)
|
||||
@@ -161,8 +161,8 @@ func NextM(M WavefrontComponent, I WavefrontComponent, D WavefrontComponent, sco
|
||||
b_ok, b, _ := I.GetVal(score, k)
|
||||
c_ok, c, _ := D.GetVal(score, k)
|
||||
|
||||
ok, nextMTraceback := SafeArgMax([]bool{a_ok, b_ok, c_ok}, []uint32{a, b, c})
|
||||
nextMVal := SafeMax([]uint32{a, b, c}, nextMTraceback)
|
||||
ok, nextMTraceback := SafeArgMax([]bool{a_ok, b_ok, c_ok}, []uint64{a, b, c})
|
||||
nextMVal := SafeMax([]uint64{a, b, c}, nextMTraceback)
|
||||
if ok {
|
||||
M.SetVal(score, k, nextMVal, []Traceback{Sub, Ins, Del}[nextMTraceback])
|
||||
}
|
||||
|
||||
+26
-29
@@ -1,26 +1,22 @@
|
||||
package wfa
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// WFAlign takes strings s1, s2, penalties, and returns the score and CIGAR if doCIGAR is true
|
||||
func WFAlign(s1 string, s2 string, penalties Penalty, doCIGAR bool) Result {
|
||||
n := len(s1)
|
||||
m := len(s2)
|
||||
A_k := m - n
|
||||
A_offset := uint32(m)
|
||||
A_k := m - n // diagonal where both sequences end
|
||||
A_offset := uint64(m) // offset along a_k diagonal corresponding to end
|
||||
score := 0
|
||||
estimatedScore := (max(n, m) * max(penalties.M, penalties.X, penalties.O, penalties.E)) / 4
|
||||
M := NewWavefrontComponent(estimatedScore)
|
||||
M := NewWavefrontComponent()
|
||||
M.SetLoHi(0, 0, 0)
|
||||
M.SetVal(0, 0, 0, End)
|
||||
I := NewWavefrontComponent(estimatedScore)
|
||||
D := NewWavefrontComponent(estimatedScore)
|
||||
I := NewWavefrontComponent()
|
||||
D := NewWavefrontComponent()
|
||||
|
||||
for {
|
||||
WFExtend(M, s1, n, s2, m, score)
|
||||
ok, val, _ := M.GetVal(score, A_k)
|
||||
if ok && val >= A_offset {
|
||||
if ok && val >= A_offset { // exit when M_(s,a_k) >= A_offset, ie the wavefront has reached the end
|
||||
break
|
||||
}
|
||||
score = score + 1
|
||||
@@ -28,7 +24,7 @@ func WFAlign(s1 string, s2 string, penalties Penalty, doCIGAR bool) Result {
|
||||
}
|
||||
|
||||
CIGAR := ""
|
||||
if doCIGAR {
|
||||
if doCIGAR { // if doCIGAR, then perform backtrace, otherwise just return the score
|
||||
CIGAR = WFBacktrace(M, I, D, score, penalties, A_k, A_offset, s1, s2)
|
||||
}
|
||||
|
||||
@@ -38,40 +34,41 @@ func WFAlign(s1 string, s2 string, penalties Penalty, doCIGAR bool) Result {
|
||||
}
|
||||
}
|
||||
|
||||
func WFExtend(M WavefrontComponent, s1 string, n int, s2 string, m int, score int) {
|
||||
func WFExtend(M *WavefrontComponent, s1 string, n int, s2 string, m int, score int) {
|
||||
_, lo, hi := M.GetLoHi(score)
|
||||
for k := lo; k <= hi; k++ {
|
||||
for k := lo; k <= hi; k++ { // for each diagonal in current wavefront
|
||||
// v = M[score][k] - k
|
||||
// h = M[score][k]
|
||||
ok, hu, _ := M.GetVal(score, k)
|
||||
h := int(hu)
|
||||
v := h - k
|
||||
|
||||
// exit early if v or h are invalid
|
||||
ok, uh, tb := M.GetVal(score, k)
|
||||
// exit early if M_(s,l) is invalid
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for v < n && h < m && s1[v] == s2[h] {
|
||||
_, val, tb := M.GetVal(score, k)
|
||||
M.SetVal(score, k, val+1, tb)
|
||||
h := int(uh)
|
||||
v := h - k
|
||||
// in the paper, we do v++, h++, M_(s,k)++
|
||||
// however, note that h = M_(s,k) so instead we just do v++, h++ and set M_(s,k) at the end
|
||||
// this saves a some memory reads and writes
|
||||
for v < n && h < m && s1[v] == s2[h] { // extend diagonal for the next set of matches
|
||||
v++
|
||||
h++
|
||||
}
|
||||
M.SetVal(score, k, uint64(h), tb)
|
||||
}
|
||||
}
|
||||
|
||||
func WFNext(M WavefrontComponent, I WavefrontComponent, D WavefrontComponent, score int, penalties Penalty) {
|
||||
func WFNext(M *WavefrontComponent, I *WavefrontComponent, D *WavefrontComponent, score int, penalties Penalty) {
|
||||
// get this score's lo, hi
|
||||
lo, hi := NextLoHi(M, I, D, score, penalties)
|
||||
|
||||
for k := lo; k <= hi; k++ {
|
||||
for k := lo; k <= hi; k++ { // for each diagonal, extend the matrices for the next wavefronts
|
||||
NextI(M, I, score, k, penalties)
|
||||
NextD(M, D, score, k, penalties)
|
||||
NextM(M, I, D, score, k, penalties)
|
||||
}
|
||||
}
|
||||
|
||||
func WFBacktrace(M WavefrontComponent, I WavefrontComponent, D WavefrontComponent, score int, penalties Penalty, A_k int, A_offset uint32, s1 string, s2 string) string {
|
||||
func WFBacktrace(M *WavefrontComponent, I *WavefrontComponent, D *WavefrontComponent, score int, penalties Penalty, A_k int, A_offset uint64, s1 string, s2 string) string {
|
||||
x := penalties.X
|
||||
o := penalties.O
|
||||
e := penalties.E
|
||||
@@ -188,11 +185,11 @@ func WFBacktrace(M WavefrontComponent, I WavefrontComponent, D WavefrontComponen
|
||||
}
|
||||
}
|
||||
|
||||
CIGAR := strings.Builder{}
|
||||
CIGAR := ""
|
||||
for i := len(Ops) - 1; i > 0; i-- {
|
||||
CIGAR.WriteString(UIntToString(Counts[i]))
|
||||
CIGAR.WriteRune(Ops[i])
|
||||
CIGAR += UIntToString(Counts[i])
|
||||
CIGAR += string(Ops[i])
|
||||
}
|
||||
|
||||
return CIGAR.String()
|
||||
return CIGAR
|
||||
}
|
||||
|
||||
+19
-4
@@ -12,6 +12,7 @@ import (
|
||||
wfa "wfa/pkg"
|
||||
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
const testJsonPath = "tests.json"
|
||||
@@ -29,14 +30,14 @@ type TestCase struct {
|
||||
Solutions string `json:"solutions"`
|
||||
}
|
||||
|
||||
func randRange(min, max int) uint32 {
|
||||
return uint32(rand.IntN(max-min) + min)
|
||||
func randRange[T constraints.Integer](min, max int) T {
|
||||
return T(rand.IntN(max-min) + min)
|
||||
}
|
||||
|
||||
func TestWavefrontPacking(t *testing.T) {
|
||||
for range 1000 {
|
||||
val := randRange(0, 1000)
|
||||
tb := wfa.Traceback(randRange(0, 7))
|
||||
val := randRange[uint64](0, 1000)
|
||||
tb := wfa.Traceback(randRange[uint64](0, 7))
|
||||
v := wfa.PackWavefrontValue(val, tb)
|
||||
|
||||
valid, gotVal, gotTB := wfa.UnpackWavefrontValue(v)
|
||||
@@ -47,6 +48,20 @@ func TestWavefrontPacking(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoHiPacking(t *testing.T) {
|
||||
for range 1000 {
|
||||
lo := randRange[int](-1000, 1000)
|
||||
hi := randRange[int](-1000, 1000)
|
||||
v := wfa.PackWavefrontLoHi(lo, hi)
|
||||
|
||||
gotLo, gotHi := wfa.UnpackWavefrontLoHi(v)
|
||||
|
||||
if gotLo != lo || gotHi != hi {
|
||||
t.Errorf(`test WavefrontPack/Unpack, lo: %d, hi: %d, packedval: %x, gotlo: %d, gothi: %d`, lo, hi, v, gotLo, gotHi)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetScoreFromCIGAR(CIGAR string, penalties wfa.Penalty) int {
|
||||
unpackedCIGAR := wfa.RunLengthDecode(CIGAR)
|
||||
previousOp := '~'
|
||||
|
||||
@@ -1,55 +1,26 @@
|
||||
// wasm_exec.js from tinygo
|
||||
|
||||
// Copyright 2018 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
//
|
||||
// This file has been modified for use by the TinyGo compiler.
|
||||
|
||||
"use strict";
|
||||
|
||||
(() => {
|
||||
// Map multiple JavaScript environments to a single common API,
|
||||
// preferring web standards over Node.js API.
|
||||
//
|
||||
// Environments considered:
|
||||
// - Browsers
|
||||
// - Node.js
|
||||
// - Electron
|
||||
// - Parcel
|
||||
|
||||
if (typeof global !== "undefined") {
|
||||
// global already exists
|
||||
} else if (typeof window !== "undefined") {
|
||||
window.global = window;
|
||||
} else if (typeof self !== "undefined") {
|
||||
self.global = self;
|
||||
} else {
|
||||
throw new Error("cannot export Go (neither global, window nor self is defined)");
|
||||
}
|
||||
|
||||
if (!global.require && typeof require !== "undefined") {
|
||||
global.require = require;
|
||||
}
|
||||
|
||||
if (!global.fs && global.require) {
|
||||
global.fs = require("node:fs");
|
||||
}
|
||||
|
||||
const enosys = () => {
|
||||
const err = new Error("not implemented");
|
||||
err.code = "ENOSYS";
|
||||
return err;
|
||||
};
|
||||
|
||||
if (!global.fs) {
|
||||
if (!globalThis.fs) {
|
||||
let outputBuf = "";
|
||||
global.fs = {
|
||||
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
|
||||
globalThis.fs = {
|
||||
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
|
||||
writeSync(fd, buf) {
|
||||
outputBuf += decoder.decode(buf);
|
||||
const nl = outputBuf.lastIndexOf("\n");
|
||||
if (nl != -1) {
|
||||
console.log(outputBuf.substr(0, nl));
|
||||
outputBuf = outputBuf.substr(nl + 1);
|
||||
console.log(outputBuf.substring(0, nl));
|
||||
outputBuf = outputBuf.substring(nl + 1);
|
||||
}
|
||||
return buf.length;
|
||||
},
|
||||
@@ -87,8 +58,8 @@
|
||||
};
|
||||
}
|
||||
|
||||
if (!global.process) {
|
||||
global.process = {
|
||||
if (!globalThis.process) {
|
||||
globalThis.process = {
|
||||
getuid() { return -1; },
|
||||
getgid() { return -1; },
|
||||
geteuid() { return -1; },
|
||||
@@ -102,52 +73,66 @@
|
||||
}
|
||||
}
|
||||
|
||||
if (!global.crypto) {
|
||||
const nodeCrypto = require("node:crypto");
|
||||
global.crypto = {
|
||||
getRandomValues(b) {
|
||||
nodeCrypto.randomFillSync(b);
|
||||
},
|
||||
};
|
||||
if (!globalThis.path) {
|
||||
globalThis.path = {
|
||||
resolve(...pathSegments) {
|
||||
return pathSegments.join("/");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!global.performance) {
|
||||
global.performance = {
|
||||
now() {
|
||||
const [sec, nsec] = process.hrtime();
|
||||
return sec * 1000 + nsec / 1000000;
|
||||
},
|
||||
};
|
||||
if (!globalThis.crypto) {
|
||||
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
|
||||
}
|
||||
|
||||
if (!global.TextEncoder) {
|
||||
global.TextEncoder = require("node:util").TextEncoder;
|
||||
if (!globalThis.performance) {
|
||||
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
|
||||
}
|
||||
|
||||
if (!global.TextDecoder) {
|
||||
global.TextDecoder = require("node:util").TextDecoder;
|
||||
if (!globalThis.TextEncoder) {
|
||||
throw new Error("globalThis.TextEncoder is not available, polyfill required");
|
||||
}
|
||||
|
||||
// End of polyfills for common API.
|
||||
if (!globalThis.TextDecoder) {
|
||||
throw new Error("globalThis.TextDecoder is not available, polyfill required");
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder("utf-8");
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
let reinterpretBuf = new DataView(new ArrayBuffer(8));
|
||||
var logLine = [];
|
||||
|
||||
global.Go = class {
|
||||
globalThis.Go = class {
|
||||
constructor() {
|
||||
this._callbackTimeouts = new Map();
|
||||
this.argv = ["js"];
|
||||
this.env = {};
|
||||
this.exit = (code) => {
|
||||
if (code !== 0) {
|
||||
console.warn("exit code:", code);
|
||||
}
|
||||
};
|
||||
this._exitPromise = new Promise((resolve) => {
|
||||
this._resolveExitPromise = resolve;
|
||||
});
|
||||
this._pendingEvent = null;
|
||||
this._scheduledTimeouts = new Map();
|
||||
this._nextCallbackTimeoutID = 1;
|
||||
|
||||
const mem = () => {
|
||||
// The buffer may change when requesting more memory.
|
||||
return new DataView(this._inst.exports.memory.buffer);
|
||||
const setInt64 = (addr, v) => {
|
||||
this.mem.setUint32(addr + 0, v, true);
|
||||
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
|
||||
}
|
||||
|
||||
const unboxValue = (v_ref) => {
|
||||
reinterpretBuf.setBigInt64(0, v_ref, true);
|
||||
const f = reinterpretBuf.getFloat64(0, true);
|
||||
const setInt32 = (addr, v) => {
|
||||
this.mem.setUint32(addr + 0, v, true);
|
||||
}
|
||||
|
||||
const getInt64 = (addr) => {
|
||||
const low = this.mem.getUint32(addr + 0, true);
|
||||
const high = this.mem.getInt32(addr + 4, true);
|
||||
return low + high * 4294967296;
|
||||
}
|
||||
|
||||
const loadValue = (addr) => {
|
||||
const f = this.mem.getFloat64(addr, true);
|
||||
if (f === 0) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -155,77 +140,69 @@
|
||||
return f;
|
||||
}
|
||||
|
||||
const id = v_ref & 0xffffffffn;
|
||||
const id = this.mem.getUint32(addr, true);
|
||||
return this._values[id];
|
||||
}
|
||||
|
||||
const storeValue = (addr, v) => {
|
||||
const nanHead = 0x7FF80000;
|
||||
|
||||
const loadValue = (addr) => {
|
||||
let v_ref = mem().getBigUint64(addr, true);
|
||||
return unboxValue(v_ref);
|
||||
}
|
||||
|
||||
const boxValue = (v) => {
|
||||
const nanHead = 0x7FF80000n;
|
||||
|
||||
if (typeof v === "number") {
|
||||
if (typeof v === "number" && v !== 0) {
|
||||
if (isNaN(v)) {
|
||||
return nanHead << 32n;
|
||||
this.mem.setUint32(addr + 4, nanHead, true);
|
||||
this.mem.setUint32(addr, 0, true);
|
||||
return;
|
||||
}
|
||||
if (v === 0) {
|
||||
return (nanHead << 32n) | 1n;
|
||||
}
|
||||
reinterpretBuf.setFloat64(0, v, true);
|
||||
return reinterpretBuf.getBigInt64(0, true);
|
||||
this.mem.setFloat64(addr, v, true);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (v) {
|
||||
case undefined:
|
||||
return 0n;
|
||||
case null:
|
||||
return (nanHead << 32n) | 2n;
|
||||
case true:
|
||||
return (nanHead << 32n) | 3n;
|
||||
case false:
|
||||
return (nanHead << 32n) | 4n;
|
||||
if (v === undefined) {
|
||||
this.mem.setFloat64(addr, 0, true);
|
||||
return;
|
||||
}
|
||||
|
||||
let id = this._ids.get(v);
|
||||
if (id === undefined) {
|
||||
id = this._idPool.pop();
|
||||
if (id === undefined) {
|
||||
id = BigInt(this._values.length);
|
||||
id = this._values.length;
|
||||
}
|
||||
this._values[id] = v;
|
||||
this._goRefCounts[id] = 0;
|
||||
this._ids.set(v, id);
|
||||
}
|
||||
this._goRefCounts[id]++;
|
||||
let typeFlag = 1n;
|
||||
let typeFlag = 0;
|
||||
switch (typeof v) {
|
||||
case "object":
|
||||
if (v !== null) {
|
||||
typeFlag = 1;
|
||||
}
|
||||
break;
|
||||
case "string":
|
||||
typeFlag = 2n;
|
||||
typeFlag = 2;
|
||||
break;
|
||||
case "symbol":
|
||||
typeFlag = 3n;
|
||||
typeFlag = 3;
|
||||
break;
|
||||
case "function":
|
||||
typeFlag = 4n;
|
||||
typeFlag = 4;
|
||||
break;
|
||||
}
|
||||
return id | ((nanHead | typeFlag) << 32n);
|
||||
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
|
||||
this.mem.setUint32(addr, id, true);
|
||||
}
|
||||
|
||||
const storeValue = (addr, v) => {
|
||||
let v_ref = boxValue(v);
|
||||
mem().setBigUint64(addr, v_ref, true);
|
||||
const loadSlice = (addr) => {
|
||||
const array = getInt64(addr + 0);
|
||||
const len = getInt64(addr + 8);
|
||||
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
|
||||
}
|
||||
|
||||
const loadSlice = (array, len, cap) => {
|
||||
return new Uint8Array(this._inst.exports.memory.buffer, array, len);
|
||||
}
|
||||
|
||||
const loadSliceOfValues = (array, len, cap) => {
|
||||
const loadSliceOfValues = (addr) => {
|
||||
const array = getInt64(addr + 0);
|
||||
const len = getInt64(addr + 8);
|
||||
const a = new Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
a[i] = loadValue(array + i * 8);
|
||||
@@ -233,74 +210,109 @@
|
||||
return a;
|
||||
}
|
||||
|
||||
const loadString = (ptr, len) => {
|
||||
return decoder.decode(new DataView(this._inst.exports.memory.buffer, ptr, len));
|
||||
const loadString = (addr) => {
|
||||
const saddr = getInt64(addr + 0);
|
||||
const len = getInt64(addr + 8);
|
||||
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
|
||||
}
|
||||
|
||||
const testCallExport = (a, b) => {
|
||||
this._inst.exports.testExport0();
|
||||
return this._inst.exports.testExport(a, b);
|
||||
}
|
||||
|
||||
const timeOrigin = Date.now() - performance.now();
|
||||
this.importObject = {
|
||||
wasi_snapshot_preview1: {
|
||||
// https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#fd_write
|
||||
fd_write: function(fd, iovs_ptr, iovs_len, nwritten_ptr) {
|
||||
let nwritten = 0;
|
||||
if (fd == 1) {
|
||||
for (let iovs_i=0; iovs_i<iovs_len;iovs_i++) {
|
||||
let iov_ptr = iovs_ptr+iovs_i*8; // assuming wasm32
|
||||
let ptr = mem().getUint32(iov_ptr + 0, true);
|
||||
let len = mem().getUint32(iov_ptr + 4, true);
|
||||
nwritten += len;
|
||||
for (let i=0; i<len; i++) {
|
||||
let c = mem().getUint8(ptr+i);
|
||||
if (c == 13) { // CR
|
||||
// ignore
|
||||
} else if (c == 10) { // LF
|
||||
// write line
|
||||
let line = decoder.decode(new Uint8Array(logLine));
|
||||
logLine = [];
|
||||
console.log(line);
|
||||
} else {
|
||||
logLine.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('invalid file descriptor:', fd);
|
||||
}
|
||||
mem().setUint32(nwritten_ptr, nwritten, true);
|
||||
return 0;
|
||||
},
|
||||
fd_close: () => 0, // dummy
|
||||
fd_fdstat_get: () => 0, // dummy
|
||||
fd_seek: () => 0, // dummy
|
||||
"proc_exit": (code) => {
|
||||
if (global.process) {
|
||||
// Node.js
|
||||
process.exit(code);
|
||||
} else {
|
||||
// Can't exit in a browser.
|
||||
throw 'trying to exit with code ' + code;
|
||||
}
|
||||
},
|
||||
random_get: (bufPtr, bufLen) => {
|
||||
crypto.getRandomValues(loadSlice(bufPtr, bufLen));
|
||||
return 0;
|
||||
},
|
||||
_gotest: {
|
||||
add: (a, b) => a + b,
|
||||
callExport: testCallExport,
|
||||
},
|
||||
gojs: {
|
||||
// func ticks() float64
|
||||
"runtime.ticks": () => {
|
||||
return timeOrigin + performance.now();
|
||||
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
|
||||
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
|
||||
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
|
||||
// This changes the SP, thus we have to update the SP used by the imported function.
|
||||
|
||||
// func wasmExit(code int32)
|
||||
"runtime.wasmExit": (sp) => {
|
||||
sp >>>= 0;
|
||||
const code = this.mem.getInt32(sp + 8, true);
|
||||
this.exited = true;
|
||||
delete this._inst;
|
||||
delete this._values;
|
||||
delete this._goRefCounts;
|
||||
delete this._ids;
|
||||
delete this._idPool;
|
||||
this.exit(code);
|
||||
},
|
||||
|
||||
// func sleepTicks(timeout float64)
|
||||
"runtime.sleepTicks": (timeout) => {
|
||||
// Do not sleep, only reactivate scheduler after the given timeout.
|
||||
setTimeout(this._inst.exports.go_scheduler, timeout);
|
||||
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
|
||||
"runtime.wasmWrite": (sp) => {
|
||||
sp >>>= 0;
|
||||
const fd = getInt64(sp + 8);
|
||||
const p = getInt64(sp + 16);
|
||||
const n = this.mem.getInt32(sp + 24, true);
|
||||
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
|
||||
},
|
||||
|
||||
// func resetMemoryDataView()
|
||||
"runtime.resetMemoryDataView": (sp) => {
|
||||
sp >>>= 0;
|
||||
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||
},
|
||||
|
||||
// func nanotime1() int64
|
||||
"runtime.nanotime1": (sp) => {
|
||||
sp >>>= 0;
|
||||
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
|
||||
},
|
||||
|
||||
// func walltime() (sec int64, nsec int32)
|
||||
"runtime.walltime": (sp) => {
|
||||
sp >>>= 0;
|
||||
const msec = (new Date).getTime();
|
||||
setInt64(sp + 8, msec / 1000);
|
||||
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
|
||||
},
|
||||
|
||||
// func scheduleTimeoutEvent(delay int64) int32
|
||||
"runtime.scheduleTimeoutEvent": (sp) => {
|
||||
sp >>>= 0;
|
||||
const id = this._nextCallbackTimeoutID;
|
||||
this._nextCallbackTimeoutID++;
|
||||
this._scheduledTimeouts.set(id, setTimeout(
|
||||
() => {
|
||||
this._resume();
|
||||
while (this._scheduledTimeouts.has(id)) {
|
||||
// for some reason Go failed to register the timeout event, log and try again
|
||||
// (temporary workaround for https://github.com/golang/go/issues/28975)
|
||||
console.warn("scheduleTimeoutEvent: missed timeout event");
|
||||
this._resume();
|
||||
}
|
||||
},
|
||||
getInt64(sp + 8),
|
||||
));
|
||||
this.mem.setInt32(sp + 16, id, true);
|
||||
},
|
||||
|
||||
// func clearTimeoutEvent(id int32)
|
||||
"runtime.clearTimeoutEvent": (sp) => {
|
||||
sp >>>= 0;
|
||||
const id = this.mem.getInt32(sp + 8, true);
|
||||
clearTimeout(this._scheduledTimeouts.get(id));
|
||||
this._scheduledTimeouts.delete(id);
|
||||
},
|
||||
|
||||
// func getRandomData(r []byte)
|
||||
"runtime.getRandomData": (sp) => {
|
||||
sp >>>= 0;
|
||||
crypto.getRandomValues(loadSlice(sp + 8));
|
||||
},
|
||||
|
||||
// func finalizeRef(v ref)
|
||||
"syscall/js.finalizeRef": (v_ref) => {
|
||||
const id = mem().getUint32(unboxValue(v_ref), true);
|
||||
"syscall/js.finalizeRef": (sp) => {
|
||||
sp >>>= 0;
|
||||
const id = this.mem.getUint32(sp + 8, true);
|
||||
this._goRefCounts[id]--;
|
||||
if (this._goRefCounts[id] === 0) {
|
||||
const v = this._values[id];
|
||||
@@ -311,183 +323,233 @@
|
||||
},
|
||||
|
||||
// func stringVal(value string) ref
|
||||
"syscall/js.stringVal": (value_ptr, value_len) => {
|
||||
const s = loadString(value_ptr, value_len);
|
||||
return boxValue(s);
|
||||
"syscall/js.stringVal": (sp) => {
|
||||
sp >>>= 0;
|
||||
storeValue(sp + 24, loadString(sp + 8));
|
||||
},
|
||||
|
||||
// func valueGet(v ref, p string) ref
|
||||
"syscall/js.valueGet": (v_ref, p_ptr, p_len) => {
|
||||
let prop = loadString(p_ptr, p_len);
|
||||
let v = unboxValue(v_ref);
|
||||
let result = Reflect.get(v, prop);
|
||||
return boxValue(result);
|
||||
"syscall/js.valueGet": (sp) => {
|
||||
sp >>>= 0;
|
||||
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 32, result);
|
||||
},
|
||||
|
||||
// func valueSet(v ref, p string, x ref)
|
||||
"syscall/js.valueSet": (v_ref, p_ptr, p_len, x_ref) => {
|
||||
const v = unboxValue(v_ref);
|
||||
const p = loadString(p_ptr, p_len);
|
||||
const x = unboxValue(x_ref);
|
||||
Reflect.set(v, p, x);
|
||||
"syscall/js.valueSet": (sp) => {
|
||||
sp >>>= 0;
|
||||
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
|
||||
},
|
||||
|
||||
// func valueDelete(v ref, p string)
|
||||
"syscall/js.valueDelete": (v_ref, p_ptr, p_len) => {
|
||||
const v = unboxValue(v_ref);
|
||||
const p = loadString(p_ptr, p_len);
|
||||
Reflect.deleteProperty(v, p);
|
||||
"syscall/js.valueDelete": (sp) => {
|
||||
sp >>>= 0;
|
||||
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
|
||||
},
|
||||
|
||||
// func valueIndex(v ref, i int) ref
|
||||
"syscall/js.valueIndex": (v_ref, i) => {
|
||||
return boxValue(Reflect.get(unboxValue(v_ref), i));
|
||||
"syscall/js.valueIndex": (sp) => {
|
||||
sp >>>= 0;
|
||||
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
|
||||
},
|
||||
|
||||
// valueSetIndex(v ref, i int, x ref)
|
||||
"syscall/js.valueSetIndex": (v_ref, i, x_ref) => {
|
||||
Reflect.set(unboxValue(v_ref), i, unboxValue(x_ref));
|
||||
"syscall/js.valueSetIndex": (sp) => {
|
||||
sp >>>= 0;
|
||||
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
|
||||
},
|
||||
|
||||
// func valueCall(v ref, m string, args []ref) (ref, bool)
|
||||
"syscall/js.valueCall": (ret_addr, v_ref, m_ptr, m_len, args_ptr, args_len, args_cap) => {
|
||||
const v = unboxValue(v_ref);
|
||||
const name = loadString(m_ptr, m_len);
|
||||
const args = loadSliceOfValues(args_ptr, args_len, args_cap);
|
||||
"syscall/js.valueCall": (sp) => {
|
||||
sp >>>= 0;
|
||||
try {
|
||||
const m = Reflect.get(v, name);
|
||||
storeValue(ret_addr, Reflect.apply(m, v, args));
|
||||
mem().setUint8(ret_addr + 8, 1);
|
||||
const v = loadValue(sp + 8);
|
||||
const m = Reflect.get(v, loadString(sp + 16));
|
||||
const args = loadSliceOfValues(sp + 32);
|
||||
const result = Reflect.apply(m, v, args);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 56, result);
|
||||
this.mem.setUint8(sp + 64, 1);
|
||||
} catch (err) {
|
||||
storeValue(ret_addr, err);
|
||||
mem().setUint8(ret_addr + 8, 0);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 56, err);
|
||||
this.mem.setUint8(sp + 64, 0);
|
||||
}
|
||||
},
|
||||
|
||||
// func valueInvoke(v ref, args []ref) (ref, bool)
|
||||
"syscall/js.valueInvoke": (ret_addr, v_ref, args_ptr, args_len, args_cap) => {
|
||||
"syscall/js.valueInvoke": (sp) => {
|
||||
sp >>>= 0;
|
||||
try {
|
||||
const v = unboxValue(v_ref);
|
||||
const args = loadSliceOfValues(args_ptr, args_len, args_cap);
|
||||
storeValue(ret_addr, Reflect.apply(v, undefined, args));
|
||||
mem().setUint8(ret_addr + 8, 1);
|
||||
const v = loadValue(sp + 8);
|
||||
const args = loadSliceOfValues(sp + 16);
|
||||
const result = Reflect.apply(v, undefined, args);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, result);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
} catch (err) {
|
||||
storeValue(ret_addr, err);
|
||||
mem().setUint8(ret_addr + 8, 0);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, err);
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
}
|
||||
},
|
||||
|
||||
// func valueNew(v ref, args []ref) (ref, bool)
|
||||
"syscall/js.valueNew": (ret_addr, v_ref, args_ptr, args_len, args_cap) => {
|
||||
const v = unboxValue(v_ref);
|
||||
const args = loadSliceOfValues(args_ptr, args_len, args_cap);
|
||||
"syscall/js.valueNew": (sp) => {
|
||||
sp >>>= 0;
|
||||
try {
|
||||
storeValue(ret_addr, Reflect.construct(v, args));
|
||||
mem().setUint8(ret_addr + 8, 1);
|
||||
const v = loadValue(sp + 8);
|
||||
const args = loadSliceOfValues(sp + 16);
|
||||
const result = Reflect.construct(v, args);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, result);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
} catch (err) {
|
||||
storeValue(ret_addr, err);
|
||||
mem().setUint8(ret_addr+ 8, 0);
|
||||
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||
storeValue(sp + 40, err);
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
}
|
||||
},
|
||||
|
||||
// func valueLength(v ref) int
|
||||
"syscall/js.valueLength": (v_ref) => {
|
||||
return unboxValue(v_ref).length;
|
||||
"syscall/js.valueLength": (sp) => {
|
||||
sp >>>= 0;
|
||||
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
|
||||
},
|
||||
|
||||
// valuePrepareString(v ref) (ref, int)
|
||||
"syscall/js.valuePrepareString": (ret_addr, v_ref) => {
|
||||
const s = String(unboxValue(v_ref));
|
||||
const str = encoder.encode(s);
|
||||
storeValue(ret_addr, str);
|
||||
mem().setInt32(ret_addr + 8, str.length, true);
|
||||
"syscall/js.valuePrepareString": (sp) => {
|
||||
sp >>>= 0;
|
||||
const str = encoder.encode(String(loadValue(sp + 8)));
|
||||
storeValue(sp + 16, str);
|
||||
setInt64(sp + 24, str.length);
|
||||
},
|
||||
|
||||
// valueLoadString(v ref, b []byte)
|
||||
"syscall/js.valueLoadString": (v_ref, slice_ptr, slice_len, slice_cap) => {
|
||||
const str = unboxValue(v_ref);
|
||||
loadSlice(slice_ptr, slice_len, slice_cap).set(str);
|
||||
"syscall/js.valueLoadString": (sp) => {
|
||||
sp >>>= 0;
|
||||
const str = loadValue(sp + 8);
|
||||
loadSlice(sp + 16).set(str);
|
||||
},
|
||||
|
||||
// func valueInstanceOf(v ref, t ref) bool
|
||||
"syscall/js.valueInstanceOf": (v_ref, t_ref) => {
|
||||
return unboxValue(v_ref) instanceof unboxValue(t_ref);
|
||||
"syscall/js.valueInstanceOf": (sp) => {
|
||||
sp >>>= 0;
|
||||
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
|
||||
},
|
||||
|
||||
// func copyBytesToGo(dst []byte, src ref) (int, bool)
|
||||
"syscall/js.copyBytesToGo": (ret_addr, dest_addr, dest_len, dest_cap, src_ref) => {
|
||||
let num_bytes_copied_addr = ret_addr;
|
||||
let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable
|
||||
|
||||
const dst = loadSlice(dest_addr, dest_len);
|
||||
const src = unboxValue(src_ref);
|
||||
"syscall/js.copyBytesToGo": (sp) => {
|
||||
sp >>>= 0;
|
||||
const dst = loadSlice(sp + 8);
|
||||
const src = loadValue(sp + 32);
|
||||
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
|
||||
mem().setUint8(returned_status_addr, 0); // Return "not ok" status
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
return;
|
||||
}
|
||||
const toCopy = src.subarray(0, dst.length);
|
||||
dst.set(toCopy);
|
||||
mem().setUint32(num_bytes_copied_addr, toCopy.length, true);
|
||||
mem().setUint8(returned_status_addr, 1); // Return "ok" status
|
||||
setInt64(sp + 40, toCopy.length);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
},
|
||||
|
||||
// copyBytesToJS(dst ref, src []byte) (int, bool)
|
||||
// Originally copied from upstream Go project, then modified:
|
||||
// https://github.com/golang/go/blob/3f995c3f3b43033013013e6c7ccc93a9b1411ca9/misc/wasm/wasm_exec.js#L404-L416
|
||||
"syscall/js.copyBytesToJS": (ret_addr, dst_ref, src_addr, src_len, src_cap) => {
|
||||
let num_bytes_copied_addr = ret_addr;
|
||||
let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable
|
||||
|
||||
const dst = unboxValue(dst_ref);
|
||||
const src = loadSlice(src_addr, src_len);
|
||||
// func copyBytesToJS(dst ref, src []byte) (int, bool)
|
||||
"syscall/js.copyBytesToJS": (sp) => {
|
||||
sp >>>= 0;
|
||||
const dst = loadValue(sp + 8);
|
||||
const src = loadSlice(sp + 16);
|
||||
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
|
||||
mem().setUint8(returned_status_addr, 0); // Return "not ok" status
|
||||
this.mem.setUint8(sp + 48, 0);
|
||||
return;
|
||||
}
|
||||
const toCopy = src.subarray(0, dst.length);
|
||||
dst.set(toCopy);
|
||||
mem().setUint32(num_bytes_copied_addr, toCopy.length, true);
|
||||
mem().setUint8(returned_status_addr, 1); // Return "ok" status
|
||||
setInt64(sp + 40, toCopy.length);
|
||||
this.mem.setUint8(sp + 48, 1);
|
||||
},
|
||||
|
||||
"debug": (value) => {
|
||||
console.log(value);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
// Go 1.20 uses 'env'. Go 1.21 uses 'gojs'.
|
||||
// For compatibility, we use both as long as Go 1.20 is supported.
|
||||
this.importObject.env = this.importObject.gojs;
|
||||
}
|
||||
|
||||
async run(instance) {
|
||||
if (!(instance instanceof WebAssembly.Instance)) {
|
||||
throw new Error("Go.run: WebAssembly.Instance expected");
|
||||
}
|
||||
this._inst = instance;
|
||||
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||
this._values = [ // JS values that Go currently has references to, indexed by reference id
|
||||
NaN,
|
||||
0,
|
||||
null,
|
||||
true,
|
||||
false,
|
||||
global,
|
||||
globalThis,
|
||||
this,
|
||||
];
|
||||
this._goRefCounts = []; // number of references that Go has to a JS value, indexed by reference id
|
||||
this._ids = new Map(); // mapping from JS values to reference ids
|
||||
this._idPool = []; // unused ids that have been garbage collected
|
||||
this.exited = false; // whether the Go program has exited
|
||||
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
|
||||
this._ids = new Map([ // mapping from JS values to reference ids
|
||||
[0, 1],
|
||||
[null, 2],
|
||||
[true, 3],
|
||||
[false, 4],
|
||||
[globalThis, 5],
|
||||
[this, 6],
|
||||
]);
|
||||
this._idPool = []; // unused ids that have been garbage collected
|
||||
this.exited = false; // whether the Go program has exited
|
||||
|
||||
while (true) {
|
||||
const callbackPromise = new Promise((resolve) => {
|
||||
this._resolveCallbackPromise = () => {
|
||||
if (this.exited) {
|
||||
throw new Error("bad callback: Go program has already exited");
|
||||
}
|
||||
setTimeout(resolve, 0); // make sure it is asynchronous
|
||||
};
|
||||
});
|
||||
this._inst.exports._start();
|
||||
if (this.exited) {
|
||||
break;
|
||||
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
|
||||
let offset = 4096;
|
||||
|
||||
const strPtr = (str) => {
|
||||
const ptr = offset;
|
||||
const bytes = encoder.encode(str + "\0");
|
||||
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
|
||||
offset += bytes.length;
|
||||
if (offset % 8 !== 0) {
|
||||
offset += 8 - (offset % 8);
|
||||
}
|
||||
await callbackPromise;
|
||||
return ptr;
|
||||
};
|
||||
|
||||
const argc = this.argv.length;
|
||||
|
||||
const argvPtrs = [];
|
||||
this.argv.forEach((arg) => {
|
||||
argvPtrs.push(strPtr(arg));
|
||||
});
|
||||
argvPtrs.push(0);
|
||||
|
||||
const keys = Object.keys(this.env).sort();
|
||||
keys.forEach((key) => {
|
||||
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
|
||||
});
|
||||
argvPtrs.push(0);
|
||||
|
||||
const argv = offset;
|
||||
argvPtrs.forEach((ptr) => {
|
||||
this.mem.setUint32(offset, ptr, true);
|
||||
this.mem.setUint32(offset + 4, 0, true);
|
||||
offset += 8;
|
||||
});
|
||||
|
||||
// The linker guarantees global data starts from at least wasmMinDataAddr.
|
||||
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
|
||||
const wasmMinDataAddr = 4096 + 8192;
|
||||
if (offset >= wasmMinDataAddr) {
|
||||
throw new Error("total length of command line and environment variables exceeds limit");
|
||||
}
|
||||
|
||||
this._inst.exports.run(argc, argv);
|
||||
if (this.exited) {
|
||||
this._resolveExitPromise();
|
||||
}
|
||||
await this._exitPromise;
|
||||
}
|
||||
|
||||
_resume() {
|
||||
@@ -510,49 +572,31 @@
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
global.require &&
|
||||
global.require.main === module &&
|
||||
global.process &&
|
||||
global.process.versions &&
|
||||
!global.process.versions.electron
|
||||
) {
|
||||
if (process.argv.length != 3) {
|
||||
console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const go = new Go();
|
||||
WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
|
||||
return go.run(result.instance);
|
||||
}).catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
// wasm setup code
|
||||
export default function init (path) {
|
||||
if (typeof global === "undefined") {
|
||||
var global = globalThis;
|
||||
}
|
||||
return new Promise ((res) => {
|
||||
const go = new Go();
|
||||
var wasm;
|
||||
|
||||
const run = (obj) => {
|
||||
const wasm = obj.instance;
|
||||
global.wfa = wasm
|
||||
go.run(wasm);
|
||||
res(wasm)
|
||||
}
|
||||
if ('instantiateStreaming' in WebAssembly) {
|
||||
WebAssembly.instantiateStreaming(fetch(path), go.importObject).then(function (obj) {
|
||||
wasm = obj.instance;
|
||||
go.run(wasm);
|
||||
res()
|
||||
run(obj)
|
||||
})
|
||||
} else {
|
||||
fetch(path).then(resp =>
|
||||
resp.arrayBuffer()
|
||||
).then(bytes =>
|
||||
WebAssembly.instantiate(bytes, go.importObject).then(function (obj) {
|
||||
wasm = obj.instance;
|
||||
go.run(wasm);
|
||||
res()
|
||||
run(obj)
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user