feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
@@ -0,0 +1,112 @@
|
||||
// App runs the round trip's checks where go test does not reach, and the
|
||||
// SQLite plugin's: in an app on a phone, whose modules are their Swift on
|
||||
// iOS and their Kotlin on Android. It logs each check, then "roundtrip: PASS" or "roundtrip:
|
||||
// FAIL", which CI waits for in the system's log:
|
||||
//
|
||||
// go run ./cmd/mygo build -platform android/arm64 native/internal/roundtrip/app
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"runtime"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/native/internal/roundtrip/check"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
func main() {
|
||||
result := "running"
|
||||
mygo.App.WhenReady(func() {
|
||||
var w *mygo.Window
|
||||
w = mygo.NewWindow(mygo.WindowOptions{Title: "Round trip", Content: ui.View(func(c *ui.Context) {
|
||||
ui.Column(c).Fill().Padding(24).Children(func() {
|
||||
ui.Text(c, "roundtrip: "+result).FontSize(20)
|
||||
})
|
||||
})})
|
||||
go func() {
|
||||
failed := run()
|
||||
mygo.RunOnMain(func() {
|
||||
result = map[bool]string{true: "FAIL", false: "PASS"}[failed]
|
||||
w.Invalidate()
|
||||
})
|
||||
log.Printf("roundtrip: %s", map[bool]string{true: "FAIL", false: "PASS"}[failed])
|
||||
}()
|
||||
})
|
||||
if err := mygo.App.Run(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// run runs the checks, each on a goroutine of its own, as a test is, and
|
||||
// reports whether one failed.
|
||||
func run() bool {
|
||||
failed := false
|
||||
checks := append(check.All, struct {
|
||||
Name string
|
||||
Run func(check.T)
|
||||
}{"SQLite", checkSQLite})
|
||||
for _, c := range checks {
|
||||
t := &tester{name: c.Name}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.failed = true
|
||||
t.log(fmt.Sprint("panic: ", r))
|
||||
}
|
||||
}()
|
||||
c.Run(t)
|
||||
}()
|
||||
<-done
|
||||
for i := len(t.cleanups) - 1; i >= 0; i-- {
|
||||
t.cleanups[i]()
|
||||
}
|
||||
switch {
|
||||
case t.failed:
|
||||
failed = true
|
||||
log.Printf("roundtrip: --- FAIL: %s", c.Name)
|
||||
case t.skipped:
|
||||
// A check that skips here fails: the app is for where the module
|
||||
// runs.
|
||||
failed = true
|
||||
log.Printf("roundtrip: --- SKIP: %s", c.Name)
|
||||
default:
|
||||
log.Printf("roundtrip: --- ok: %s", c.Name)
|
||||
}
|
||||
}
|
||||
return failed
|
||||
}
|
||||
|
||||
// tester is a check's T: Fatal and Skip end its goroutine, as testing.T's
|
||||
// do.
|
||||
type tester struct {
|
||||
name string
|
||||
failed, skipped bool
|
||||
cleanups []func()
|
||||
}
|
||||
|
||||
func (t *tester) Helper() {}
|
||||
|
||||
func (t *tester) log(msg string) { log.Printf("roundtrip: %s: %s", t.name, msg) }
|
||||
|
||||
func (t *tester) Fatal(args ...any) {
|
||||
t.failed = true
|
||||
t.log(fmt.Sprint(args...))
|
||||
runtime.Goexit()
|
||||
}
|
||||
|
||||
func (t *tester) Fatalf(format string, args ...any) { t.Fatal(fmt.Sprintf(format, args...)) }
|
||||
|
||||
func (t *tester) Skip(args ...any) {
|
||||
t.skipped = true
|
||||
t.log(fmt.Sprint(args...))
|
||||
runtime.Goexit()
|
||||
}
|
||||
|
||||
func (t *tester) Context() context.Context { return context.Background() }
|
||||
|
||||
func (t *tester) Cleanup(f func()) { t.cleanups = append(t.cleanups, f) }
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"name": "Roundtrip",
|
||||
"identifier": "dev.mygo.roundtrip"
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
"github.com/egoist/mygo/native/internal/roundtrip/check"
|
||||
"github.com/egoist/mygo/plugins/sqlite"
|
||||
)
|
||||
|
||||
// checkSQLite checks the SQLite plugin's native module, which phones build
|
||||
// from its Swift and its Kotlin as they do the round trip's.
|
||||
func checkSQLite(t check.T) {
|
||||
ctx := context.Background()
|
||||
db, err := sqlite.Open(ctx, ":memory:", sqlite.OpenOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.Execute(ctx, "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT NOT NULL, score REAL, data BLOB)"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := db.Execute(ctx, "INSERT INTO t (name, score, data) VALUES (?, ?, ?)", "héllo 🌍", 0.5, []byte{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Changes != 1 || r.LastInsertID != 1 {
|
||||
t.Fatalf("insert: %+v", r)
|
||||
}
|
||||
rows, err := db.Query(ctx, "SELECT id, name, score, data, NULL AS none, sqlite_version() FROM t")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := sqlite.Rows{Columns: []string{"id", "name", "score", "data", "none", "sqlite_version()"}, Values: [][]any{{int64(1), "héllo 🌍", 0.5, []byte{}, nil, "3.53.4"}}}
|
||||
if !reflect.DeepEqual(rows, want) {
|
||||
t.Fatalf("query: %#v, want %#v", rows, want)
|
||||
}
|
||||
var e *sqlite.Error
|
||||
if _, err := db.Execute(ctx, "INSERT INTO t (name) VALUES (NULL)"); !errors.As(err, &e) || e.ExtendedCode != 1299 {
|
||||
t.Fatalf("NOT NULL: %v, want SQLITE_CONSTRAINT_NOTNULL", err)
|
||||
}
|
||||
if _, err := db.Execute(ctx, "SELEC 1"); !errors.As(err, &e) || e.Code != 1 {
|
||||
t.Fatalf("syntax: %v, want SQLITE_ERROR", err)
|
||||
}
|
||||
if _, err := db.Execute(ctx, "SELECT 1; SELECT 2"); err == nil {
|
||||
t.Fatal("two statements ran")
|
||||
}
|
||||
if _, err := db.Execute(ctx, "ATTACH ':memory:' AS other"); err == nil {
|
||||
t.Fatal("ATTACH ran")
|
||||
}
|
||||
results, err := db.Transaction(ctx, []sqlite.Statement{
|
||||
{SQL: "INSERT INTO t (name) VALUES (?)", Args: []any{"a"}},
|
||||
{SQL: "UPDATE t SET score = score + 1 WHERE score IS NOT NULL"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(results) != 2 || results[0].LastInsertID != 2 || results[1].Changes != 1 {
|
||||
t.Fatalf("transaction: %+v", results)
|
||||
}
|
||||
if _, err := db.Transaction(ctx, []sqlite.Statement{{SQL: "INSERT INTO t (name) VALUES ('b')"}, {SQL: "INSERT INTO t (name) VALUES (NULL)"}}); err == nil {
|
||||
t.Fatal("a failing transaction committed")
|
||||
}
|
||||
if rows, err := db.Query(ctx, "SELECT count(*) FROM t"); err != nil || rows.Values[0][0] != int64(2) {
|
||||
t.Fatalf("after rollback: %v %v", rows, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// Package check holds the checks of the round trip of every kind of value
|
||||
// through the module roundtrip, which its tests run under go test, and
|
||||
// its app (roundtrip/app) on phones, where go test does not reach.
|
||||
package check
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/native"
|
||||
"github.com/egoist/mygo/native/internal/roundtrip"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// T is what the checks use of a test: testing.T's methods, which the app
|
||||
// implements too.
|
||||
type T interface {
|
||||
Helper()
|
||||
Fatal(args ...any)
|
||||
Fatalf(format string, args ...any)
|
||||
Skip(args ...any)
|
||||
Context() context.Context
|
||||
Cleanup(func())
|
||||
}
|
||||
|
||||
// ctx is a context for a check, which ends with it, and after a while.
|
||||
func ctx(t T) context.Context {
|
||||
c, cancel := context.WithTimeout(t.Context(), time.Minute)
|
||||
t.Cleanup(cancel)
|
||||
return c
|
||||
}
|
||||
|
||||
// Echo makes the module's implementation, skipping where it is not built:
|
||||
// mygo native build -target host native/internal/roundtrip, with Swift.
|
||||
func Echo(t T) roundtrip.Echo {
|
||||
t.Helper()
|
||||
e, err := roundtrip.NewEcho()
|
||||
if errors.Is(err, errors.ErrUnsupported) {
|
||||
t.Skip("no implementation on this platform")
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), "mygo native build") {
|
||||
t.Skip(err)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func Scalars(t T) {
|
||||
e := Echo(t)
|
||||
got := e.Scalars(-5, 127, 65535, -7, 1<<63, 1.5, -2.25, true)
|
||||
want := roundtrip.Scalars{I: -4, I8: -128, U16: 0, I32: -6, U64: 1<<63 + 1, F32: 2.5, F: -1.25, B: false}
|
||||
if got != want {
|
||||
t.Fatalf("Scalars = %+v, want %+v", got, want)
|
||||
}
|
||||
if n := e.Add(40, 2); n != 42 {
|
||||
t.Fatalf("Add = %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func Text(t T) {
|
||||
e := Echo(t)
|
||||
got := e.Text("héllo, 世界\x00!", []byte{1, 2, 3})
|
||||
if got.S != "héllo, 世界\x00!héllo, 世界\x00!" || !bytes.Equal(got.B, []byte{3, 2, 1}) {
|
||||
t.Fatalf("Text = %+v", got)
|
||||
}
|
||||
if got := e.Text("", nil); got.S != "" || len(got.B) != 0 {
|
||||
t.Fatalf("Text of nothing = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func Record(t T) {
|
||||
e := Echo(t)
|
||||
in := roundtrip.Record{
|
||||
Name: "r",
|
||||
Counts: []int{1, -2, 3},
|
||||
Tags: map[string]string{"a": "1", "b": ""},
|
||||
Inner: roundtrip.Inner{X: 1.5, Y: -2},
|
||||
Next: &roundtrip.Inner{X: 3},
|
||||
Kind: roundtrip.KindB,
|
||||
Data: []byte("data"),
|
||||
}
|
||||
got, err := e.Record(in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Name != "r" || !slices.Equal(got.Counts, []int{2, -4, 6}) || len(got.Tags) != 2 || got.Tags["a"] != "1" ||
|
||||
got.Inner != in.Inner || got.Next == nil || *got.Next != *in.Next || got.Kind != roundtrip.KindB || string(got.Data) != "data" {
|
||||
t.Fatalf("Record = %+v", got)
|
||||
}
|
||||
got, err = e.Record(roundtrip.Record{Kind: roundtrip.KindA})
|
||||
if err != nil || got.Next != nil || len(got.Counts) != 0 || len(got.Tags) != 0 {
|
||||
t.Fatalf("Record of zeros = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func Lists(t T) {
|
||||
e := Echo(t)
|
||||
got, err := e.Lists([]string{"a", "bb", "世"}, [][]int{{1, 2}, {}, {3}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 4 || got["a"] != 1 || got["bb"] != 2 || got["世"] != 3 || got["nested"] != 6 {
|
||||
t.Fatalf("Lists = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func Maybe(t T) {
|
||||
e := Echo(t)
|
||||
n := 41
|
||||
if got := e.Maybe(&n); got == nil || *got != 42 {
|
||||
t.Fatalf("Maybe(41) = %v", got)
|
||||
}
|
||||
if got := e.Maybe(nil); got != nil {
|
||||
t.Fatalf("Maybe(nil) = %v", *got)
|
||||
}
|
||||
}
|
||||
|
||||
func Times(t T) {
|
||||
e := Echo(t)
|
||||
at := time.Date(2026, 11, 7, 12, 30, 0, 125_000_000, time.UTC)
|
||||
got, err := e.Times(at, 1500*time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d := got.At.Sub(at.Add(1500 * time.Millisecond)); d < -time.Millisecond || d > time.Millisecond || got.Twice != 3*time.Second {
|
||||
t.Fatalf("Times = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func Kinds(t T) {
|
||||
e := Echo(t)
|
||||
got, err := e.Kind(roundtrip.KindC, roundtrip.Low)
|
||||
if err != nil || got.Kind != roundtrip.KindA || got.Level != roundtrip.High {
|
||||
t.Fatalf("Kind = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func Errors(t T) {
|
||||
e := Echo(t)
|
||||
if err := e.Fail(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Fail("named"); !errors.Is(err, roundtrip.ErrNamed) {
|
||||
t.Fatalf("Fail(named) = %v", err)
|
||||
}
|
||||
if err := e.Fail("unsupported"); !errors.Is(err, errors.ErrUnsupported) {
|
||||
t.Fatalf("Fail(unsupported) = %v", err)
|
||||
}
|
||||
var ne *native.Error
|
||||
if err := e.Fail("other"); !errors.As(err, &ne) || ne.Domain != "RoundtripDomain" || ne.Number != 7 || ne.Message != "other" {
|
||||
t.Fatalf("Fail(other) = %#v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Async(t T) {
|
||||
e := Echo(t)
|
||||
s, err := e.Wait(ctx(t), time.Millisecond, "done")
|
||||
if err != nil || s != "done" {
|
||||
t.Fatalf("Wait = %q, %v", s, err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx(t), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, err := e.Wait(ctx, time.Minute, "never"); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("Wait canceled = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Streams(t T) {
|
||||
e := Echo(t)
|
||||
var got []int
|
||||
for n, err := range e.Count(ctx(t), 5, -1) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, n)
|
||||
}
|
||||
if !slices.Equal(got, []int{0, 1, 2, 3, 4}) {
|
||||
t.Fatalf("Count = %v", got)
|
||||
}
|
||||
got = nil
|
||||
var last error
|
||||
for n, err := range e.Count(ctx(t), 5, 2) {
|
||||
if err != nil {
|
||||
last = err
|
||||
break
|
||||
}
|
||||
got = append(got, n)
|
||||
}
|
||||
if !slices.Equal(got, []int{0, 1}) || !errors.Is(last, roundtrip.ErrNamed) {
|
||||
t.Fatalf("Count failing = %v, %v", got, last)
|
||||
}
|
||||
// Breaking out early stops the stream.
|
||||
for n := range e.Count(ctx(t), 1000, -1) {
|
||||
if n == 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
var names []string
|
||||
for r, err := range e.Records(ctx(t), 3) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names = append(names, r.Name+":"+r.Tags["i"])
|
||||
}
|
||||
if !slices.Equal(names, []string{"r0:0", "r1:1", "r2:2"}) {
|
||||
t.Fatalf("Records = %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func Objects(t T) {
|
||||
e := Echo(t)
|
||||
c, err := e.Counter(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a, b := c.Next(), c.Next(); a != 10 || b != 11 {
|
||||
t.Fatalf("Next = %d, %d", a, b)
|
||||
}
|
||||
d := c.Same()
|
||||
if n := d.Next(); n != 12 {
|
||||
t.Fatalf("Same().Next() = %d", n)
|
||||
}
|
||||
if err := c.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.Close(); !errors.Is(err, native.ErrClosed) {
|
||||
t.Fatalf("second Close = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Callbacks(t T) {
|
||||
e := Echo(t)
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
n := e.Each([]string{"a", "b", "c"}, func(word string, i int) {
|
||||
mu.Lock()
|
||||
seen = append(seen, word+string(rune('0'+i)))
|
||||
mu.Unlock()
|
||||
})
|
||||
native.Flush()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if n != 3 || !slices.Equal(seen, []string{"a0", "b1", "c2"}) {
|
||||
t.Fatalf("Each = %d, %v", n, seen)
|
||||
}
|
||||
sum, err := e.Ask([]int{1, 2, 3}, func(n int) (int, error) { return 2 * n, nil })
|
||||
if err != nil || sum != 12 {
|
||||
t.Fatalf("Ask = %d, %v", sum, err)
|
||||
}
|
||||
boom := errors.New("boom")
|
||||
if _, err := e.Ask([]int{1}, func(int) (int, error) { return 0, boom }); err == nil || !strings.Contains(err.Error(), "boom") {
|
||||
t.Fatalf("Ask failing = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Ticks(t T) {
|
||||
e := Echo(t)
|
||||
var n atomic.Int64
|
||||
c := e.Ticks(time.Millisecond, func(i int) { n.Store(int64(i)) })
|
||||
// f runs on Go's main thread, which an Android emulator keeps busy for
|
||||
// seconds as the app draws its first frames.
|
||||
deadline := time.Now().Add(30 * time.Second)
|
||||
for n.Load() < 3 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if err := c.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n.Load() < 3 {
|
||||
t.Fatalf("ticked %d times", n.Load())
|
||||
}
|
||||
}
|
||||
|
||||
type scorer struct{}
|
||||
|
||||
func (scorer) Score(word string) float64 { return float64(len(word)) }
|
||||
|
||||
func (scorer) Explain(ctx context.Context, word string) (string, error) {
|
||||
select {
|
||||
case <-time.After(time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return "because " + word, nil
|
||||
}
|
||||
|
||||
func GoImplements(t T) {
|
||||
e := Echo(t)
|
||||
got, err := e.Use(ctx(t), scorer{}, []string{"ab", "cde"})
|
||||
if err != nil || got != 5+float64(len("because ab")) {
|
||||
t.Fatalf("Use = %v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func Buffer(t T) {
|
||||
e := Echo(t)
|
||||
buf := native.NewBuffer(300)
|
||||
n, err := e.Fill(buf, 0x55)
|
||||
if err != nil || n != 300 {
|
||||
t.Fatalf("Fill = %d, %v", n, err)
|
||||
}
|
||||
for i, b := range buf.Bytes() {
|
||||
if b != byte(i^0x55) {
|
||||
t.Fatalf("byte %d = %#x", i, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func More(t T) {
|
||||
e := Echo(t)
|
||||
if got := e.Mix(1.5, 2.25, true, -3); got != 1.75 {
|
||||
t.Fatalf("Mix = %v", got)
|
||||
}
|
||||
if got := e.Mix(0, -0.5, false, 127); got != 126.5 {
|
||||
t.Fatalf("Mix = %v", got)
|
||||
}
|
||||
got, err := e.Box(ui.Rect{X: 1, Y: 2, W: 3, H: 4.5})
|
||||
if err != nil || got != (ui.Rect{X: 4, Y: 6.5, W: 3, H: 4.5}) {
|
||||
t.Fatalf("Box = %+v, %v", got, err)
|
||||
}
|
||||
if n := e.Nothing(make([]roundtrip.Empty, 3)); n != 3 {
|
||||
t.Fatalf("Nothing = %d", n)
|
||||
}
|
||||
// Main-thread methods wait for the app, which tests do not run.
|
||||
if !mygo.App.IsReady() {
|
||||
if _, err := e.OnMain(roundtrip.Record{}, nil); err == nil {
|
||||
t.Fatal("OnMain ran off the main thread")
|
||||
}
|
||||
} else {
|
||||
// f, which returns nothing, runs later on Go's main thread.
|
||||
in := make(chan roundtrip.Inner, 1)
|
||||
got, err := e.OnMain(roundtrip.Record{Name: "main", Kind: roundtrip.KindA, Inner: roundtrip.Inner{X: 2}}, func(i roundtrip.Inner) { in <- i })
|
||||
if err != nil || got.S != "main" {
|
||||
t.Fatalf("OnMain = %+v, %v", got, err)
|
||||
}
|
||||
if i := <-in; i.X != 2 {
|
||||
t.Fatalf("OnMain's f got %+v", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// All are the checks, by name.
|
||||
var All = []struct {
|
||||
Name string
|
||||
Run func(T)
|
||||
}{
|
||||
{"Scalars", Scalars},
|
||||
{"Text", Text},
|
||||
{"Record", Record},
|
||||
{"Lists", Lists},
|
||||
{"Maybe", Maybe},
|
||||
{"Times", Times},
|
||||
{"Kinds", Kinds},
|
||||
{"Errors", Errors},
|
||||
{"Async", Async},
|
||||
{"Streams", Streams},
|
||||
{"Objects", Objects},
|
||||
{"Callbacks", Callbacks},
|
||||
{"Ticks", Ticks},
|
||||
{"GoImplements", GoImplements},
|
||||
{"Buffer", Buffer},
|
||||
{"More", More},
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/build
|
||||
@@ -0,0 +1,15 @@
|
||||
// The Kotlin of the native module roundtrip: an Android library, which mygo
|
||||
// build adds to the app's Gradle build. The build sets its SDK levels, Java
|
||||
// and Kotlin, and its dependency on MyGo's host library (dev.mygo), which
|
||||
// brings coroutines: add only what the implementation uses.
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.github.egoist.mygo.native_.internal.roundtrip"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.github.egoist.mygo.native_.internal.roundtrip
|
||||
|
||||
import android.graphics.RectF
|
||||
import dev.mygo.NativeBuffer
|
||||
import dev.mygo.NativeCloser
|
||||
import dev.mygo.NativeException
|
||||
import dev.mygo.NativeUnsupportedException
|
||||
import java.time.Instant
|
||||
import java.util.Timer
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlin.concurrent.fixedRateTimer
|
||||
import kotlin.time.Duration
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
// The implementation of package roundtrip on Android: every value it is
|
||||
// given, back, as the Swift, Rust and Zig ones do.
|
||||
|
||||
fun makeEcho(): Echo = Echoer()
|
||||
|
||||
private class Echoer : Echo {
|
||||
override fun scalars(i: Long, i8: Byte, u16: UShort, i32: Int, u64: ULong, f32: Float, f: Double, b: Boolean): Scalars =
|
||||
Scalars(i + 1, (i8 + 1).toByte(), (u16 + 1u).toUShort(), i32 + 1, u64 + 1u, f32 + 1, f + 1, !b)
|
||||
|
||||
override fun add(a: Long, b: Long): Long = a + b
|
||||
|
||||
override fun text(s: String, b: ByteArray): Texts = Texts(s + s, b.reversedArray())
|
||||
|
||||
override fun record(r: Record): Record = r.copy(counts = r.counts.map { it * 2 })
|
||||
|
||||
override fun lists(words: List<String>, nested: List<List<Long>>): Map<String, Long> {
|
||||
val m = HashMap<String, Long>()
|
||||
for (w in words) m[w] = w.toByteArray(Charsets.UTF_8).size.toLong()
|
||||
m["nested"] = nested.sumOf { it.sum() }
|
||||
return m
|
||||
}
|
||||
|
||||
override fun maybe(p: Long?): Long? = p?.plus(1)
|
||||
|
||||
override fun times(t: Instant, d: Duration): Moment = Moment(t.plusNanos(d.inWholeNanoseconds), d * 2)
|
||||
|
||||
override fun kind(k: Kind, l: Level): Kinds {
|
||||
val all = Kind.entries
|
||||
return Kinds(all[(all.indexOf(k) + 1) % all.size], if (l == Level.LOW) Level.HIGH else Level.LOW)
|
||||
}
|
||||
|
||||
override fun fail(name: String) {
|
||||
when (name) {
|
||||
"" -> return
|
||||
"named" -> throw RoundtripException(RoundtripError.NAMED)
|
||||
"unsupported" -> throw NativeUnsupportedException()
|
||||
else -> throw NativeException("RoundtripDomain", 7, name)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun wait(d: Duration, s: String): String {
|
||||
delay(d)
|
||||
return s
|
||||
}
|
||||
|
||||
override fun count(n: Long, fail: Long): Flow<Long> = flow {
|
||||
for (i in 0 until n) {
|
||||
if (i == fail) throw RoundtripException(RoundtripError.NAMED)
|
||||
emit(i)
|
||||
}
|
||||
}
|
||||
|
||||
override fun records(n: Long): Flow<Record> = flow {
|
||||
for (i in 0 until n) {
|
||||
emit(Record("r$i", listOf(i), mapOf("i" to "$i"), Inner(i.toDouble(), 0.0), null, Kind.KIND_A, byteArrayOf(i.toByte())))
|
||||
}
|
||||
}
|
||||
|
||||
override fun counter(n: Long): Counter = Counting(n)
|
||||
|
||||
override fun each(words: List<String>, f: (String, Long) -> Unit): Long {
|
||||
words.forEachIndexed { i, w -> f(w, i.toLong()) }
|
||||
return words.size.toLong()
|
||||
}
|
||||
|
||||
override fun ask(ns: List<Long>, f: (Long) -> Long): Long = ns.sumOf { f(it) }
|
||||
|
||||
override fun ticks(interval: Duration, f: (Long) -> Unit): AutoCloseable {
|
||||
var n = 0L
|
||||
val period = maxOf(interval.inWholeMilliseconds, 1)
|
||||
val timer: Timer = fixedRateTimer("roundtrip-ticks", daemon = true, initialDelay = period, period = period) {
|
||||
n++
|
||||
f(n)
|
||||
}
|
||||
return NativeCloser { timer.cancel() }
|
||||
}
|
||||
|
||||
override suspend fun use(s: Scorer, words: List<String>): Double {
|
||||
var sum = words.sumOf { s.score(it) }
|
||||
words.firstOrNull()?.let { sum += s.explain(it).toByteArray(Charsets.UTF_8).size }
|
||||
return sum
|
||||
}
|
||||
|
||||
override fun fill(buf: NativeBuffer, x: Long): Long {
|
||||
val b = buf.bytes
|
||||
for (i in 0 until buf.size) b.put(i, (i.toLong() xor x).toByte())
|
||||
return buf.size.toLong()
|
||||
}
|
||||
|
||||
override fun mix(f: Float, d: Double, b: Boolean, i: Byte): Double = f + d + (if (b) 1 else 0) + i
|
||||
|
||||
override fun box(r: RectF): RectF = RectF(r).apply { offset(r.width(), r.height()) }
|
||||
|
||||
override fun nothing(e: List<Empty>): Long = e.size.toLong()
|
||||
|
||||
override fun onMain(r: Record, f: (Inner) -> Unit): Texts {
|
||||
f(r.inner)
|
||||
return Texts(r.name, r.data)
|
||||
}
|
||||
}
|
||||
|
||||
private class Counting(start: Long) : Counter {
|
||||
private val n = AtomicLong(start)
|
||||
|
||||
override fun next(): Long = n.getAndIncrement()
|
||||
|
||||
override fun same(): Counter = Counting(n.get())
|
||||
|
||||
override fun close() {}
|
||||
}
|
||||
+742
@@ -0,0 +1,742 @@
|
||||
// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.
|
||||
// mygo:native 3 aebdfd9f7bfb2215
|
||||
//
|
||||
// The declarations of package roundtrip, which the implementation implements,
|
||||
// and the object Go calls. See docs/native-modules.md.
|
||||
|
||||
@file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE", "RedundantVisibilityModifier", "FunctionName", "ClassName", "LocalVariableName")
|
||||
|
||||
package com.github.egoist.mygo.native_.internal.roundtrip
|
||||
|
||||
import dev.mygo.GoFunc
|
||||
import dev.mygo.NativeBuffer
|
||||
import dev.mygo.NativeCodedError
|
||||
import dev.mygo.NativeModule
|
||||
import dev.mygo.NativeReader
|
||||
import dev.mygo.NativeWireException
|
||||
import dev.mygo.NativeWriter
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Echo returns what it is given.
|
||||
*/
|
||||
interface Echo {
|
||||
/**
|
||||
* Scalars returns its arguments, one more each.
|
||||
*/
|
||||
fun scalars(i: Long, i8: Byte, u16: UShort, i32: Int, u64: ULong, f32: Float, f: Double, b: Boolean): Scalars
|
||||
/**
|
||||
* Add is a plain sum, the cheapest call.
|
||||
*/
|
||||
fun add(a: Long, b: Long): Long
|
||||
/**
|
||||
* Text returns s twice, and b reversed.
|
||||
*/
|
||||
fun text(s: String, b: ByteArray): Texts
|
||||
/**
|
||||
* Record returns r with its counts doubled.
|
||||
*/
|
||||
fun record(r: Record): Record
|
||||
/**
|
||||
* Lists returns the lengths of the words, and a map of each to its
|
||||
* length.
|
||||
*/
|
||||
fun lists(words: List<String>, nested: List<List<Long>>): Map<String, Long>
|
||||
/**
|
||||
* Maybe returns p's value plus one, or nil for nil.
|
||||
*/
|
||||
fun maybe(p: Long?): Long?
|
||||
/**
|
||||
* Times returns t moved by d, and d doubled.
|
||||
*/
|
||||
fun times(t: java.time.Instant, d: kotlin.time.Duration): Moment
|
||||
/**
|
||||
* Kind returns the next kind, and the next level.
|
||||
*/
|
||||
fun kind(k: Kind, l: Level): Kinds
|
||||
/**
|
||||
* Fail throws the error named, or nothing for "".
|
||||
*/
|
||||
fun fail(name: String)
|
||||
/**
|
||||
* Wait waits d, or until ctx is done, then returns s.
|
||||
*/
|
||||
suspend fun wait(d: kotlin.time.Duration, s: String): String
|
||||
/**
|
||||
* Count yields 0 to n-1, failing at fail when it is not -1.
|
||||
*/
|
||||
fun count(n: Long, fail: Long): Flow<Long>
|
||||
/**
|
||||
* Records yields n records.
|
||||
*/
|
||||
fun records(n: Long): Flow<Record>
|
||||
/**
|
||||
* Counter makes a counter starting at n.
|
||||
*/
|
||||
fun counter(n: Long): Counter
|
||||
/**
|
||||
* Each calls f with each word and its index, and returns how many.
|
||||
*/
|
||||
fun each(words: List<String>, f: (String, Long) -> kotlin.Unit): Long
|
||||
/**
|
||||
* Ask asks f for the double of each number, and returns their sum.
|
||||
*/
|
||||
fun ask(ns: List<Long>, f: (Long) -> Long): Long
|
||||
/**
|
||||
* Ticks calls f every interval until closed.
|
||||
*/
|
||||
fun ticks(interval: kotlin.time.Duration, f: (Long) -> kotlin.Unit): AutoCloseable
|
||||
/**
|
||||
* Use asks s for a score of each word, and returns their sum.
|
||||
*/
|
||||
suspend fun use(s: Scorer, words: List<String>): Double
|
||||
/**
|
||||
* Fill writes b's index into each byte of buf, xor x.
|
||||
*/
|
||||
fun fill(buf: NativeBuffer, x: Long): Long
|
||||
/**
|
||||
* Mix sums numbers of each kind, a call of numbers only.
|
||||
*/
|
||||
fun mix(f: Float, d: Double, b: Boolean, i: Byte): Double
|
||||
/**
|
||||
* Box returns r moved by its size.
|
||||
*/
|
||||
fun box(r: android.graphics.RectF): android.graphics.RectF
|
||||
/**
|
||||
* Nothing returns how many structs without fields it was given.
|
||||
*/
|
||||
fun nothing(e: List<Empty>): Long
|
||||
/**
|
||||
* OnMain runs on the main thread, which go test does not run: the
|
||||
* tests only build it.
|
||||
* It runs on the main thread.
|
||||
*/
|
||||
fun onMain(r: Record, f: (Inner) -> kotlin.Unit): Texts
|
||||
}
|
||||
|
||||
/**
|
||||
* Counter counts.
|
||||
*/
|
||||
interface Counter : AutoCloseable {
|
||||
/**
|
||||
* Next returns the count, then adds one.
|
||||
*/
|
||||
fun next(): Long
|
||||
/**
|
||||
* Same returns another counter of the same count.
|
||||
*/
|
||||
fun same(): Counter
|
||||
}
|
||||
|
||||
/**
|
||||
* Scorer is implemented by Go.
|
||||
* Go implements it: the module's Kotlin calls it.
|
||||
*/
|
||||
interface Scorer {
|
||||
/**
|
||||
* Score scores a word.
|
||||
*/
|
||||
fun score(word: String): Double
|
||||
/**
|
||||
* Explain explains a score, which may wait.
|
||||
*/
|
||||
suspend fun explain(word: String): String
|
||||
}
|
||||
|
||||
/**
|
||||
* Scalars are the scalars back.
|
||||
*/
|
||||
data class Scalars(
|
||||
val i: Long,
|
||||
val i8: Byte,
|
||||
val u16: UShort,
|
||||
val i32: Int,
|
||||
val u64: ULong,
|
||||
val f32: Float,
|
||||
val f: Double,
|
||||
val b: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Texts are a string and bytes back.
|
||||
*/
|
||||
data class Texts(
|
||||
val s: String,
|
||||
val b: ByteArray = ByteArray(0),
|
||||
)
|
||||
|
||||
/**
|
||||
* Inner is nested.
|
||||
*/
|
||||
data class Inner(
|
||||
val x: Double,
|
||||
val y: Double,
|
||||
)
|
||||
|
||||
/**
|
||||
* Record is a struct with every kind of field.
|
||||
*/
|
||||
data class Record(
|
||||
val name: String,
|
||||
val counts: List<Long> = emptyList(),
|
||||
val tags: Map<String, String> = emptyMap(),
|
||||
val inner: Inner,
|
||||
val next: Inner? = null,
|
||||
val kind: Kind,
|
||||
val data: ByteArray = ByteArray(0),
|
||||
)
|
||||
|
||||
/**
|
||||
* Moment is a time and a duration back.
|
||||
*/
|
||||
data class Moment(
|
||||
val at: java.time.Instant,
|
||||
val twice: kotlin.time.Duration,
|
||||
)
|
||||
|
||||
/**
|
||||
* Kinds are an enum of each kind back.
|
||||
*/
|
||||
data class Kinds(
|
||||
val kind: Kind,
|
||||
val level: Level,
|
||||
)
|
||||
|
||||
/**
|
||||
* Empty has no fields.
|
||||
*/
|
||||
class Empty {
|
||||
override fun equals(other: Any?): Boolean = other is Empty
|
||||
override fun hashCode(): Int = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Kind is a string enum.
|
||||
*/
|
||||
enum class Kind(val value: String) {
|
||||
KIND_A("a"),
|
||||
KIND_B("b"),
|
||||
KIND_C("c"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
/** The constant of a value, which Go sent. */
|
||||
fun of(value: String): Kind = entries.firstOrNull { it.value == value } ?: throw NativeWireException("native: Kind has no constant $value")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Level is an integer enum.
|
||||
*/
|
||||
enum class Level(val value: Long) {
|
||||
LOW(1L),
|
||||
HIGH(2L),
|
||||
;
|
||||
|
||||
companion object {
|
||||
/** The constant of a value, which Go sent. */
|
||||
fun of(value: Long): Level = entries.firstOrNull { it.value == value } ?: throw NativeWireException("native: Level has no constant $value")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The errors package roundtrip declares, with native.NewError: throw
|
||||
* RoundtripException(RoundtripError.X) for Go to get that error, which errors.Is
|
||||
* compares.
|
||||
*/
|
||||
enum class RoundtripError(val code: String) {
|
||||
/**
|
||||
* ErrNamed is the error Fail throws for "named".
|
||||
*/
|
||||
NAMED("named"),
|
||||
;
|
||||
}
|
||||
|
||||
/** An error package roundtrip declares. */
|
||||
class RoundtripException(val error: RoundtripError, message: String = error.code) : Exception(message), NativeCodedError {
|
||||
override val nativeCode: String get() = error.code
|
||||
}
|
||||
|
||||
/** What Go calls: the functions of the module, by name. */
|
||||
object MygoModule : NativeModule() {
|
||||
override fun invoke(sym: String, h: Long, args: ByteArray, call: Long): ByteArray = when (sym) {
|
||||
"new_Echo" -> answer { _w -> _w.u64(retain(makeEcho())) }
|
||||
"Echo_Scalars" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.i64()
|
||||
val _p1 = _a.i64().toByte()
|
||||
val _p2 = _a.i64().toUShort()
|
||||
val _p3 = _a.i64().toInt()
|
||||
val _p4 = _a.i64().toULong()
|
||||
val _p5 = _a.double().toFloat()
|
||||
val _p6 = _a.double()
|
||||
val _p7 = _a.bool()
|
||||
val _r = _o.scalars(_p0, _p1, _p2, _p3, _p4, _p5, _p6, _p7)
|
||||
_write_Scalars(_w, _r)
|
||||
}
|
||||
"Echo_Add" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.i64()
|
||||
val _p1 = _a.i64()
|
||||
val _r = _o.add(_p0, _p1)
|
||||
_w.i64(_r.toLong())
|
||||
}
|
||||
"Echo_Text" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.string()
|
||||
val _p1 = _a.data()
|
||||
val _r = _o.text(_p0, _p1)
|
||||
_write_Texts(_w, _r)
|
||||
}
|
||||
"Echo_Record" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_Record(_a)
|
||||
val _r = _o.record(_p0)
|
||||
_write_Record(_w, _r)
|
||||
}
|
||||
"Echo_Lists" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_slice_string(_a)
|
||||
val _p1 = _read_slice_slice_int(_a)
|
||||
val _r = _o.lists(_p0, _p1)
|
||||
_write_map_int(_w, _r)
|
||||
}
|
||||
"Echo_Maybe" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_ptr_int(_a)
|
||||
val _r = _o.maybe(_p0)
|
||||
_write_ptr_int(_w, _r)
|
||||
}
|
||||
"Echo_Times" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.time()
|
||||
val _p1 = _a.duration()
|
||||
val _r = _o.times(_p0, _p1)
|
||||
_write_Moment(_w, _r)
|
||||
}
|
||||
"Echo_Kind" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_Kind(_a)
|
||||
val _p1 = _read_Level(_a)
|
||||
val _r = _o.kind(_p0, _p1)
|
||||
_write_Kinds(_w, _r)
|
||||
}
|
||||
"Echo_Fail" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.string()
|
||||
_o.fail(_p0)
|
||||
}
|
||||
"Echo_Wait" -> start {
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.duration()
|
||||
val _p1 = _a.string()
|
||||
task(call, false) { _w ->
|
||||
val _r = _o.wait(_p0, _p1)
|
||||
_w.string(_r)
|
||||
}
|
||||
}
|
||||
"Echo_Count" -> start {
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.i64()
|
||||
val _p1 = _a.i64()
|
||||
stream(call, false, { _o.count(_p0, _p1) }) { _w, _r -> _w.i64(_r.toLong()) }
|
||||
}
|
||||
"Echo_Records" -> start {
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.i64()
|
||||
stream(call, false, { _o.records(_p0) }) { _w, _r -> _write_Record(_w, _r) }
|
||||
}
|
||||
"Echo_Counter" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.i64()
|
||||
val _r = _o.counter(_p0)
|
||||
_w.u64(MygoModule.handle(_r))
|
||||
}
|
||||
"Echo_Each" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_slice_string(_a)
|
||||
val _p1 = _a.u64()
|
||||
val _g1 = goFunc(_p1)
|
||||
val _f1: (String, Long) -> kotlin.Unit = { q0, q1 ->
|
||||
val _cw = NativeWriter()
|
||||
_cw.string(q0)
|
||||
_cw.i64(q1.toLong())
|
||||
_g1.notify(_cw)
|
||||
}
|
||||
val _r = _o.each(_p0, _f1)
|
||||
_w.i64(_r.toLong())
|
||||
}
|
||||
"Echo_Ask" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_slice_int(_a)
|
||||
val _p1 = _a.u64()
|
||||
val _g1 = goFunc(_p1)
|
||||
val _f1: (Long) -> Long = { q0 ->
|
||||
val _cw = NativeWriter()
|
||||
_cw.i64(q0.toLong())
|
||||
_g1.ask(_cw) { _r -> _r.i64() }
|
||||
}
|
||||
val _r = _o.ask(_p0, _f1)
|
||||
_w.i64(_r.toLong())
|
||||
}
|
||||
"Echo_Ticks" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.duration()
|
||||
val _p1 = _a.u64()
|
||||
val _g1 = goFunc(_p1)
|
||||
val _f1: (Long) -> kotlin.Unit = { q0 ->
|
||||
val _cw = NativeWriter()
|
||||
_cw.i64(q0.toLong())
|
||||
_g1.notify(_cw)
|
||||
}
|
||||
_w.u64(retain(_o.ticks(_p0, _f1)))
|
||||
}
|
||||
"Echo_Use" -> start {
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.u64()
|
||||
val _p1 = _read_slice_string(_a)
|
||||
task(call, false) { _w ->
|
||||
val _r = _o.use(_GoScorer(_p0), _p1)
|
||||
_w.double(_r.toDouble())
|
||||
}
|
||||
}
|
||||
"Echo_Fill" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.buffer()
|
||||
val _p1 = _a.i64()
|
||||
val _r = _o.fill(_p0, _p1)
|
||||
_w.i64(_r.toLong())
|
||||
}
|
||||
"Echo_Mix" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.double().toFloat()
|
||||
val _p1 = _a.double()
|
||||
val _p2 = _a.bool()
|
||||
val _p3 = _a.i64().toByte()
|
||||
val _r = _o.mix(_p0, _p1, _p2, _p3)
|
||||
_w.double(_r.toDouble())
|
||||
}
|
||||
"Echo_Box" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _a.rect()
|
||||
val _r = _o.box(_p0)
|
||||
_w.rect(_r)
|
||||
}
|
||||
"Echo_Nothing" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_slice_Empty(_a)
|
||||
val _r = _o.nothing(_p0)
|
||||
_w.i64(_r.toLong())
|
||||
}
|
||||
"Echo_OnMain" -> answer { _w ->
|
||||
val _o: Echo = obj(h)
|
||||
val _a = NativeReader(args)
|
||||
val _p0 = _read_Record(_a)
|
||||
val _p1 = _a.u64()
|
||||
val _g1 = goFunc(_p1)
|
||||
val _f1: (Inner) -> kotlin.Unit = { q0 ->
|
||||
val _cw = NativeWriter()
|
||||
_write_Inner(_cw, q0)
|
||||
_g1.notify(_cw)
|
||||
}
|
||||
val _r = _o.onMain(_p0, _f1)
|
||||
_write_Texts(_w, _r)
|
||||
}
|
||||
"Counter_Next" -> answer { _w ->
|
||||
val _o: Counter = obj(h)
|
||||
val _r = _o.next()
|
||||
_w.i64(_r.toLong())
|
||||
}
|
||||
"Counter_Same" -> answer { _w ->
|
||||
val _o: Counter = obj(h)
|
||||
val _r = _o.same()
|
||||
_w.u64(MygoModule.handle(_r))
|
||||
}
|
||||
"close" -> answer { close(h) }
|
||||
else -> unknown(sym)
|
||||
}
|
||||
|
||||
override fun direct(sym: String, h: Long, args: LongArray): Long = try {
|
||||
when (sym) {
|
||||
"Echo_Add_direct" -> {
|
||||
obj<Echo>(h).add(args[0], args[1]).toLong()
|
||||
}
|
||||
"Echo_Mix_direct" -> {
|
||||
obj<Echo>(h).mix(Double.fromBits(args[0]).toFloat(), Double.fromBits(args[1]), args[2] != 0L, args[3].toByte()).toDouble().toRawBits()
|
||||
}
|
||||
"Counter_Next_direct" -> {
|
||||
obj<Counter>(h).next().toLong()
|
||||
}
|
||||
else -> 0L
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
0L
|
||||
}
|
||||
|
||||
override fun error(code: String): Throwable? = RoundtripError.entries.firstOrNull { it.code == code }?.let { RoundtripException(it) }
|
||||
|
||||
/** A handle of an object of the implementation, which Go holds. */
|
||||
fun handle(v: Any): Long = retain(v)
|
||||
}
|
||||
|
||||
/** Calls a Go value implementing Scorer. */
|
||||
internal class _GoScorer(private val _id: Long) : Scorer {
|
||||
init {
|
||||
if (_id == 0L) throw NativeWireException("Roundtrip: Go passed nil for Scorer")
|
||||
MygoModule.releaseWith(this, _id)
|
||||
}
|
||||
override fun score(word: String): Double {
|
||||
val _w = NativeWriter()
|
||||
_w.i64(0)
|
||||
_w.string(word)
|
||||
return MygoModule.invokeGo(_id, _w) { _r -> _r.double() }
|
||||
}
|
||||
override suspend fun explain(word: String): String {
|
||||
val _w = NativeWriter()
|
||||
_w.i64(1)
|
||||
_w.string(word)
|
||||
return MygoModule.invokeGoAsync(_id, _w) { _r -> _r.string() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun _read_Empty(r: NativeReader): Empty {
|
||||
r.bool()
|
||||
return Empty()
|
||||
}
|
||||
|
||||
private fun _write_Empty(w: NativeWriter, v: Empty) {
|
||||
w.bool(false)
|
||||
}
|
||||
|
||||
private fun _read_Inner(r: NativeReader): Inner {
|
||||
return Inner(
|
||||
x = r.double(),
|
||||
y = r.double(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun _write_Inner(w: NativeWriter, v: Inner) {
|
||||
w.double(v.x.toDouble())
|
||||
w.double(v.y.toDouble())
|
||||
}
|
||||
|
||||
private fun _read_Kind(r: NativeReader): Kind {
|
||||
return Kind.of(r.string())
|
||||
}
|
||||
|
||||
private fun _write_Kind(w: NativeWriter, v: Kind) {
|
||||
w.string(v.value)
|
||||
}
|
||||
|
||||
private fun _read_Kinds(r: NativeReader): Kinds {
|
||||
return Kinds(
|
||||
kind = _read_Kind(r),
|
||||
level = _read_Level(r),
|
||||
)
|
||||
}
|
||||
|
||||
private fun _write_Kinds(w: NativeWriter, v: Kinds) {
|
||||
_write_Kind(w, v.kind)
|
||||
_write_Level(w, v.level)
|
||||
}
|
||||
|
||||
private fun _read_Level(r: NativeReader): Level {
|
||||
return Level.of(r.i64())
|
||||
}
|
||||
|
||||
private fun _write_Level(w: NativeWriter, v: Level) {
|
||||
w.i64(v.value)
|
||||
}
|
||||
|
||||
private fun _read_Moment(r: NativeReader): Moment {
|
||||
return Moment(
|
||||
at = r.time(),
|
||||
twice = r.duration(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun _write_Moment(w: NativeWriter, v: Moment) {
|
||||
w.time(v.at)
|
||||
w.duration(v.twice)
|
||||
}
|
||||
|
||||
private fun _read_Record(r: NativeReader): Record {
|
||||
return Record(
|
||||
name = r.string(),
|
||||
counts = _read_slice_int(r),
|
||||
tags = _read_map_string(r),
|
||||
inner = _read_Inner(r),
|
||||
next = _read_ptr_Inner(r),
|
||||
kind = _read_Kind(r),
|
||||
data = r.data(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun _write_Record(w: NativeWriter, v: Record) {
|
||||
w.string(v.name)
|
||||
_write_slice_int(w, v.counts)
|
||||
_write_map_string(w, v.tags)
|
||||
_write_Inner(w, v.inner)
|
||||
_write_ptr_Inner(w, v.next)
|
||||
_write_Kind(w, v.kind)
|
||||
w.data(v.data)
|
||||
}
|
||||
|
||||
private fun _read_Scalars(r: NativeReader): Scalars {
|
||||
return Scalars(
|
||||
i = r.i64(),
|
||||
i8 = r.i64().toByte(),
|
||||
u16 = r.i64().toUShort(),
|
||||
i32 = r.i64().toInt(),
|
||||
u64 = r.i64().toULong(),
|
||||
f32 = r.double().toFloat(),
|
||||
f = r.double(),
|
||||
b = r.bool(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun _write_Scalars(w: NativeWriter, v: Scalars) {
|
||||
w.i64(v.i.toLong())
|
||||
w.i64(v.i8.toLong())
|
||||
w.i64(v.u16.toLong())
|
||||
w.i64(v.i32.toLong())
|
||||
w.i64(v.u64.toLong())
|
||||
w.double(v.f32.toDouble())
|
||||
w.double(v.f.toDouble())
|
||||
w.bool(v.b)
|
||||
}
|
||||
|
||||
private fun _read_Texts(r: NativeReader): Texts {
|
||||
return Texts(
|
||||
s = r.string(),
|
||||
b = r.data(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun _write_Texts(w: NativeWriter, v: Texts) {
|
||||
w.string(v.s)
|
||||
w.data(v.b)
|
||||
}
|
||||
|
||||
private fun _read_map_int(r: NativeReader): Map<String, Long> {
|
||||
val n = r.count()
|
||||
val v = LinkedHashMap<String, Long>(n)
|
||||
repeat(n) {
|
||||
val k = r.string()
|
||||
v[k] = r.i64()
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
private fun _write_map_int(w: NativeWriter, v: Map<String, Long>) {
|
||||
w.count(v.size)
|
||||
for ((k, x) in v) {
|
||||
w.string(k)
|
||||
w.i64(x.toLong())
|
||||
}
|
||||
}
|
||||
|
||||
private fun _read_map_string(r: NativeReader): Map<String, String> {
|
||||
val n = r.count()
|
||||
val v = LinkedHashMap<String, String>(n)
|
||||
repeat(n) {
|
||||
val k = r.string()
|
||||
v[k] = r.string()
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
private fun _write_map_string(w: NativeWriter, v: Map<String, String>) {
|
||||
w.count(v.size)
|
||||
for ((k, x) in v) {
|
||||
w.string(k)
|
||||
w.string(x)
|
||||
}
|
||||
}
|
||||
|
||||
private fun _read_ptr_Inner(r: NativeReader): Inner? {
|
||||
return if (r.bool()) _read_Inner(r) else null
|
||||
}
|
||||
|
||||
private fun _write_ptr_Inner(w: NativeWriter, v: Inner?) {
|
||||
if (v == null) {
|
||||
w.bool(false)
|
||||
} else {
|
||||
w.bool(true)
|
||||
_write_Inner(w, v)
|
||||
}
|
||||
}
|
||||
|
||||
private fun _read_ptr_int(r: NativeReader): Long? {
|
||||
return if (r.bool()) r.i64() else null
|
||||
}
|
||||
|
||||
private fun _write_ptr_int(w: NativeWriter, v: Long?) {
|
||||
if (v == null) {
|
||||
w.bool(false)
|
||||
} else {
|
||||
w.bool(true)
|
||||
w.i64(v.toLong())
|
||||
}
|
||||
}
|
||||
|
||||
private fun _read_slice_Empty(r: NativeReader): List<Empty> {
|
||||
val n = r.count()
|
||||
return List(n) { _read_Empty(r) }
|
||||
}
|
||||
|
||||
private fun _write_slice_Empty(w: NativeWriter, v: List<Empty>) {
|
||||
w.count(v.size)
|
||||
for (x in v) _write_Empty(w, x)
|
||||
}
|
||||
|
||||
private fun _read_slice_int(r: NativeReader): List<Long> {
|
||||
val n = r.count()
|
||||
return List(n) { r.i64() }
|
||||
}
|
||||
|
||||
private fun _write_slice_int(w: NativeWriter, v: List<Long>) {
|
||||
w.count(v.size)
|
||||
for (x in v) w.i64(x.toLong())
|
||||
}
|
||||
|
||||
private fun _read_slice_slice_int(r: NativeReader): List<List<Long>> {
|
||||
val n = r.count()
|
||||
return List(n) { _read_slice_int(r) }
|
||||
}
|
||||
|
||||
private fun _write_slice_slice_int(w: NativeWriter, v: List<List<Long>>) {
|
||||
w.count(v.size)
|
||||
for (x in v) _write_slice_int(w, x)
|
||||
}
|
||||
|
||||
private fun _read_slice_string(r: NativeReader): List<String> {
|
||||
val n = r.count()
|
||||
return List(n) { r.string() }
|
||||
}
|
||||
|
||||
private fun _write_slice_string(w: NativeWriter, v: List<String>) {
|
||||
w.count(v.size)
|
||||
for (x in v) w.string(x)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// Package roundtrip is a native module for the tests of the runtime and
|
||||
// the generator: every kind of value that crosses, sent to the platform
|
||||
// and back, with calls of each shape. It is implemented three times, in
|
||||
// swift/ (with Foundation only, so that it builds on Linux too), rust/ and
|
||||
// zig/, each of which the tests run.
|
||||
package roundtrip
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"iter"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/native"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Echo returns what it is given.
|
||||
//
|
||||
//mygo:native
|
||||
type Echo interface {
|
||||
// Scalars returns its arguments, one more each.
|
||||
Scalars(i int, i8 int8, u16 uint16, i32 int32, u64 uint64, f32 float32, f float64, b bool) Scalars
|
||||
// Add is a plain sum, the cheapest call.
|
||||
Add(a, b int) int
|
||||
// Text returns s twice, and b reversed.
|
||||
Text(s string, b []byte) Texts
|
||||
// Record returns r with its counts doubled.
|
||||
Record(r Record) (Record, error)
|
||||
// Lists returns the lengths of the words, and a map of each to its
|
||||
// length.
|
||||
Lists(words []string, nested [][]int) (map[string]int, error)
|
||||
// Maybe returns p's value plus one, or nil for nil.
|
||||
Maybe(p *int) *int
|
||||
// Times returns t moved by d, and d doubled.
|
||||
Times(t time.Time, d time.Duration) (Moment, error)
|
||||
// Kind returns the next kind, and the next level.
|
||||
Kind(k Kind, l Level) (Kinds, error)
|
||||
// Fail throws the error named, or nothing for "".
|
||||
Fail(name string) error
|
||||
// Wait waits d, or until ctx is done, then returns s.
|
||||
Wait(ctx context.Context, d time.Duration, s string) (string, error)
|
||||
// Count yields 0 to n-1, failing at fail when it is not -1.
|
||||
Count(ctx context.Context, n, fail int) iter.Seq2[int, error]
|
||||
// Records yields n records.
|
||||
Records(ctx context.Context, n int) iter.Seq2[Record, error]
|
||||
// Counter makes a counter starting at n.
|
||||
Counter(n int) (Counter, error)
|
||||
// Each calls f with each word and its index, and returns how many.
|
||||
Each(words []string, f func(word string, i int)) int
|
||||
// Ask asks f for the double of each number, and returns their sum.
|
||||
Ask(ns []int, f func(n int) (int, error)) (int, error)
|
||||
// Ticks calls f every interval until closed.
|
||||
Ticks(interval time.Duration, f func(n int)) io.Closer
|
||||
// Use asks s for a score of each word, and returns their sum.
|
||||
Use(ctx context.Context, s Scorer, words []string) (float64, error)
|
||||
// Fill writes b's index into each byte of buf, xor x.
|
||||
Fill(buf *native.Buffer, x int) (int, error)
|
||||
// Mix sums numbers of each kind, a call of numbers only.
|
||||
Mix(f float32, d float64, b bool, i int8) float64
|
||||
// Box returns r moved by its size.
|
||||
Box(r ui.Rect) (ui.Rect, error)
|
||||
// Nothing returns how many structs without fields it was given.
|
||||
Nothing(e []Empty) int
|
||||
// OnMain runs on the main thread, which go test does not run: the
|
||||
// tests only build it.
|
||||
//
|
||||
//mygo:mainthread
|
||||
OnMain(r Record, f func(in Inner)) (Texts, error)
|
||||
}
|
||||
|
||||
// Empty has no fields.
|
||||
type Empty struct{}
|
||||
|
||||
// Counter counts.
|
||||
type Counter interface {
|
||||
io.Closer
|
||||
// Next returns the count, then adds one.
|
||||
Next() int
|
||||
// Same returns another counter of the same count.
|
||||
Same() Counter
|
||||
}
|
||||
|
||||
// Scorer is implemented by Go.
|
||||
type Scorer interface {
|
||||
// Score scores a word.
|
||||
Score(word string) float64
|
||||
// Explain explains a score, which may wait.
|
||||
Explain(ctx context.Context, word string) (string, error)
|
||||
}
|
||||
|
||||
// Scalars are the scalars back.
|
||||
type Scalars struct {
|
||||
I int
|
||||
I8 int8
|
||||
U16 uint16
|
||||
I32 int32
|
||||
U64 uint64
|
||||
F32 float32
|
||||
F float64
|
||||
B bool
|
||||
}
|
||||
|
||||
// Texts are a string and bytes back.
|
||||
type Texts struct {
|
||||
S string
|
||||
B []byte
|
||||
}
|
||||
|
||||
// Record is a struct with every kind of field.
|
||||
type Record struct {
|
||||
Name string
|
||||
Counts []int
|
||||
Tags map[string]string
|
||||
Inner Inner
|
||||
Next *Inner
|
||||
Kind Kind
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// Inner is nested.
|
||||
type Inner struct {
|
||||
X, Y float64
|
||||
}
|
||||
|
||||
// Moment is a time and a duration back.
|
||||
type Moment struct {
|
||||
At time.Time
|
||||
Twice time.Duration
|
||||
}
|
||||
|
||||
// Kinds are an enum of each kind back.
|
||||
type Kinds struct {
|
||||
Kind Kind
|
||||
Level Level
|
||||
}
|
||||
|
||||
// Kind is a string enum.
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
KindA Kind = "a"
|
||||
KindB Kind = "b"
|
||||
KindC Kind = "c"
|
||||
)
|
||||
|
||||
// Level is an integer enum.
|
||||
type Level int
|
||||
|
||||
const (
|
||||
Low Level = 1
|
||||
High Level = 2
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNamed is the error Fail throws for "named".
|
||||
ErrNamed = native.NewError("named")
|
||||
)
|
||||
@@ -0,0 +1,724 @@
|
||||
// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.
|
||||
// mygo:native 3 aebdfd9f7bfb2215
|
||||
|
||||
package roundtrip
|
||||
|
||||
import (
|
||||
"context"
|
||||
_context "context"
|
||||
_fmt "fmt"
|
||||
"io"
|
||||
"iter"
|
||||
_filepath "path/filepath"
|
||||
_runtime "runtime"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/native"
|
||||
_native "github.com/egoist/mygo/native"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// _module describes the module to the runtime.
|
||||
var _module = &_native.Module{Name: "Roundtrip", Symbol: "roundtrip", Langs: []string{"swift", "kotlin", "rust", "zig"}, SwiftOS: []string{"macos", "ios"}, MinMacOS: "13", MinIOS: "16", Kotlin: "com.github.egoist.mygo.native_.internal.roundtrip.MygoModule", Dir: _dir(), Errors: []*_native.Error{ErrNamed}, Deps: []string{}}
|
||||
|
||||
// _dir returns the package's directory when the binary knows it, where
|
||||
// mygo dev builds the implementation for go test and go run.
|
||||
func _dir() string {
|
||||
_, file, _, ok := _runtime.Caller(0)
|
||||
if !ok || !_filepath.IsAbs(file) {
|
||||
return ""
|
||||
}
|
||||
return _filepath.Dir(file)
|
||||
}
|
||||
|
||||
func init() {
|
||||
_native.Register(_module, map[string]_native.Wrapper{
|
||||
"Echo": {Flags: 0, Wrap: func(o *_native.Object) any { return &_Echo{o} }},
|
||||
"Counter": {Flags: 0, Wrap: func(o *_native.Object) any { return &_Counter{o} }},
|
||||
})
|
||||
}
|
||||
|
||||
// NewEcho makes the implementation of Echo on this platform. It returns
|
||||
// errors.ErrUnsupported where the module has none, or the system lacks
|
||||
// what it needs.
|
||||
func NewEcho() (Echo, error) {
|
||||
o, err := _module.New("Echo", 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &_Echo{o}, nil
|
||||
}
|
||||
|
||||
// _Echo calls the platform's implementation of Echo.
|
||||
type _Echo struct{ o *_native.Object }
|
||||
|
||||
// NativeObject returns the platform's object.
|
||||
func (x *_Echo) NativeObject() *_native.Object { return x.o }
|
||||
|
||||
// _wrapEcho wraps a handle of the platform's, or returns nil.
|
||||
func _wrapEcho(h uint64) Echo {
|
||||
if h == 0 {
|
||||
return nil
|
||||
}
|
||||
return &_Echo{_module.Object(h, 0)}
|
||||
}
|
||||
|
||||
func (_x *_Echo) Scalars(i int, i8 int8, u16 uint16, i32 int32, u64 uint64, f32 float32, f float64, b bool) Scalars {
|
||||
_e := _native.NewEncoder()
|
||||
_e.Int(int64(i))
|
||||
_e.Int(int64(i8))
|
||||
_e.Int(int64(u16))
|
||||
_e.Int(int64(i32))
|
||||
_e.Int(int64(u64))
|
||||
_e.Float(float64(f32))
|
||||
_e.Float(float64(f))
|
||||
_e.Bool(b)
|
||||
var _r Scalars
|
||||
_d, _err := _x.NativeObject().Call("Echo_Scalars", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_Scalars(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
_ = _err
|
||||
return _r
|
||||
}
|
||||
|
||||
func (_x *_Echo) Add(a int, b int) int {
|
||||
return int(_x.NativeObject().Direct("Echo_Add_direct", uintptr(a), uintptr(b)))
|
||||
}
|
||||
|
||||
func (_x *_Echo) Text(s string, b []byte) Texts {
|
||||
_e := _native.NewEncoder()
|
||||
_e.String(s)
|
||||
_e.Bytes(b)
|
||||
var _r Texts
|
||||
_d, _err := _x.NativeObject().Call("Echo_Text", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_Texts(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
_ = _err
|
||||
return _r
|
||||
}
|
||||
|
||||
func (_x *_Echo) Record(r Record) (Record, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_enc_Record(_e, r)
|
||||
var _r Record
|
||||
_d, _err := _x.NativeObject().Call("Echo_Record", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_Record(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Lists(words []string, nested [][]int) (map[string]int, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_enc_slice_string(_e, words)
|
||||
_enc_slice_slice_int(_e, nested)
|
||||
var _r map[string]int
|
||||
_d, _err := _x.NativeObject().Call("Echo_Lists", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_map_int(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Maybe(p *int) *int {
|
||||
_e := _native.NewEncoder()
|
||||
_enc_ptr_int(_e, p)
|
||||
var _r *int
|
||||
_d, _err := _x.NativeObject().Call("Echo_Maybe", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_ptr_int(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
_ = _err
|
||||
return _r
|
||||
}
|
||||
|
||||
func (_x *_Echo) Times(t time.Time, d time.Duration) (Moment, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_e.Time(t)
|
||||
_e.Duration(d)
|
||||
var _r Moment
|
||||
_d, _err := _x.NativeObject().Call("Echo_Times", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_Moment(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Kind(k Kind, l Level) (Kinds, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_enc_Kind(_e, k)
|
||||
_enc_Level(_e, l)
|
||||
var _r Kinds
|
||||
_d, _err := _x.NativeObject().Call("Echo_Kind", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_Kinds(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Fail(name string) error {
|
||||
_e := _native.NewEncoder()
|
||||
_e.String(name)
|
||||
_d, _err := _x.NativeObject().Call("Echo_Fail", 0, _e)
|
||||
if _err == nil {
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Wait(_ctx context.Context, d time.Duration, s string) (string, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_e.Duration(d)
|
||||
_e.String(s)
|
||||
var _r string
|
||||
_d, _err := _x.NativeObject().CallContext(_ctx, "Echo_Wait", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _d.String()
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Count(_ctx context.Context, n int, fail int) iter.Seq2[int, error] {
|
||||
return _native.Stream(_ctx, _x.NativeObject(), "Echo_Count", 0, func() (*_native.Encoder, []uint64) {
|
||||
_e := _native.NewEncoder()
|
||||
_e.Int(int64(n))
|
||||
_e.Int(int64(fail))
|
||||
return _e, nil
|
||||
}, func(_d *_native.Decoder) int { return int(_d.Int()) })
|
||||
}
|
||||
|
||||
func (_x *_Echo) Records(_ctx context.Context, n int) iter.Seq2[Record, error] {
|
||||
return _native.Stream(_ctx, _x.NativeObject(), "Echo_Records", 0, func() (*_native.Encoder, []uint64) {
|
||||
_e := _native.NewEncoder()
|
||||
_e.Int(int64(n))
|
||||
return _e, nil
|
||||
}, func(_d *_native.Decoder) Record { return _dec_Record(_d) })
|
||||
}
|
||||
|
||||
func (_x *_Echo) Counter(n int) (Counter, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_e.Int(int64(n))
|
||||
var _h uint64
|
||||
_d, _err := _x.NativeObject().Call("Echo_Counter", 0, _e)
|
||||
if _err == nil {
|
||||
_h = _d.Uint()
|
||||
_err = _d.Close()
|
||||
}
|
||||
if _err != nil {
|
||||
return nil, _err
|
||||
}
|
||||
return _wrapCounter(_h), nil
|
||||
}
|
||||
|
||||
func (_x *_Echo) Each(words []string, f func(word string, i int)) int {
|
||||
var _f1 uint64
|
||||
if f != nil {
|
||||
_f1 = _native.Func(func(_d *_native.Decoder, _e *_native.Encoder) error {
|
||||
_p0 := _d.String()
|
||||
_p1 := int(_d.Int())
|
||||
if _err := _d.Err(); _err != nil {
|
||||
return _err
|
||||
}
|
||||
f(_p0, _p1)
|
||||
return nil
|
||||
}, true)
|
||||
}
|
||||
_e := _native.NewEncoder()
|
||||
_enc_slice_string(_e, words)
|
||||
_e.Uint(_f1)
|
||||
var _r int
|
||||
_d, _err := _x.NativeObject().Call("Echo_Each", 0, _e)
|
||||
if _err == nil {
|
||||
_r = int(_d.Int())
|
||||
_err = _d.Close()
|
||||
}
|
||||
if _err != nil {
|
||||
_native.Forget(_f1)
|
||||
}
|
||||
_ = _err
|
||||
return _r
|
||||
}
|
||||
|
||||
func (_x *_Echo) Ask(ns []int, f func(n int) (int, error)) (int, error) {
|
||||
var _f1 uint64
|
||||
if f != nil {
|
||||
_f1 = _native.Func(func(_d *_native.Decoder, _e *_native.Encoder) error {
|
||||
_p0 := int(_d.Int())
|
||||
if _err := _d.Err(); _err != nil {
|
||||
return _err
|
||||
}
|
||||
_r, _err := f(_p0)
|
||||
if _err != nil {
|
||||
return _err
|
||||
}
|
||||
_e.Int(int64(_r))
|
||||
return nil
|
||||
}, false)
|
||||
}
|
||||
_e := _native.NewEncoder()
|
||||
_enc_slice_int(_e, ns)
|
||||
_e.Uint(_f1)
|
||||
var _r int
|
||||
_d, _err := _x.NativeObject().Call("Echo_Ask", 0, _e)
|
||||
if _err == nil {
|
||||
_r = int(_d.Int())
|
||||
_err = _d.Close()
|
||||
}
|
||||
if _err != nil {
|
||||
_native.Forget(_f1)
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Ticks(interval time.Duration, f func(n int)) io.Closer {
|
||||
var _f1 uint64
|
||||
if f != nil {
|
||||
_f1 = _native.Func(func(_d *_native.Decoder, _e *_native.Encoder) error {
|
||||
_p0 := int(_d.Int())
|
||||
if _err := _d.Err(); _err != nil {
|
||||
return _err
|
||||
}
|
||||
f(_p0)
|
||||
return nil
|
||||
}, true)
|
||||
}
|
||||
_e := _native.NewEncoder()
|
||||
_e.Duration(interval)
|
||||
_e.Uint(_f1)
|
||||
return _x.NativeObject().Subscribe("Echo_Ticks", 0, _e, _f1)
|
||||
}
|
||||
|
||||
func (_x *_Echo) Use(_ctx context.Context, s Scorer, words []string) (float64, error) {
|
||||
var _g0 uint64
|
||||
if s != nil {
|
||||
_g0 = _native.Export(_module, s, func(_c _context.Context, _m int, _d *_native.Decoder, _e *_native.Encoder) error {
|
||||
return _dispatchScorer(s, _c, _m, _d, _e)
|
||||
})
|
||||
}
|
||||
_e := _native.NewEncoder()
|
||||
_e.Uint(_g0)
|
||||
_enc_slice_string(_e, words)
|
||||
var _r float64
|
||||
_d, _err := _x.NativeObject().CallContext(_ctx, "Echo_Use", 0, _e)
|
||||
if _err == nil {
|
||||
_r = float64(_d.Float())
|
||||
_err = _d.Close()
|
||||
}
|
||||
if _err != nil {
|
||||
_native.Forget(_g0)
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Fill(buf *native.Buffer, x int) (int, error) {
|
||||
defer _runtime.KeepAlive(buf)
|
||||
_e := _native.NewEncoder()
|
||||
_e.Buffer(buf)
|
||||
_e.Int(int64(x))
|
||||
var _r int
|
||||
_d, _err := _x.NativeObject().Call("Echo_Fill", 0, _e)
|
||||
if _err == nil {
|
||||
_r = int(_d.Int())
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Mix(f float32, d float64, b bool, i int8) float64 {
|
||||
return float64(_native.FloatResult(_x.NativeObject().Direct("Echo_Mix_direct", _native.FloatArg(float64(f)), _native.FloatArg(float64(d)), _native.BoolArg(b), uintptr(i))))
|
||||
}
|
||||
|
||||
func (_x *_Echo) Box(r ui.Rect) (ui.Rect, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_e.Rect(r.X, r.Y, r.W, r.H)
|
||||
var _r ui.Rect
|
||||
_d, _err := _x.NativeObject().Call("Echo_Box", 0, _e)
|
||||
if _err == nil {
|
||||
_r = ui.Rect{X: float32(_d.Float()), Y: float32(_d.Float()), W: float32(_d.Float()), H: float32(_d.Float())}
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Echo) Nothing(e []Empty) int {
|
||||
_e := _native.NewEncoder()
|
||||
_enc_slice_Empty(_e, e)
|
||||
var _r int
|
||||
_d, _err := _x.NativeObject().Call("Echo_Nothing", 0, _e)
|
||||
if _err == nil {
|
||||
_r = int(_d.Int())
|
||||
_err = _d.Close()
|
||||
}
|
||||
_ = _err
|
||||
return _r
|
||||
}
|
||||
|
||||
func (_x *_Echo) OnMain(r Record, f func(in Inner)) (Texts, error) {
|
||||
var _f1 uint64
|
||||
if f != nil {
|
||||
_f1 = _native.Func(func(_d *_native.Decoder, _e *_native.Encoder) error {
|
||||
_p0 := _dec_Inner(_d)
|
||||
if _err := _d.Err(); _err != nil {
|
||||
return _err
|
||||
}
|
||||
f(_p0)
|
||||
return nil
|
||||
}, true)
|
||||
}
|
||||
_e := _native.NewEncoder()
|
||||
_enc_Record(_e, r)
|
||||
_e.Uint(_f1)
|
||||
var _r Texts
|
||||
_d, _err := _x.NativeObject().Call("Echo_OnMain", _native.MainThread, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_Texts(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
if _err != nil {
|
||||
_native.Forget(_f1)
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
// _Counter calls the platform's implementation of Counter.
|
||||
type _Counter struct{ o *_native.Object }
|
||||
|
||||
// NativeObject returns the platform's object.
|
||||
func (x *_Counter) NativeObject() *_native.Object { return x.o }
|
||||
|
||||
// _wrapCounter wraps a handle of the platform's, or returns nil.
|
||||
func _wrapCounter(h uint64) Counter {
|
||||
if h == 0 {
|
||||
return nil
|
||||
}
|
||||
return &_Counter{_module.Object(h, 0)}
|
||||
}
|
||||
|
||||
func (_x *_Counter) Close() error {
|
||||
return _x.NativeObject().Close()
|
||||
}
|
||||
|
||||
func (_x *_Counter) Next() int {
|
||||
return int(_x.NativeObject().Direct("Counter_Next_direct"))
|
||||
}
|
||||
|
||||
func (_x *_Counter) Same() Counter {
|
||||
var _h uint64
|
||||
_d, _err := _x.NativeObject().Call("Counter_Same", 0, nil)
|
||||
if _err == nil {
|
||||
_h = _d.Uint()
|
||||
_err = _d.Close()
|
||||
}
|
||||
if _err != nil {
|
||||
return nil
|
||||
}
|
||||
return _wrapCounter(_h)
|
||||
}
|
||||
|
||||
// _dispatchScorer calls the method number _m of _v for the platform, with
|
||||
// the arguments in _d, and writes its result to _e.
|
||||
func _dispatchScorer(_v Scorer, _ctx _context.Context, _m int, _d *_native.Decoder, _e *_native.Encoder) error {
|
||||
switch _m {
|
||||
case 0:
|
||||
_p0 := _d.String()
|
||||
if _err := _d.Err(); _err != nil {
|
||||
return _err
|
||||
}
|
||||
_r := _v.Score(_p0)
|
||||
_e.Float(float64(_r))
|
||||
return nil
|
||||
case 1:
|
||||
_p0 := _d.String()
|
||||
if _err := _d.Err(); _err != nil {
|
||||
return _err
|
||||
}
|
||||
_r, _err := _v.Explain(_ctx, _p0)
|
||||
if _err != nil {
|
||||
return _err
|
||||
}
|
||||
_e.String(_r)
|
||||
return nil
|
||||
}
|
||||
return _fmt.Errorf("native: Scorer has no method %d", _m)
|
||||
}
|
||||
|
||||
func _enc_Empty(_e *_native.Encoder, _v Empty) {
|
||||
_e.Bool(false)
|
||||
}
|
||||
|
||||
func _dec_Empty(_d *_native.Decoder) Empty {
|
||||
_d.Bool()
|
||||
return Empty{}
|
||||
}
|
||||
|
||||
func _enc_Inner(_e *_native.Encoder, _v Inner) {
|
||||
_e.Float(float64(_v.X))
|
||||
_e.Float(float64(_v.Y))
|
||||
}
|
||||
|
||||
func _dec_Inner(_d *_native.Decoder) Inner {
|
||||
return Inner{
|
||||
X: float64(_d.Float()),
|
||||
Y: float64(_d.Float()),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_Kind(_e *_native.Encoder, _v Kind) {
|
||||
_e.String(string(_v))
|
||||
}
|
||||
|
||||
func _dec_Kind(_d *_native.Decoder) Kind {
|
||||
return Kind(_d.String())
|
||||
}
|
||||
|
||||
func _enc_Kinds(_e *_native.Encoder, _v Kinds) {
|
||||
_enc_Kind(_e, _v.Kind)
|
||||
_enc_Level(_e, _v.Level)
|
||||
}
|
||||
|
||||
func _dec_Kinds(_d *_native.Decoder) Kinds {
|
||||
return Kinds{
|
||||
Kind: _dec_Kind(_d),
|
||||
Level: _dec_Level(_d),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_Level(_e *_native.Encoder, _v Level) {
|
||||
_e.Int(int64(_v))
|
||||
}
|
||||
|
||||
func _dec_Level(_d *_native.Decoder) Level {
|
||||
return Level(_d.Int())
|
||||
}
|
||||
|
||||
func _enc_Moment(_e *_native.Encoder, _v Moment) {
|
||||
_e.Time(_v.At)
|
||||
_e.Duration(_v.Twice)
|
||||
}
|
||||
|
||||
func _dec_Moment(_d *_native.Decoder) Moment {
|
||||
return Moment{
|
||||
At: _d.Time(),
|
||||
Twice: _d.Duration(),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_Record(_e *_native.Encoder, _v Record) {
|
||||
_e.String(_v.Name)
|
||||
_enc_slice_int(_e, _v.Counts)
|
||||
_enc_map_string(_e, _v.Tags)
|
||||
_enc_Inner(_e, _v.Inner)
|
||||
_enc_ptr_Inner(_e, _v.Next)
|
||||
_enc_Kind(_e, _v.Kind)
|
||||
_e.Bytes(_v.Data)
|
||||
}
|
||||
|
||||
func _dec_Record(_d *_native.Decoder) Record {
|
||||
return Record{
|
||||
Name: _d.String(),
|
||||
Counts: _dec_slice_int(_d),
|
||||
Tags: _dec_map_string(_d),
|
||||
Inner: _dec_Inner(_d),
|
||||
Next: _dec_ptr_Inner(_d),
|
||||
Kind: _dec_Kind(_d),
|
||||
Data: _d.Bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_Scalars(_e *_native.Encoder, _v Scalars) {
|
||||
_e.Int(int64(_v.I))
|
||||
_e.Int(int64(_v.I8))
|
||||
_e.Int(int64(_v.U16))
|
||||
_e.Int(int64(_v.I32))
|
||||
_e.Int(int64(_v.U64))
|
||||
_e.Float(float64(_v.F32))
|
||||
_e.Float(float64(_v.F))
|
||||
_e.Bool(_v.B)
|
||||
}
|
||||
|
||||
func _dec_Scalars(_d *_native.Decoder) Scalars {
|
||||
return Scalars{
|
||||
I: int(_d.Int()),
|
||||
I8: int8(_d.Int()),
|
||||
U16: uint16(_d.Int()),
|
||||
I32: int32(_d.Int()),
|
||||
U64: uint64(_d.Int()),
|
||||
F32: float32(_d.Float()),
|
||||
F: float64(_d.Float()),
|
||||
B: _d.Bool(),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_Texts(_e *_native.Encoder, _v Texts) {
|
||||
_e.String(_v.S)
|
||||
_e.Bytes(_v.B)
|
||||
}
|
||||
|
||||
func _dec_Texts(_d *_native.Decoder) Texts {
|
||||
return Texts{
|
||||
S: _d.String(),
|
||||
B: _d.Bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_map_int(_e *_native.Encoder, _v map[string]int) {
|
||||
_e.Len(len(_v))
|
||||
for _k, _x := range _v {
|
||||
_e.String(_k)
|
||||
_e.Int(int64(_x))
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_map_int(_d *_native.Decoder) map[string]int {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make(map[string]int, _n)
|
||||
for range _n {
|
||||
_k := _d.String()
|
||||
_v[_k] = int(_d.Int())
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_map_string(_e *_native.Encoder, _v map[string]string) {
|
||||
_e.Len(len(_v))
|
||||
for _k, _x := range _v {
|
||||
_e.String(_k)
|
||||
_e.String(_x)
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_map_string(_d *_native.Decoder) map[string]string {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make(map[string]string, _n)
|
||||
for range _n {
|
||||
_k := _d.String()
|
||||
_v[_k] = _d.String()
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_ptr_Inner(_e *_native.Encoder, _v *Inner) {
|
||||
if _v == nil {
|
||||
_e.Bool(false)
|
||||
return
|
||||
}
|
||||
_e.Bool(true)
|
||||
_enc_Inner(_e, *_v)
|
||||
}
|
||||
|
||||
func _dec_ptr_Inner(_d *_native.Decoder) *Inner {
|
||||
if !_d.Bool() {
|
||||
return nil
|
||||
}
|
||||
_x := _dec_Inner(_d)
|
||||
return &_x
|
||||
}
|
||||
|
||||
func _enc_ptr_int(_e *_native.Encoder, _v *int) {
|
||||
if _v == nil {
|
||||
_e.Bool(false)
|
||||
return
|
||||
}
|
||||
_e.Bool(true)
|
||||
_e.Int(int64(*_v))
|
||||
}
|
||||
|
||||
func _dec_ptr_int(_d *_native.Decoder) *int {
|
||||
if !_d.Bool() {
|
||||
return nil
|
||||
}
|
||||
_x := int(_d.Int())
|
||||
return &_x
|
||||
}
|
||||
|
||||
func _enc_slice_Empty(_e *_native.Encoder, _v []Empty) {
|
||||
_e.Len(len(_v))
|
||||
for _, _x := range _v {
|
||||
_enc_Empty(_e, _x)
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_slice_Empty(_d *_native.Decoder) []Empty {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make([]Empty, _n)
|
||||
for _i := range _v {
|
||||
_v[_i] = _dec_Empty(_d)
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_slice_int(_e *_native.Encoder, _v []int) {
|
||||
_e.Len(len(_v))
|
||||
for _, _x := range _v {
|
||||
_e.Int(int64(_x))
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_slice_int(_d *_native.Decoder) []int {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make([]int, _n)
|
||||
for _i := range _v {
|
||||
_v[_i] = int(_d.Int())
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_slice_slice_int(_e *_native.Encoder, _v [][]int) {
|
||||
_e.Len(len(_v))
|
||||
for _, _x := range _v {
|
||||
_enc_slice_int(_e, _x)
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_slice_slice_int(_d *_native.Decoder) [][]int {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make([][]int, _n)
|
||||
for _i := range _v {
|
||||
_v[_i] = _dec_slice_int(_d)
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_slice_string(_e *_native.Encoder, _v []string) {
|
||||
_e.Len(len(_v))
|
||||
for _, _x := range _v {
|
||||
_e.String(_x)
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_slice_string(_d *_native.Decoder) []string {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make([]string, _n)
|
||||
for _i := range _v {
|
||||
_v[_i] = _d.String()
|
||||
}
|
||||
return _v
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package roundtrip_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/native/internal/roundtrip"
|
||||
"github.com/egoist/mygo/native/internal/roundtrip/check"
|
||||
)
|
||||
|
||||
func echo(t testing.TB) roundtrip.Echo { return check.Echo(t) }
|
||||
|
||||
func TestScalars(t *testing.T) { check.Scalars(t) }
|
||||
|
||||
func TestText(t *testing.T) { check.Text(t) }
|
||||
|
||||
func TestRecord(t *testing.T) { check.Record(t) }
|
||||
|
||||
func TestLists(t *testing.T) { check.Lists(t) }
|
||||
|
||||
func TestMaybe(t *testing.T) { check.Maybe(t) }
|
||||
|
||||
func TestTimes(t *testing.T) { check.Times(t) }
|
||||
|
||||
func TestKinds(t *testing.T) { check.Kinds(t) }
|
||||
|
||||
func TestErrors(t *testing.T) { check.Errors(t) }
|
||||
|
||||
func TestAsync(t *testing.T) { check.Async(t) }
|
||||
|
||||
func TestStreams(t *testing.T) { check.Streams(t) }
|
||||
|
||||
func TestObjects(t *testing.T) { check.Objects(t) }
|
||||
|
||||
func TestCallbacks(t *testing.T) { check.Callbacks(t) }
|
||||
|
||||
func TestTicks(t *testing.T) { check.Ticks(t) }
|
||||
|
||||
func TestGoImplements(t *testing.T) { check.GoImplements(t) }
|
||||
|
||||
func TestBuffer(t *testing.T) { check.Buffer(t) }
|
||||
|
||||
func TestMore(t *testing.T) { check.More(t) }
|
||||
|
||||
// The cost of a call of each shape, which the encoding of values decides.
|
||||
func BenchmarkAdd(b *testing.B) {
|
||||
e := echo(b)
|
||||
for b.Loop() {
|
||||
e.Add(1, 2)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkText(b *testing.B) {
|
||||
e := echo(b)
|
||||
s := strings.Repeat("x", 100)
|
||||
for b.Loop() {
|
||||
e.Text(s, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRecord(b *testing.B) {
|
||||
e := echo(b)
|
||||
r := roundtrip.Record{Name: "r", Counts: []int{1, 2, 3, 4}, Tags: map[string]string{"a": "b"}, Next: &roundtrip.Inner{}, Kind: roundtrip.KindA, Data: make([]byte, 64)}
|
||||
for b.Loop() {
|
||||
if _, err := e.Record(r); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStream(b *testing.B) {
|
||||
e := echo(b)
|
||||
for b.Loop() {
|
||||
for _, err := range e.Count(context.Background(), 100, -1) {
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/target
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "roundtrip"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "roundtrip"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,208 @@
|
||||
//! The implementation of package roundtrip in Rust: every value it is
|
||||
//! given, back, as its Swift and Zig implementations do.
|
||||
|
||||
mod mygo;
|
||||
|
||||
use mygo::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
pub fn make_echo() -> Result<Arc<dyn Echo>, Error> {
|
||||
Ok(Arc::new(Echoer))
|
||||
}
|
||||
|
||||
struct Echoer;
|
||||
|
||||
impl Echo for Echoer {
|
||||
fn scalars(&self, i: i64, i8: i8, u16: u16, i32: i32, u64: u64, f32: f32, f: f64, b: bool) -> Scalars {
|
||||
Scalars {
|
||||
i: i + 1,
|
||||
i8: i8.wrapping_add(1),
|
||||
u16: u16.wrapping_add(1),
|
||||
i32: i32 + 1,
|
||||
u64: u64.wrapping_add(1),
|
||||
f32: f32 + 1.0,
|
||||
f: f + 1.0,
|
||||
b: !b,
|
||||
}
|
||||
}
|
||||
|
||||
fn add(&self, a: i64, b: i64) -> i64 {
|
||||
a + b
|
||||
}
|
||||
|
||||
fn text(&self, s: String, b: Vec<u8>) -> Texts {
|
||||
Texts {
|
||||
s: s.repeat(2),
|
||||
b: b.into_iter().rev().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record(&self, mut r: Record) -> Result<Record, Error> {
|
||||
for c in r.counts.iter_mut() {
|
||||
*c *= 2;
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn lists(&self, words: Vec<String>, nested: Vec<Vec<i64>>) -> Result<HashMap<String, i64>, Error> {
|
||||
let mut m: HashMap<String, i64> = words.iter().map(|w| (w.clone(), w.len() as i64)).collect();
|
||||
m.insert("nested".into(), nested.iter().flatten().sum());
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
fn maybe(&self, p: Option<i64>) -> Option<i64> {
|
||||
p.map(|v| v + 1)
|
||||
}
|
||||
|
||||
fn times(&self, t: SystemTime, d: Duration) -> Result<Moment, Error> {
|
||||
Ok(Moment { at: t + d, twice: d * 2 })
|
||||
}
|
||||
|
||||
fn kind(&self, k: Kind, l: Level) -> Result<Kinds, Error> {
|
||||
let next = match k {
|
||||
Kind::KindA => Kind::KindB,
|
||||
Kind::KindB => Kind::KindC,
|
||||
Kind::KindC => Kind::KindA,
|
||||
};
|
||||
let level = if l == Level::Low { Level::High } else { Level::Low };
|
||||
Ok(Kinds { kind: next, level })
|
||||
}
|
||||
|
||||
fn fail(&self, name: String) -> Result<(), Error> {
|
||||
match name.as_str() {
|
||||
"" => Ok(()),
|
||||
"named" => Err(RoundtripError::Named.into()),
|
||||
"unsupported" => Err(Error::Unsupported),
|
||||
_ => Err(Error::Other {
|
||||
domain: "RoundtripDomain".into(),
|
||||
number: 7,
|
||||
message: name,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn wait(&self, ctx: &Context, d: Duration, s: String) -> Result<String, Error> {
|
||||
ctx.sleep(d)?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn count(&self, _ctx: &Context, n: i64, fail: i64) -> Stream<Result<i64, Error>> {
|
||||
let mut i = 0;
|
||||
stream_of(std::iter::from_fn(move || {
|
||||
if i >= n || i > fail && fail >= 0 {
|
||||
return None;
|
||||
}
|
||||
i += 1;
|
||||
if i - 1 == fail {
|
||||
return Some(Err(RoundtripError::Named.into()));
|
||||
}
|
||||
Some(Ok(i - 1))
|
||||
}))
|
||||
}
|
||||
|
||||
fn records(&self, _ctx: &Context, n: i64) -> Stream<Result<Record, Error>> {
|
||||
stream_of((0..n).map(|i| {
|
||||
Ok(Record {
|
||||
name: format!("r{}", i),
|
||||
counts: vec![i],
|
||||
tags: HashMap::from([("i".to_string(), i.to_string())]),
|
||||
inner: Inner { x: i as f64, y: 0.0 },
|
||||
next: None,
|
||||
kind: Kind::KindA,
|
||||
data: vec![(i & 0xff) as u8],
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
fn counter(&self, n: i64) -> Result<Arc<dyn Counter>, Error> {
|
||||
Ok(Arc::new(Counting(AtomicI64::new(n))))
|
||||
}
|
||||
|
||||
fn each(&self, words: Vec<String>, f: Arc<dyn Fn(String, i64) + Send + Sync>) -> i64 {
|
||||
for (i, w) in words.iter().enumerate() {
|
||||
f(w.clone(), i as i64);
|
||||
}
|
||||
words.len() as i64
|
||||
}
|
||||
|
||||
fn ask(&self, ns: Vec<i64>, f: Arc<dyn Fn(i64) -> Result<i64, Error> + Send + Sync>) -> Result<i64, Error> {
|
||||
let mut sum = 0;
|
||||
for n in ns {
|
||||
sum += f(n)?;
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
|
||||
fn ticks(&self, interval: Duration, f: Arc<dyn Fn(i64) + Send + Sync>) -> Box<dyn Closer> {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let s = Arc::clone(&stop);
|
||||
std::thread::spawn(move || {
|
||||
let mut n = 0;
|
||||
while !s.load(Ordering::SeqCst) {
|
||||
std::thread::sleep(interval);
|
||||
if s.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
n += 1;
|
||||
f(n);
|
||||
}
|
||||
});
|
||||
closer(move || stop.store(true, Ordering::SeqCst))
|
||||
}
|
||||
|
||||
fn r#use(&self, ctx: &Context, s: Arc<dyn Scorer>, words: Vec<String>) -> Result<f64, Error> {
|
||||
let mut sum: f64 = words.iter().map(|w| s.score(w.clone())).sum();
|
||||
if let Some(first) = words.first() {
|
||||
let why = s.explain(ctx, first.clone())?;
|
||||
sum += why.len() as f64;
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
|
||||
fn fill(&self, mut buf: Buffer, x: i64) -> Result<i64, Error> {
|
||||
for (i, b) in buf.bytes_mut().iter_mut().enumerate() {
|
||||
*b = (i as i64 ^ x) as u8;
|
||||
}
|
||||
Ok(buf.len() as i64)
|
||||
}
|
||||
|
||||
fn mix(&self, f: f32, d: f64, b: bool, i: i8) -> f64 {
|
||||
f as f64 + d + if b { 1.0 } else { 0.0 } + i as f64
|
||||
}
|
||||
|
||||
fn r#box(&self, r: Rect) -> Result<Rect, Error> {
|
||||
Ok(Rect {
|
||||
x: r.x + r.w,
|
||||
y: r.y + r.h,
|
||||
..r
|
||||
})
|
||||
}
|
||||
|
||||
fn nothing(&self, e: Vec<Empty>) -> i64 {
|
||||
e.len() as i64
|
||||
}
|
||||
|
||||
fn on_main(&self, r: Record, f: Arc<dyn Fn(Inner) + Send + Sync>) -> Result<Texts, Error> {
|
||||
f(r.inner.clone());
|
||||
Ok(Texts { s: r.name, b: r.data })
|
||||
}
|
||||
}
|
||||
|
||||
struct Counting(AtomicI64);
|
||||
|
||||
impl Counter for Counting {
|
||||
fn close(&self) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next(&self) -> i64 {
|
||||
self.0.fetch_add(1, Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn same(&self) -> Arc<dyn Counter> {
|
||||
Arc::new(Counting(AtomicI64::new(self.0.load(Ordering::SeqCst))))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
/.build
|
||||
/.swiftpm
|
||||
@@ -0,0 +1,13 @@
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Roundtrip",
|
||||
platforms: [.macOS(.v13), .iOS(.v16)],
|
||||
products: [.library(name: "Roundtrip", type: .dynamic, targets: ["Roundtrip"])],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(name: "Roundtrip"),
|
||||
],
|
||||
swiftLanguageModes: [.v5]
|
||||
)
|
||||
+1515
File diff suppressed because it is too large.
Load diff
+145
@@ -0,0 +1,145 @@
|
||||
import Foundation
|
||||
|
||||
// The implementation of package roundtrip: every value it is given, back,
|
||||
// with Foundation only, so that it builds on Linux too.
|
||||
|
||||
func makeEcho() throws -> any Echo { Echoer() }
|
||||
|
||||
final class Echoer: Echo {
|
||||
func scalars(i: Int, i8: Int8, u16: UInt16, i32: Int32, u64: UInt64, f32: Float, f: Double, b: Bool) -> Scalars {
|
||||
Scalars(i: i + 1, i8: i8 &+ 1, u16: u16 &+ 1, i32: i32 + 1, u64: u64 &+ 1, f32: f32 + 1, f: f + 1, b: !b)
|
||||
}
|
||||
|
||||
func add(a: Int, b: Int) -> Int { a + b }
|
||||
|
||||
func text(s: String, b: Data) -> Texts { Texts(s: s + s, b: Data(b.reversed())) }
|
||||
|
||||
func record(r: Record) throws -> Record {
|
||||
var r = r
|
||||
r.counts = r.counts.map { $0 * 2 }
|
||||
return r
|
||||
}
|
||||
|
||||
func lists(words: [String], nested: [[Int]]) throws -> [String: Int] {
|
||||
var m: [String: Int] = [:]
|
||||
for w in words { m[w] = w.utf8.count }
|
||||
m["nested"] = nested.map { $0.reduce(0, +) }.reduce(0, +)
|
||||
return m
|
||||
}
|
||||
|
||||
func maybe(p: Int?) -> Int? { p.map { $0 + 1 } }
|
||||
|
||||
func times(t: Date, d: Duration) throws -> Moment {
|
||||
let c = d.components
|
||||
let seconds = Double(c.seconds) + Double(c.attoseconds) / 1e18
|
||||
return Moment(at: t.addingTimeInterval(seconds), twice: d * 2)
|
||||
}
|
||||
|
||||
func kind(k: Kind, l: Level) throws -> Kinds {
|
||||
let all = Kind.allCases
|
||||
let next = all[(all.firstIndex(of: k)! + 1) % all.count]
|
||||
return Kinds(kind: next, level: l == .low ? .high : .low)
|
||||
}
|
||||
|
||||
func fail(name: String) throws {
|
||||
switch name {
|
||||
case "": return
|
||||
case "named": throw RoundtripError.named
|
||||
case "unsupported": throw NativeError.unsupported
|
||||
default: throw NSError(domain: "RoundtripDomain", code: 7, userInfo: [NSLocalizedDescriptionKey: name])
|
||||
}
|
||||
}
|
||||
|
||||
func wait(d: Duration, s: String) async throws -> String {
|
||||
try await Task.sleep(for: d)
|
||||
return s
|
||||
}
|
||||
|
||||
func count(n: Int, fail: Int) -> AsyncThrowingStream<Int, Error> {
|
||||
AsyncThrowingStream { continuation in
|
||||
for i in 0..<n {
|
||||
if i == fail {
|
||||
continuation.finish(throwing: RoundtripError.named)
|
||||
return
|
||||
}
|
||||
continuation.yield(i)
|
||||
}
|
||||
continuation.finish()
|
||||
}
|
||||
}
|
||||
|
||||
func records(n: Int) -> AsyncThrowingStream<Record, Error> {
|
||||
AsyncThrowingStream { continuation in
|
||||
for i in 0..<n {
|
||||
continuation.yield(Record(name: "r\(i)", counts: [i], tags: ["i": "\(i)"], inner: Inner(x: Double(i), y: 0), next: nil, kind: .kindA, data: Data([UInt8(i & 0xff)])))
|
||||
}
|
||||
continuation.finish()
|
||||
}
|
||||
}
|
||||
|
||||
func counter(n: Int) throws -> any Counter { Counting(n) }
|
||||
|
||||
func each(words: [String], f: @escaping @Sendable (String, Int) -> Void) -> Int {
|
||||
for (i, w) in words.enumerated() { f(w, i) }
|
||||
return words.count
|
||||
}
|
||||
|
||||
func ask(ns: [Int], f: @escaping @Sendable (Int) throws -> Int) throws -> Int {
|
||||
try ns.reduce(0) { $0 + (try f($1)) }
|
||||
}
|
||||
|
||||
func ticks(interval: Duration, f: @escaping @Sendable (Int) -> Void) -> any Closer {
|
||||
let timer = DispatchSource.makeTimerSource(queue: .global())
|
||||
let c = interval.components
|
||||
let nanos = Int(c.seconds) * 1_000_000_000 + Int(c.attoseconds / 1_000_000_000)
|
||||
nonisolated(unsafe) var n = 0
|
||||
timer.schedule(deadline: .now() + .nanoseconds(nanos), repeating: .nanoseconds(nanos))
|
||||
timer.setEventHandler { n += 1; f(n) }
|
||||
timer.resume()
|
||||
return NativeCloser { timer.cancel() }
|
||||
}
|
||||
|
||||
func use(s: any Scorer, words: [String]) async throws -> Double {
|
||||
var sum = 0.0
|
||||
for w in words { sum += s.score(word: w) }
|
||||
if let first = words.first {
|
||||
let why = try await s.explain(word: first)
|
||||
sum += Double(why.utf8.count)
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
func fill(buf: NativeBuffer, x: Int) throws -> Int {
|
||||
for i in 0..<buf.count { buf.bytes[i] = UInt8(truncatingIfNeeded: i ^ x) }
|
||||
return buf.count
|
||||
}
|
||||
|
||||
func mix(f: Float, d: Double, b: Bool, i: Int8) -> Double { Double(f) + d + (b ? 1 : 0) + Double(i) }
|
||||
|
||||
func box(r: CGRect) throws -> CGRect { r.offsetBy(dx: r.width, dy: r.height) }
|
||||
|
||||
func nothing(e: [Empty]) -> Int { e.count }
|
||||
|
||||
func onMain(r: Record, f: @escaping @Sendable (Inner) -> Void) throws -> Texts {
|
||||
f(r.inner)
|
||||
return Texts(s: r.name, b: r.data)
|
||||
}
|
||||
}
|
||||
|
||||
final class Counting: Counter, @unchecked Sendable {
|
||||
let lock = NSLock()
|
||||
var n: Int
|
||||
init(_ n: Int) { self.n = n }
|
||||
func next() -> Int {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
n += 1
|
||||
return n - 1
|
||||
}
|
||||
func same() -> any Counter {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return Counting(n)
|
||||
}
|
||||
func close() throws {}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
/.build
|
||||
/.swiftpm
|
||||
@@ -0,0 +1,13 @@
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Uses",
|
||||
platforms: [.macOS(.v13)],
|
||||
products: [.library(name: "Uses", type: .dynamic, targets: ["Uses"])],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(name: "Uses"),
|
||||
],
|
||||
swiftLanguageModes: [.v5]
|
||||
)
|
||||
+960
@@ -0,0 +1,960 @@
|
||||
// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.
|
||||
// mygo:native 3 49247f7c2dec49eb
|
||||
//
|
||||
// The declarations of package uses, which the implementation conforms to,
|
||||
// and the functions Go calls. See docs/native-modules.md.
|
||||
|
||||
import Foundation
|
||||
#if canImport(IOSurface)
|
||||
import CoreVideo
|
||||
import IOSurface
|
||||
#endif
|
||||
#if canImport(AppKit)
|
||||
import AppKit
|
||||
#elseif canImport(UIKit)
|
||||
import UIKit
|
||||
#endif
|
||||
import Roundtrip
|
||||
|
||||
// MARK: - Declarations
|
||||
|
||||
/// Mixer takes roundtrip's values.
|
||||
public protocol Mixer: AnyObject {
|
||||
/// Pair returns p with its record's counts summed into N.
|
||||
func pair(p: Pair) throws -> Pair
|
||||
/// Kinds returns the kinds of the records.
|
||||
func kinds(rs: [Roundtrip.Record]) -> [Roundtrip.Kind]
|
||||
/// Next asks c, roundtrip's, for its next count.
|
||||
func next(c: any Roundtrip.Counter) -> Int
|
||||
}
|
||||
|
||||
/// Pair holds a record of roundtrip's.
|
||||
public struct Pair: Sendable, Hashable {
|
||||
public var r: Roundtrip.Record
|
||||
public var inner: Roundtrip.Inner?
|
||||
public var n: Int
|
||||
|
||||
public init(r: Roundtrip.Record, inner: Roundtrip.Inner? = nil, n: Int) {
|
||||
self.r = r
|
||||
self.inner = inner
|
||||
self.n = n
|
||||
}
|
||||
}
|
||||
|
||||
/// The errors package uses declares, with native.NewError: none.
|
||||
public struct UsesError: Error, Sendable, RawRepresentable {
|
||||
public let rawValue: String
|
||||
public init?(rawValue: String) { return nil }
|
||||
}
|
||||
|
||||
// MARK: - What Go calls
|
||||
|
||||
@_cdecl("mygo_uses_init")
|
||||
public func _mygo_init(_ cb: _MygoCallback, _ idBase: UInt64, _ malloc: UnsafeRawPointer?, _ free: UnsafeRawPointer?) {
|
||||
_mygoCallback = cb
|
||||
_mygoIDBase = idBase
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_new_Mixer")
|
||||
public func _mygo_new_Mixer(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { _w in
|
||||
let v: any Mixer = try _mygoCall(makeMixer)
|
||||
_w.u64(_mygoRetain(v))
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_Mixer_Pair")
|
||||
public func _mygo_Mixer_Pair(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { _w in
|
||||
let _o: any Mixer = _mygoObject(obj)
|
||||
var _a = _MygoReader(args, n)
|
||||
let _p0 = try _mygoRead_Pair(&_a)
|
||||
let _r = try _o.pair(p: _p0)
|
||||
_mygoWrite_Pair(&_w, _r)
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_Mixer_Kinds")
|
||||
public func _mygo_Mixer_Kinds(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { _w in
|
||||
let _o: any Mixer = _mygoObject(obj)
|
||||
var _a = _MygoReader(args, n)
|
||||
let _p0 = try _mygoRead_slice_Roundtrip_Record(&_a)
|
||||
let _r = _o.kinds(rs: _p0)
|
||||
_mygoWrite_slice_Roundtrip_Kind(&_w, _r)
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_Mixer_Next")
|
||||
public func _mygo_Mixer_Next(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { _w in
|
||||
let _o: any Mixer = _mygoObject(obj)
|
||||
var _a = _MygoReader(args, n)
|
||||
let _p0 = try _a.u64()
|
||||
let _r = _o.next(c: (_mygoObject(_p0) as any Roundtrip.Counter))
|
||||
_w.i64(Int64(truncatingIfNeeded: _r))
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_close")
|
||||
public func _mygo_close(_ obj: UInt64, _ args: UnsafeRawPointer?, _ n: Int, _ call: UInt64) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { _ in
|
||||
let o = _mygoAnyObject(obj)
|
||||
if let c = o as? any Closer { try c.close() }
|
||||
#if canImport(AppKit) || canImport(UIKit)
|
||||
// A view closed leaves the windows showing it; Go closes views on
|
||||
// the main thread.
|
||||
if let v = o as? NativeView { MainActor.assumeIsolated { v.removeFromSuperview() } }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_release")
|
||||
public func _mygo_release(_ obj: UInt64) {
|
||||
_mygoRelease(obj)
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_cancel")
|
||||
public func _mygo_cancel(_ call: UInt64) {
|
||||
_mygoTasks.cancel(call)
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_next")
|
||||
public func _mygo_next(_ call: UInt64) {
|
||||
_mygoDemands.get(call)?.yield(())
|
||||
}
|
||||
|
||||
@_cdecl("mygo_uses_resume")
|
||||
public func _mygo_resume(_ cont: UInt64, _ block: UnsafeMutableRawPointer?) {
|
||||
if let c = _mygoConts.remove(cont) {
|
||||
c.resume(returning: _MygoBlock(p: block))
|
||||
} else {
|
||||
free(block)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Encoding
|
||||
|
||||
func _mygoRead_Pair(_ r: inout _MygoReader) throws -> Pair {
|
||||
return Pair(
|
||||
r: try _mygoRead_Roundtrip_Record(&r),
|
||||
inner: try _mygoRead_ptr_Roundtrip_Inner(&r),
|
||||
n: Int(truncatingIfNeeded: try r.i64())
|
||||
)
|
||||
}
|
||||
|
||||
func _mygoWrite_Pair(_ w: inout _MygoWriter, _ v: Pair) {
|
||||
_mygoWrite_Roundtrip_Record(&w, v.r)
|
||||
_mygoWrite_ptr_Roundtrip_Inner(&w, v.inner)
|
||||
w.i64(Int64(truncatingIfNeeded: v.n))
|
||||
}
|
||||
|
||||
func _mygoRead_Roundtrip_Inner(_ r: inout _MygoReader) throws -> Roundtrip.Inner {
|
||||
return Roundtrip.Inner(
|
||||
x: try r.double(),
|
||||
y: try r.double()
|
||||
)
|
||||
}
|
||||
|
||||
func _mygoWrite_Roundtrip_Inner(_ w: inout _MygoWriter, _ v: Roundtrip.Inner) {
|
||||
w.double(v.x)
|
||||
w.double(v.y)
|
||||
}
|
||||
|
||||
func _mygoRead_Roundtrip_Kind(_ r: inout _MygoReader) throws -> Roundtrip.Kind {
|
||||
let raw = try r.string()
|
||||
guard let v = Roundtrip.Kind(rawValue: raw) else { throw _MygoWireError.value("Roundtrip.Kind", raw) }
|
||||
return v
|
||||
}
|
||||
|
||||
func _mygoWrite_Roundtrip_Kind(_ w: inout _MygoWriter, _ v: Roundtrip.Kind) {
|
||||
w.string(v.rawValue)
|
||||
}
|
||||
|
||||
func _mygoRead_Roundtrip_Record(_ r: inout _MygoReader) throws -> Roundtrip.Record {
|
||||
return Roundtrip.Record(
|
||||
name: try r.string(),
|
||||
counts: try _mygoRead_slice_int(&r),
|
||||
tags: try _mygoRead_map_string(&r),
|
||||
inner: try _mygoRead_Roundtrip_Inner(&r),
|
||||
next: try _mygoRead_ptr_Roundtrip_Inner(&r),
|
||||
kind: try _mygoRead_Roundtrip_Kind(&r),
|
||||
data: try r.data()
|
||||
)
|
||||
}
|
||||
|
||||
func _mygoWrite_Roundtrip_Record(_ w: inout _MygoWriter, _ v: Roundtrip.Record) {
|
||||
w.string(v.name)
|
||||
_mygoWrite_slice_int(&w, v.counts)
|
||||
_mygoWrite_map_string(&w, v.tags)
|
||||
_mygoWrite_Roundtrip_Inner(&w, v.inner)
|
||||
_mygoWrite_ptr_Roundtrip_Inner(&w, v.next)
|
||||
_mygoWrite_Roundtrip_Kind(&w, v.kind)
|
||||
w.data(v.data)
|
||||
}
|
||||
|
||||
func _mygoRead_map_string(_ r: inout _MygoReader) throws -> [String: String] {
|
||||
let n = try r.count()
|
||||
var v: [String: String] = [:]
|
||||
v.reserveCapacity(n)
|
||||
for _ in 0..<n {
|
||||
let k = try r.string()
|
||||
v[k] = try r.string()
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func _mygoWrite_map_string(_ w: inout _MygoWriter, _ v: [String: String]) {
|
||||
w.count(v.count)
|
||||
for (k, x) in v {
|
||||
w.string(k)
|
||||
w.string(x)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoRead_ptr_Roundtrip_Inner(_ r: inout _MygoReader) throws -> Roundtrip.Inner? {
|
||||
if try r.bool() { return try _mygoRead_Roundtrip_Inner(&r) }
|
||||
return nil
|
||||
}
|
||||
|
||||
func _mygoWrite_ptr_Roundtrip_Inner(_ w: inout _MygoWriter, _ v: Roundtrip.Inner?) {
|
||||
if let x = v {
|
||||
w.bool(true)
|
||||
_mygoWrite_Roundtrip_Inner(&w, x)
|
||||
} else {
|
||||
w.bool(false)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoRead_slice_Roundtrip_Kind(_ r: inout _MygoReader) throws -> [Roundtrip.Kind] {
|
||||
let n = try r.count()
|
||||
var v: [Roundtrip.Kind] = []
|
||||
v.reserveCapacity(n)
|
||||
for _ in 0..<n { v.append(try _mygoRead_Roundtrip_Kind(&r)) }
|
||||
return v
|
||||
}
|
||||
|
||||
func _mygoWrite_slice_Roundtrip_Kind(_ w: inout _MygoWriter, _ v: [Roundtrip.Kind]) {
|
||||
w.count(v.count)
|
||||
for x in v { _mygoWrite_Roundtrip_Kind(&w, x) }
|
||||
}
|
||||
|
||||
func _mygoRead_slice_Roundtrip_Record(_ r: inout _MygoReader) throws -> [Roundtrip.Record] {
|
||||
let n = try r.count()
|
||||
var v: [Roundtrip.Record] = []
|
||||
v.reserveCapacity(n)
|
||||
for _ in 0..<n { v.append(try _mygoRead_Roundtrip_Record(&r)) }
|
||||
return v
|
||||
}
|
||||
|
||||
func _mygoWrite_slice_Roundtrip_Record(_ w: inout _MygoWriter, _ v: [Roundtrip.Record]) {
|
||||
w.count(v.count)
|
||||
for x in v { _mygoWrite_Roundtrip_Record(&w, x) }
|
||||
}
|
||||
|
||||
func _mygoRead_slice_int(_ r: inout _MygoReader) throws -> [Int] {
|
||||
let n = try r.count()
|
||||
var v: [Int] = []
|
||||
v.reserveCapacity(n)
|
||||
for _ in 0..<n { v.append(Int(truncatingIfNeeded: try r.i64())) }
|
||||
return v
|
||||
}
|
||||
|
||||
func _mygoWrite_slice_int(_ w: inout _MygoWriter, _ v: [Int]) {
|
||||
w.count(v.count)
|
||||
for x in v { w.i64(Int64(truncatingIfNeeded: x)) }
|
||||
}
|
||||
|
||||
// MARK: - Types for the implementation
|
||||
|
||||
/// Errors an implementation throws that are not the module's own.
|
||||
public enum NativeError: Error, Sendable {
|
||||
/// Reaches Go as errors.ErrUnsupported: the system lacks what the
|
||||
/// implementation needs, such as a framework of a newer version.
|
||||
case unsupported
|
||||
/// Reaches Go as native.ErrClosed.
|
||||
case closed
|
||||
/// An error a Go function or method returned.
|
||||
case go(String)
|
||||
}
|
||||
|
||||
/// What stops what a method started, as Go's io.Closer.
|
||||
public protocol Closer: AnyObject {
|
||||
func close() throws
|
||||
}
|
||||
|
||||
/// A Closer that runs a closure, once.
|
||||
public final class NativeCloser: Closer, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var fn: (() -> Void)?
|
||||
|
||||
public init(_ fn: @escaping () -> Void) { self.fn = fn }
|
||||
|
||||
public func close() {
|
||||
lock.lock()
|
||||
let f = fn
|
||||
fn = nil
|
||||
lock.unlock()
|
||||
f?()
|
||||
}
|
||||
}
|
||||
|
||||
/// Memory that Go and the implementation both use: a *native.Buffer.
|
||||
public final class NativeBuffer: @unchecked Sendable {
|
||||
/// The buffer's memory, valid as long as the buffer.
|
||||
public let bytes: UnsafeMutableRawBufferPointer
|
||||
private let owned: Bool
|
||||
/// The pool the buffer goes back to once Go is done with it.
|
||||
fileprivate weak var pool: NativeBufferPool?
|
||||
|
||||
/// Makes a buffer of count bytes, which the implementation may yield
|
||||
/// from a stream: Go reads it until its loop asks for the next value.
|
||||
public init(count: Int) {
|
||||
bytes = .allocate(byteCount: Swift.max(count, 1), alignment: 16)
|
||||
owned = true
|
||||
}
|
||||
|
||||
public var count: Int { bytes.count }
|
||||
|
||||
/// The buffer of Go's at p.
|
||||
init(p: UInt64, count: Int) {
|
||||
bytes = UnsafeMutableRawBufferPointer(start: UnsafeMutableRawPointer(bitPattern: UInt(p)), count: count)
|
||||
owned = false
|
||||
}
|
||||
|
||||
deinit {
|
||||
if owned { bytes.deallocate() }
|
||||
}
|
||||
|
||||
/// Gives the buffer back to its pool, as Go's loop moved on.
|
||||
fileprivate func recycle() { pool?.put(self) }
|
||||
}
|
||||
|
||||
/// Buffers of one size that a stream yields, each reused once Go's loop
|
||||
/// moves on from it, so that a stream of buffers allocates none once it
|
||||
/// runs: get one, fill it, yield it.
|
||||
public final class NativeBufferPool: @unchecked Sendable {
|
||||
/// The size of the pool's buffers.
|
||||
public let size: Int
|
||||
private let lock = NSLock()
|
||||
private var free: [NativeBuffer] = []
|
||||
|
||||
public init(size: Int) { self.size = size }
|
||||
|
||||
/// Returns a buffer Go is done with, or a new one.
|
||||
public func get() -> NativeBuffer {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if let b = free.popLast() { return b }
|
||||
let b = NativeBuffer(count: size)
|
||||
b.pool = self
|
||||
return b
|
||||
}
|
||||
|
||||
fileprivate func put(_ b: NativeBuffer) {
|
||||
lock.lock()
|
||||
free.append(b)
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
/// An image on the GPU that native UI shows: a *native.Texture. Present
|
||||
/// frames into it, IOSurfaces or CVPixelBuffers backed by them, which show
|
||||
/// in the next frame of the windows showing it.
|
||||
public final class NativeTexture: @unchecked Sendable {
|
||||
let id: UInt64
|
||||
|
||||
init(id: UInt64) { self.id = id }
|
||||
|
||||
#if canImport(IOSurface)
|
||||
/// The attributes of the pixel buffers native UI draws without
|
||||
/// converting them: 32-bit BGRA, backed by IOSurfaces, for Metal.
|
||||
public var pixelBufferAttributes: [String: Any] {
|
||||
[
|
||||
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
|
||||
kCVPixelBufferIOSurfacePropertiesKey as String: [String: Any](),
|
||||
kCVPixelBufferMetalCompatibilityKey as String: true,
|
||||
]
|
||||
}
|
||||
|
||||
/// Shows surface, 32-bit BGRA, in the next frame. Native UI keeps it
|
||||
/// until another one replaces it: draw the next frame into another
|
||||
/// surface, as a pool of pixel buffers gives.
|
||||
public func present(_ surface: IOSurfaceRef) {
|
||||
let p = Unmanaged.passRetained(surface).toOpaque()
|
||||
_mygoSend(_mygoKindPresent, id, Int64(Int(bitPattern: p)), nil)
|
||||
}
|
||||
|
||||
/// Shows the IOSurface backing buffer in the next frame.
|
||||
public func present(_ buffer: CVPixelBuffer) {
|
||||
guard let s = CVPixelBufferGetIOSurface(buffer)?.takeUnretainedValue() else { return }
|
||||
present(s)
|
||||
}
|
||||
|
||||
#endif
|
||||
#if os(macOS)
|
||||
/// Calls f on each refresh of the display, with the host time the
|
||||
/// frame will show at, in seconds (as CACurrentMediaTime counts),
|
||||
/// until the link is invalidated.
|
||||
public func displayLink(_ f: @escaping @Sendable (CFTimeInterval) -> Void) -> NativeDisplayLink {
|
||||
NativeDisplayLink(f)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
/// Calls back on each refresh of the display, until invalidated.
|
||||
public final class NativeDisplayLink: @unchecked Sendable {
|
||||
private var link: CVDisplayLink?
|
||||
|
||||
init(_ f: @escaping @Sendable (CFTimeInterval) -> Void) {
|
||||
CVDisplayLinkCreateWithActiveCGDisplays(&link)
|
||||
guard let link else { return }
|
||||
let frequency = CVGetHostClockFrequency()
|
||||
CVDisplayLinkSetOutputHandler(link) { _, _, out, _, _ in
|
||||
f(Double(out.pointee.hostTime) / frequency)
|
||||
return kCVReturnSuccess
|
||||
}
|
||||
CVDisplayLinkStart(link)
|
||||
}
|
||||
|
||||
/// Stops the callbacks.
|
||||
public func invalidate() {
|
||||
if let link { CVDisplayLinkStop(link) }
|
||||
link = nil
|
||||
}
|
||||
|
||||
deinit { invalidate() }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Glue
|
||||
|
||||
public typealias _MygoCallback = @convention(c) (UInt64, UInt64, Int64, UnsafeRawPointer?, Int) -> UnsafeMutableRawPointer?
|
||||
|
||||
nonisolated(unsafe) var _mygoCallback: _MygoCallback?
|
||||
|
||||
let _mygoKindResult: UInt64 = 1
|
||||
let _mygoKindItem: UInt64 = 2
|
||||
let _mygoKindNotify: UInt64 = 3
|
||||
let _mygoKindAsk: UInt64 = 4
|
||||
let _mygoKindRelease: UInt64 = 5
|
||||
let _mygoKindInvoke: UInt64 = 6
|
||||
let _mygoKindInvokeAsync: UInt64 = 7
|
||||
let _mygoKindCancel: UInt64 = 8
|
||||
let _mygoKindPresent: UInt64 = 9
|
||||
|
||||
// Values cross in a binary encoding, which package native describes, in
|
||||
// the order of the declarations: every integer as 8 bytes, little-endian,
|
||||
// floats as Double, bools as a byte, strings, Data, arrays and
|
||||
// dictionaries as their count then their contents, optionals as a Bool
|
||||
// then the value, structs as their fields, enums as their raw values.
|
||||
|
||||
/// Writes values for Go, after the 16 bytes of a block's head: its status
|
||||
/// and its length.
|
||||
struct _MygoWriter {
|
||||
private(set) var p: UnsafeMutableRawPointer
|
||||
private var cap: Int
|
||||
private(set) var n = 16
|
||||
|
||||
init() {
|
||||
cap = 128
|
||||
p = malloc(cap)!
|
||||
}
|
||||
|
||||
private mutating func reserve(_ k: Int) {
|
||||
if n + k <= cap { return }
|
||||
cap = Swift.max(cap * 2, n + k)
|
||||
p = realloc(p, cap)!
|
||||
}
|
||||
|
||||
mutating func raw(_ b: UnsafeRawBufferPointer) {
|
||||
guard let base = b.baseAddress, b.count > 0 else { return }
|
||||
reserve(b.count)
|
||||
(p + n).copyMemory(from: base, byteCount: b.count)
|
||||
n += b.count
|
||||
}
|
||||
|
||||
mutating func u64(_ v: UInt64) {
|
||||
reserve(8)
|
||||
p.storeBytes(of: v.littleEndian, toByteOffset: n, as: UInt64.self)
|
||||
n += 8
|
||||
}
|
||||
|
||||
mutating func u8(_ v: UInt8) {
|
||||
reserve(1)
|
||||
p.storeBytes(of: v, toByteOffset: n, as: UInt8.self)
|
||||
n += 1
|
||||
}
|
||||
|
||||
mutating func i64(_ v: Int64) { u64(UInt64(bitPattern: v)) }
|
||||
mutating func bool(_ v: Bool) { u8(v ? 1 : 0) }
|
||||
mutating func double(_ v: Double) { u64(v.bitPattern) }
|
||||
mutating func count(_ c: Int) { i64(Int64(c)) }
|
||||
|
||||
mutating func string(_ s: String) {
|
||||
var s = s
|
||||
s.withUTF8 { b in
|
||||
self.count(b.count)
|
||||
self.raw(UnsafeRawBufferPointer(b))
|
||||
}
|
||||
}
|
||||
|
||||
mutating func data(_ d: Data) {
|
||||
count(d.count)
|
||||
d.withUnsafeBytes { self.raw($0) }
|
||||
}
|
||||
|
||||
mutating func date(_ d: Date) {
|
||||
let t = d.timeIntervalSince1970
|
||||
var s = t.rounded(.down)
|
||||
var ns = ((t - s) * 1e9).rounded()
|
||||
if ns >= 1e9 {
|
||||
s += 1
|
||||
ns -= 1e9
|
||||
}
|
||||
i64(Int64(s))
|
||||
i64(Int64(ns))
|
||||
}
|
||||
|
||||
mutating func rect(_ r: CGRect) {
|
||||
double(Double(r.minX))
|
||||
double(Double(r.minY))
|
||||
double(Double(r.width))
|
||||
double(Double(r.height))
|
||||
}
|
||||
|
||||
mutating func buffer(_ b: NativeBuffer) {
|
||||
u64(UInt64(UInt(bitPattern: b.bytes.baseAddress)))
|
||||
count(b.count)
|
||||
}
|
||||
|
||||
mutating func texture(_ t: NativeTexture) { u64(t.id) }
|
||||
|
||||
/// The values written, without the head.
|
||||
var bytes: UnsafeRawBufferPointer { UnsafeRawBufferPointer(start: p + 16, count: n - 16) }
|
||||
|
||||
/// Forgets what was written.
|
||||
mutating func reset() { n = 16 }
|
||||
|
||||
/// Gives the values to Go as a block, which Go frees.
|
||||
func block(_ status: Int64) -> UnsafeMutableRawPointer {
|
||||
p.storeBytes(of: status, as: Int64.self)
|
||||
p.storeBytes(of: Int64(n - 16), toByteOffset: 8, as: Int64.self)
|
||||
return p
|
||||
}
|
||||
|
||||
/// Frees the writer, which a block Go was given does not need.
|
||||
func free() { Foundation.free(p) }
|
||||
}
|
||||
|
||||
enum _MygoWireError: Error {
|
||||
case short
|
||||
case value(String, String)
|
||||
}
|
||||
|
||||
/// Reads the values Go wrote.
|
||||
struct _MygoReader {
|
||||
let p: UnsafeRawPointer?
|
||||
let n: Int
|
||||
var i = 0
|
||||
|
||||
init(_ p: UnsafeRawPointer?, _ n: Int) {
|
||||
self.p = p
|
||||
self.n = n
|
||||
}
|
||||
|
||||
mutating func take(_ k: Int) throws -> UnsafeRawPointer {
|
||||
guard k >= 0, k <= n - i, let p else { throw _MygoWireError.short }
|
||||
defer { i += k }
|
||||
return p + i
|
||||
}
|
||||
|
||||
mutating func u64() throws -> UInt64 { UInt64(littleEndian: try take(8).loadUnaligned(as: UInt64.self)) }
|
||||
mutating func u8() throws -> UInt8 { try take(1).load(as: UInt8.self) }
|
||||
mutating func i64() throws -> Int64 { Int64(bitPattern: try u64()) }
|
||||
mutating func bool() throws -> Bool { try u8() != 0 }
|
||||
mutating func double() throws -> Double { Double(bitPattern: try u64()) }
|
||||
|
||||
/// Reads the count of an array or a dictionary, whose elements take a
|
||||
/// byte each at least.
|
||||
mutating func count() throws -> Int {
|
||||
let c = try i64()
|
||||
guard c >= 0, c <= Int64(n - i) else { throw _MygoWireError.short }
|
||||
return Int(c)
|
||||
}
|
||||
|
||||
mutating func string() throws -> String {
|
||||
let c = try count()
|
||||
return String(decoding: UnsafeRawBufferPointer(start: try take(c), count: c), as: UTF8.self)
|
||||
}
|
||||
|
||||
mutating func data() throws -> Data {
|
||||
let c = try count()
|
||||
return Data(bytes: try take(c), count: c)
|
||||
}
|
||||
|
||||
mutating func date() throws -> Date {
|
||||
let s = try i64()
|
||||
let ns = try i64()
|
||||
return Date(timeIntervalSince1970: Double(s) + Double(ns) / 1e9)
|
||||
}
|
||||
|
||||
mutating func rect() throws -> CGRect {
|
||||
CGRect(x: try double(), y: try double(), width: try double(), height: try double())
|
||||
}
|
||||
|
||||
mutating func buffer() throws -> NativeBuffer {
|
||||
let p = try u64()
|
||||
return NativeBuffer(p: p, count: Int(try i64()))
|
||||
}
|
||||
|
||||
mutating func texture() throws -> NativeTexture { NativeTexture(id: try u64()) }
|
||||
}
|
||||
|
||||
/// Tells Go something, with the values w holds, and returns its answer, a
|
||||
/// block to read with _mygoAnswer, if any.
|
||||
@discardableResult
|
||||
func _mygoSend(_ kind: UInt64, _ id: UInt64, _ status: Int64, _ w: _MygoWriter?) -> UnsafeMutableRawPointer? {
|
||||
guard let cb = _mygoCallback else { return nil }
|
||||
guard let w, w.n > 16 else { return cb(kind, id, status, nil, 0) }
|
||||
return cb(kind, id, status, w.p + 16, w.n - 16)
|
||||
}
|
||||
|
||||
/// Reads a block Go answered with, and frees it.
|
||||
func _mygoAnswer<R>(_ p: UnsafeMutableRawPointer?, _ read: (inout _MygoReader) throws -> R) throws -> R {
|
||||
guard let p else { throw NativeError.closed }
|
||||
defer { free(p) }
|
||||
let st = p.loadUnaligned(as: Int64.self)
|
||||
var r = _MygoReader(p + 16, Int(p.loadUnaligned(fromByteOffset: 8, as: Int64.self)))
|
||||
if st == 1 { throw _mygoReadError(&r) }
|
||||
return try read(&r)
|
||||
}
|
||||
|
||||
/// Runs what returns at once, which writes its result to w.
|
||||
func _mygoRun(_ body: (inout _MygoWriter) throws -> Void) -> UnsafeMutableRawPointer? {
|
||||
var w = _MygoWriter()
|
||||
do {
|
||||
try body(&w)
|
||||
return w.block(0)
|
||||
} catch {
|
||||
w.reset()
|
||||
_mygoWriteError(&w, error)
|
||||
return w.block(1)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoRunMain(_ body: @MainActor (inout _MygoWriter) throws -> Void) -> UnsafeMutableRawPointer? {
|
||||
_mygoRun { w in try MainActor.assumeIsolated { try body(&w) } }
|
||||
}
|
||||
|
||||
/// Runs what starts an asynchronous call or a stream: Go waits for its
|
||||
/// results through the callback.
|
||||
func _mygoStart(_ body: () throws -> Void) -> UnsafeMutableRawPointer? {
|
||||
var w = _MygoWriter()
|
||||
do {
|
||||
try body()
|
||||
return w.block(2)
|
||||
} catch {
|
||||
_mygoWriteError(&w, error)
|
||||
return w.block(1)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoCall<T>(_ f: () throws -> T) rethrows -> T { try f() }
|
||||
|
||||
@MainActor func _mygoCallMain<T>(_ f: @MainActor () throws -> T) rethrows -> T { try f() }
|
||||
|
||||
func _mygoMust<T>(_ f: () throws -> T) -> T {
|
||||
do {
|
||||
return try f()
|
||||
} catch {
|
||||
fatalError("Uses: Go failed to answer: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoFail<T>() -> T { fatalError("Uses: Go failed to answer") }
|
||||
|
||||
// The kinds of errors, as they cross both ways: the kind, then the code,
|
||||
// domain, number and message.
|
||||
let _mygoErrOther: UInt8 = 0
|
||||
let _mygoErrCode: UInt8 = 1
|
||||
let _mygoErrUnsupported: UInt8 = 2
|
||||
let _mygoErrClosed: UInt8 = 3
|
||||
let _mygoErrCanceled: UInt8 = 4
|
||||
let _mygoErrGo: UInt8 = 5
|
||||
|
||||
func _mygoWriteError(_ w: inout _MygoWriter, _ error: any Error) {
|
||||
var kind = _mygoErrOther
|
||||
var code = "", domain = "", message = ""
|
||||
var number = 0
|
||||
switch error {
|
||||
case let e as UsesError:
|
||||
kind = _mygoErrCode
|
||||
code = e.rawValue
|
||||
case NativeError.unsupported:
|
||||
kind = _mygoErrUnsupported
|
||||
case NativeError.closed:
|
||||
kind = _mygoErrClosed
|
||||
case NativeError.go(let m):
|
||||
kind = _mygoErrGo
|
||||
message = m
|
||||
case is CancellationError:
|
||||
kind = _mygoErrCanceled
|
||||
default:
|
||||
let ns = error as NSError
|
||||
if type(of: error) is NSError.Type {
|
||||
domain = ns.domain
|
||||
message = ns.localizedDescription
|
||||
} else {
|
||||
let name = String(describing: type(of: error))
|
||||
domain = name
|
||||
message = (error as? LocalizedError)?.errorDescription ?? "\(name).\(error)"
|
||||
}
|
||||
number = ns.code
|
||||
}
|
||||
w.u8(kind)
|
||||
w.string(code)
|
||||
w.string(domain)
|
||||
w.i64(Int64(number))
|
||||
w.string(message)
|
||||
}
|
||||
|
||||
func _mygoReadError(_ r: inout _MygoReader) -> any Error {
|
||||
guard let kind = try? r.u8(), let code = try? r.string(), (try? r.string()) != nil, (try? r.i64()) != nil, let message = try? r.string() else {
|
||||
return NativeError.go("an error of Go's that does not decode")
|
||||
}
|
||||
switch kind {
|
||||
case _mygoErrCode: return UsesError(rawValue: code) ?? NativeError.go(message)
|
||||
case _mygoErrUnsupported: return NativeError.unsupported
|
||||
case _mygoErrClosed: return NativeError.closed
|
||||
case _mygoErrCanceled: return CancellationError()
|
||||
default: return NativeError.go(message)
|
||||
}
|
||||
}
|
||||
|
||||
func _mygoRetain(_ v: AnyObject) -> UInt64 {
|
||||
UInt64(UInt(bitPattern: Unmanaged.passRetained(v).toOpaque()))
|
||||
}
|
||||
|
||||
func _mygoAnyObject(_ h: UInt64) -> AnyObject {
|
||||
guard let p = UnsafeRawPointer(bitPattern: UInt(h)) else { fatalError("Uses: Go passed nil for an object") }
|
||||
return Unmanaged<AnyObject>.fromOpaque(p).takeUnretainedValue()
|
||||
}
|
||||
|
||||
func _mygoObject<T>(_ h: UInt64) -> T {
|
||||
guard let v = _mygoAnyObject(h) as? T else { fatalError("Uses: Go passed an object of the wrong type for \(T.self)") }
|
||||
return v
|
||||
}
|
||||
|
||||
func _mygoRelease(_ h: UInt64) {
|
||||
guard let p = UnsafeRawPointer(bitPattern: UInt(h)) else { return }
|
||||
Unmanaged<AnyObject>.fromOpaque(p).release()
|
||||
}
|
||||
|
||||
#if canImport(AppKit)
|
||||
/// The views of native UI's windows, which views of the module are, and
|
||||
/// the windows methods take: AppKit's on macOS, UIKit's on iOS, where a
|
||||
/// window is its view controller.
|
||||
public typealias NativeView = NSView
|
||||
public typealias NativeWindow = NSWindow
|
||||
|
||||
@MainActor func _mygoWindow(_ h: UInt64) -> NSWindow {
|
||||
let w: NSWindow = _mygoObject(h)
|
||||
return w
|
||||
}
|
||||
|
||||
/// Turns a rectangle of native UI, whose origin is the window's top-left,
|
||||
/// into the coordinates of the window's content view.
|
||||
@MainActor func _mygoFlip(_ r: CGRect, in w: NSWindow) -> CGRect {
|
||||
guard let v = w.contentView, !v.isFlipped else { return r }
|
||||
return CGRect(x: r.minX, y: v.bounds.height - r.minY - r.height, width: r.width, height: r.height)
|
||||
}
|
||||
#elseif canImport(UIKit)
|
||||
public typealias NativeView = UIView
|
||||
public typealias NativeWindow = UIViewController
|
||||
|
||||
/// The view controller of a window of the app, which the host keeps by its
|
||||
/// number: Go's handle of it.
|
||||
@MainActor func _mygoWindow(_ h: UInt64) -> UIViewController {
|
||||
guard let windows = NSClassFromString("MyGoWindows") as? NSObject.Type,
|
||||
let c = windows.perform(NSSelectorFromString("controller:"), with: NSNumber(value: h))?.takeUnretainedValue() as? UIViewController else {
|
||||
fatalError("Uses: the window Go passed is gone")
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
/// UIKit's coordinates are native UI's: from the top-left.
|
||||
@MainActor func _mygoFlip(_ r: CGRect, in w: UIViewController) -> CGRect { r }
|
||||
#endif
|
||||
|
||||
final class _MygoTable<V>: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var values: [UInt64: V] = [:]
|
||||
func put(_ k: UInt64, _ v: V) { lock.lock(); values[k] = v; lock.unlock() }
|
||||
func get(_ k: UInt64) -> V? { lock.lock(); defer { lock.unlock() }; return values[k] }
|
||||
@discardableResult func remove(_ k: UInt64) -> V? { lock.lock(); defer { lock.unlock() }; return values.removeValue(forKey: k) }
|
||||
}
|
||||
|
||||
/// The tasks of asynchronous calls and streams, by their call, which Go
|
||||
/// cancels.
|
||||
final class _MygoTasks: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var tasks: [UInt64: Task<Void, Never>] = [:]
|
||||
private var done: Set<UInt64> = []
|
||||
private var canceled: Set<UInt64> = []
|
||||
|
||||
func put(_ call: UInt64, _ t: Task<Void, Never>) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if done.remove(call) != nil { return }
|
||||
if canceled.remove(call) != nil { t.cancel() }
|
||||
tasks[call] = t
|
||||
}
|
||||
|
||||
func finish(_ call: UInt64) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if tasks.removeValue(forKey: call) == nil { done.insert(call) }
|
||||
canceled.remove(call)
|
||||
}
|
||||
|
||||
func cancel(_ call: UInt64) {
|
||||
lock.lock()
|
||||
let t = tasks.removeValue(forKey: call)
|
||||
if t == nil, done.remove(call) == nil { canceled.insert(call) }
|
||||
lock.unlock()
|
||||
t?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
let _mygoTasks = _MygoTasks()
|
||||
let _mygoDemands = _MygoTable<AsyncStream<Void>.Continuation>()
|
||||
let _mygoConts = _MygoTable<CheckedContinuation<_MygoBlock, Never>>()
|
||||
|
||||
/// A block Go answered with, for a continuation.
|
||||
struct _MygoBlock: @unchecked Sendable {
|
||||
let p: UnsafeMutableRawPointer?
|
||||
}
|
||||
|
||||
private let _mygoIDLock = NSLock()
|
||||
nonisolated(unsafe) private var _mygoLastID: UInt64 = 0
|
||||
/// The module's index, from Go, in the high bits of every id, which makes
|
||||
/// the ids of continuations unique among modules.
|
||||
nonisolated(unsafe) var _mygoIDBase: UInt64 = 0
|
||||
|
||||
func _mygoNextID() -> UInt64 {
|
||||
_mygoIDLock.lock()
|
||||
defer { _mygoIDLock.unlock() }
|
||||
_mygoLastID += 1
|
||||
return _mygoIDBase | _mygoLastID
|
||||
}
|
||||
|
||||
func _mygoFinish(_ call: UInt64, _ body: (inout _MygoWriter) async throws -> Void) async {
|
||||
var w = _MygoWriter()
|
||||
var status: Int64 = 0
|
||||
do {
|
||||
try await body(&w)
|
||||
} catch {
|
||||
w.reset()
|
||||
_mygoWriteError(&w, error)
|
||||
status = 1
|
||||
}
|
||||
_mygoTasks.finish(call)
|
||||
_mygoSend(_mygoKindResult, call, status, w)
|
||||
w.free()
|
||||
}
|
||||
|
||||
func _mygoTask(_ call: UInt64, _ body: @escaping (inout _MygoWriter) async throws -> Void) {
|
||||
_mygoTasks.put(call, Task { await _mygoFinish(call, body) })
|
||||
}
|
||||
|
||||
func _mygoTaskMain(_ call: UInt64, _ body: @escaping @MainActor (inout _MygoWriter) async throws -> Void) {
|
||||
_mygoTasks.put(call, Task { @MainActor in await _mygoFinish(call, body) })
|
||||
}
|
||||
|
||||
func _mygoIterate<S: AsyncSequence & Sendable>(_ call: UInt64, _ s: S, _ demand: AsyncStream<Void>, _ enc: (inout _MygoWriter, S.Element) -> Void) async {
|
||||
var it = s.makeAsyncIterator()
|
||||
var lent: S.Element? = nil
|
||||
var w = _MygoWriter()
|
||||
for await _ in demand {
|
||||
// Go is done with what the previous value lent.
|
||||
(lent as? NativeBuffer)?.recycle()
|
||||
lent = nil
|
||||
w.reset()
|
||||
do {
|
||||
guard let v = try await it.next() else {
|
||||
_mygoSend(_mygoKindItem, call, 3, nil)
|
||||
break
|
||||
}
|
||||
lent = v
|
||||
enc(&w, v)
|
||||
_mygoSend(_mygoKindItem, call, 0, w)
|
||||
} catch {
|
||||
_mygoWriteError(&w, error)
|
||||
_mygoSend(_mygoKindItem, call, 1, w)
|
||||
break
|
||||
}
|
||||
}
|
||||
w.free()
|
||||
withExtendedLifetime(lent) {}
|
||||
_mygoDemands.remove(call)
|
||||
_mygoTasks.finish(call)
|
||||
}
|
||||
|
||||
func _mygoDemand(_ call: UInt64) -> AsyncStream<Void> {
|
||||
var cont: AsyncStream<Void>.Continuation!
|
||||
let demand = AsyncStream<Void>(bufferingPolicy: .unbounded) { cont = $0 }
|
||||
_mygoDemands.put(call, cont)
|
||||
return demand
|
||||
}
|
||||
|
||||
func _mygoStream<S: AsyncSequence & Sendable>(_ call: UInt64, _ make: @escaping () -> S, _ enc: @escaping (inout _MygoWriter, S.Element) -> Void) {
|
||||
let demand = _mygoDemand(call)
|
||||
_mygoTasks.put(call, Task { await _mygoIterate(call, make(), demand, enc) })
|
||||
}
|
||||
|
||||
func _mygoStreamMain<S: AsyncSequence & Sendable>(_ call: UInt64, _ make: @escaping @MainActor () -> S, _ enc: @escaping (inout _MygoWriter, S.Element) -> Void) {
|
||||
let demand = _mygoDemand(call)
|
||||
_mygoTasks.put(call, Task { @MainActor in await _mygoIterate(call, make(), demand, enc) })
|
||||
}
|
||||
|
||||
/// A Go function the implementation calls: a notification, or a question
|
||||
/// Go answers at once. Both take the writer of the arguments, and free it.
|
||||
final class _MygoGoFunc: @unchecked Sendable {
|
||||
let id: UInt64
|
||||
init(_ id: UInt64) { self.id = id }
|
||||
deinit { if id != 0 { _mygoSend(_mygoKindRelease, id, 0, nil) } }
|
||||
|
||||
func notify(_ w: _MygoWriter) {
|
||||
if id != 0 { _mygoSend(_mygoKindNotify, id, 0, w) }
|
||||
w.free()
|
||||
}
|
||||
|
||||
func ask<R>(_ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) throws -> R {
|
||||
defer { w.free() }
|
||||
guard id != 0 else { throw NativeError.closed }
|
||||
return try _mygoAnswer(_mygoSend(_mygoKindAsk, id, 0, w), read)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the method of a value of Go's that w names, with the arguments
|
||||
/// after it, and frees w.
|
||||
func _mygoInvoke<R>(_ id: UInt64, _ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) throws -> R {
|
||||
defer { w.free() }
|
||||
return try _mygoAnswer(_mygoSend(_mygoKindInvoke, id, 0, w), read)
|
||||
}
|
||||
|
||||
func _mygoInvokeAsync<R>(_ id: UInt64, _ w: _MygoWriter, _ read: (inout _MygoReader) throws -> R) async throws -> R {
|
||||
let cont = _mygoNextID()
|
||||
let b = await withTaskCancellationHandler {
|
||||
await withCheckedContinuation { (c: CheckedContinuation<_MygoBlock, Never>) in
|
||||
_mygoConts.put(cont, c)
|
||||
_mygoSend(_mygoKindInvokeAsync, id, Int64(bitPattern: cont), w)
|
||||
w.free()
|
||||
}
|
||||
} onCancel: {
|
||||
_mygoSend(_mygoKindCancel, cont, 0, nil)
|
||||
}
|
||||
return try _mygoAnswer(b.p, read)
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import Foundation
|
||||
import Roundtrip
|
||||
|
||||
// The implementation of package uses, with Foundation only.
|
||||
|
||||
func makeMixer() throws -> any Mixer { Mixing() }
|
||||
|
||||
final class Mixing: Mixer {
|
||||
func pair(p: Pair) throws -> Pair {
|
||||
var p = p
|
||||
p.n = p.r.counts.reduce(0, +)
|
||||
p.inner = p.r.inner
|
||||
return p
|
||||
}
|
||||
|
||||
func kinds(rs: [Record]) -> [Kind] { rs.map(\.kind) }
|
||||
|
||||
func next(c: any Counter) -> Int { c.next() }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Package uses is a native module that uses another, roundtrip: its
|
||||
// structs, enums and objects cross from one module to the other.
|
||||
package uses
|
||||
|
||||
import "github.com/egoist/mygo/native/internal/roundtrip"
|
||||
|
||||
// Mixer takes roundtrip's values.
|
||||
//
|
||||
//mygo:native
|
||||
type Mixer interface {
|
||||
// Pair returns p with its record's counts summed into N.
|
||||
Pair(p Pair) (Pair, error)
|
||||
// Kinds returns the kinds of the records.
|
||||
Kinds(rs []roundtrip.Record) []roundtrip.Kind
|
||||
// Next asks c, roundtrip's, for its next count.
|
||||
Next(c roundtrip.Counter) int
|
||||
}
|
||||
|
||||
// Pair holds a record of roundtrip's.
|
||||
type Pair struct {
|
||||
R roundtrip.Record
|
||||
Inner *roundtrip.Inner
|
||||
N int
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
// Code generated by mygo generate from the interfaces of the native module. DO NOT EDIT.
|
||||
// mygo:native 3 49247f7c2dec49eb
|
||||
|
||||
package uses
|
||||
|
||||
import (
|
||||
_filepath "path/filepath"
|
||||
_runtime "runtime"
|
||||
|
||||
_native "github.com/egoist/mygo/native"
|
||||
"github.com/egoist/mygo/native/internal/roundtrip"
|
||||
)
|
||||
|
||||
// _module describes the module to the runtime.
|
||||
var _module = &_native.Module{Name: "Uses", Symbol: "uses", Langs: []string{"swift"}, SwiftOS: []string{"macos"}, MinMacOS: "13", MinIOS: "", Kotlin: "", Dir: _dir(), Errors: []*_native.Error{}, Deps: []string{"Roundtrip"}}
|
||||
|
||||
// _dir returns the package's directory when the binary knows it, where
|
||||
// mygo dev builds the implementation for go test and go run.
|
||||
func _dir() string {
|
||||
_, file, _, ok := _runtime.Caller(0)
|
||||
if !ok || !_filepath.IsAbs(file) {
|
||||
return ""
|
||||
}
|
||||
return _filepath.Dir(file)
|
||||
}
|
||||
|
||||
func init() {
|
||||
_native.Register(_module, map[string]_native.Wrapper{
|
||||
"Mixer": {Flags: 0, Wrap: func(o *_native.Object) any { return &_Mixer{o} }},
|
||||
})
|
||||
}
|
||||
|
||||
// NewMixer makes the implementation of Mixer on this platform. It returns
|
||||
// errors.ErrUnsupported where the module has none, or the system lacks
|
||||
// what it needs.
|
||||
func NewMixer() (Mixer, error) {
|
||||
o, err := _module.New("Mixer", 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &_Mixer{o}, nil
|
||||
}
|
||||
|
||||
// _Mixer calls the platform's implementation of Mixer.
|
||||
type _Mixer struct{ o *_native.Object }
|
||||
|
||||
// NativeObject returns the platform's object.
|
||||
func (x *_Mixer) NativeObject() *_native.Object { return x.o }
|
||||
|
||||
// _wrapMixer wraps a handle of the platform's, or returns nil.
|
||||
func _wrapMixer(h uint64) Mixer {
|
||||
if h == 0 {
|
||||
return nil
|
||||
}
|
||||
return &_Mixer{_module.Object(h, 0)}
|
||||
}
|
||||
|
||||
func (_x *_Mixer) Pair(p Pair) (Pair, error) {
|
||||
_e := _native.NewEncoder()
|
||||
_enc_Pair(_e, p)
|
||||
var _r Pair
|
||||
_d, _err := _x.NativeObject().Call("Mixer_Pair", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_Pair(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
return _r, _err
|
||||
}
|
||||
|
||||
func (_x *_Mixer) Kinds(rs []roundtrip.Record) []roundtrip.Kind {
|
||||
_e := _native.NewEncoder()
|
||||
_enc_slice_Roundtrip_Record(_e, rs)
|
||||
var _r []roundtrip.Kind
|
||||
_d, _err := _x.NativeObject().Call("Mixer_Kinds", 0, _e)
|
||||
if _err == nil {
|
||||
_r = _dec_slice_Roundtrip_Kind(_d)
|
||||
_err = _d.Close()
|
||||
}
|
||||
_ = _err
|
||||
return _r
|
||||
}
|
||||
|
||||
func (_x *_Mixer) Next(c roundtrip.Counter) int {
|
||||
defer _runtime.KeepAlive(c)
|
||||
_e := _native.NewEncoder()
|
||||
_e.Uint(_native.HandleOf(c))
|
||||
var _r int
|
||||
_d, _err := _x.NativeObject().Call("Mixer_Next", 0, _e)
|
||||
if _err == nil {
|
||||
_r = int(_d.Int())
|
||||
_err = _d.Close()
|
||||
}
|
||||
_ = _err
|
||||
return _r
|
||||
}
|
||||
|
||||
func _enc_Pair(_e *_native.Encoder, _v Pair) {
|
||||
_enc_Roundtrip_Record(_e, _v.R)
|
||||
_enc_ptr_Roundtrip_Inner(_e, _v.Inner)
|
||||
_e.Int(int64(_v.N))
|
||||
}
|
||||
|
||||
func _dec_Pair(_d *_native.Decoder) Pair {
|
||||
return Pair{
|
||||
R: _dec_Roundtrip_Record(_d),
|
||||
Inner: _dec_ptr_Roundtrip_Inner(_d),
|
||||
N: int(_d.Int()),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_Roundtrip_Inner(_e *_native.Encoder, _v roundtrip.Inner) {
|
||||
_e.Float(float64(_v.X))
|
||||
_e.Float(float64(_v.Y))
|
||||
}
|
||||
|
||||
func _dec_Roundtrip_Inner(_d *_native.Decoder) roundtrip.Inner {
|
||||
return roundtrip.Inner{
|
||||
X: float64(_d.Float()),
|
||||
Y: float64(_d.Float()),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_Roundtrip_Kind(_e *_native.Encoder, _v roundtrip.Kind) {
|
||||
_e.String(string(_v))
|
||||
}
|
||||
|
||||
func _dec_Roundtrip_Kind(_d *_native.Decoder) roundtrip.Kind {
|
||||
return roundtrip.Kind(_d.String())
|
||||
}
|
||||
|
||||
func _enc_Roundtrip_Record(_e *_native.Encoder, _v roundtrip.Record) {
|
||||
_e.String(_v.Name)
|
||||
_enc_slice_int(_e, _v.Counts)
|
||||
_enc_map_string(_e, _v.Tags)
|
||||
_enc_Roundtrip_Inner(_e, _v.Inner)
|
||||
_enc_ptr_Roundtrip_Inner(_e, _v.Next)
|
||||
_enc_Roundtrip_Kind(_e, _v.Kind)
|
||||
_e.Bytes(_v.Data)
|
||||
}
|
||||
|
||||
func _dec_Roundtrip_Record(_d *_native.Decoder) roundtrip.Record {
|
||||
return roundtrip.Record{
|
||||
Name: _d.String(),
|
||||
Counts: _dec_slice_int(_d),
|
||||
Tags: _dec_map_string(_d),
|
||||
Inner: _dec_Roundtrip_Inner(_d),
|
||||
Next: _dec_ptr_Roundtrip_Inner(_d),
|
||||
Kind: _dec_Roundtrip_Kind(_d),
|
||||
Data: _d.Bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
func _enc_map_string(_e *_native.Encoder, _v map[string]string) {
|
||||
_e.Len(len(_v))
|
||||
for _k, _x := range _v {
|
||||
_e.String(_k)
|
||||
_e.String(_x)
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_map_string(_d *_native.Decoder) map[string]string {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make(map[string]string, _n)
|
||||
for range _n {
|
||||
_k := _d.String()
|
||||
_v[_k] = _d.String()
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_ptr_Roundtrip_Inner(_e *_native.Encoder, _v *roundtrip.Inner) {
|
||||
if _v == nil {
|
||||
_e.Bool(false)
|
||||
return
|
||||
}
|
||||
_e.Bool(true)
|
||||
_enc_Roundtrip_Inner(_e, *_v)
|
||||
}
|
||||
|
||||
func _dec_ptr_Roundtrip_Inner(_d *_native.Decoder) *roundtrip.Inner {
|
||||
if !_d.Bool() {
|
||||
return nil
|
||||
}
|
||||
_x := _dec_Roundtrip_Inner(_d)
|
||||
return &_x
|
||||
}
|
||||
|
||||
func _enc_slice_Roundtrip_Kind(_e *_native.Encoder, _v []roundtrip.Kind) {
|
||||
_e.Len(len(_v))
|
||||
for _, _x := range _v {
|
||||
_enc_Roundtrip_Kind(_e, _x)
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_slice_Roundtrip_Kind(_d *_native.Decoder) []roundtrip.Kind {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make([]roundtrip.Kind, _n)
|
||||
for _i := range _v {
|
||||
_v[_i] = _dec_Roundtrip_Kind(_d)
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_slice_Roundtrip_Record(_e *_native.Encoder, _v []roundtrip.Record) {
|
||||
_e.Len(len(_v))
|
||||
for _, _x := range _v {
|
||||
_enc_Roundtrip_Record(_e, _x)
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_slice_Roundtrip_Record(_d *_native.Decoder) []roundtrip.Record {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make([]roundtrip.Record, _n)
|
||||
for _i := range _v {
|
||||
_v[_i] = _dec_Roundtrip_Record(_d)
|
||||
}
|
||||
return _v
|
||||
}
|
||||
|
||||
func _enc_slice_int(_e *_native.Encoder, _v []int) {
|
||||
_e.Len(len(_v))
|
||||
for _, _x := range _v {
|
||||
_e.Int(int64(_x))
|
||||
}
|
||||
}
|
||||
|
||||
func _dec_slice_int(_d *_native.Decoder) []int {
|
||||
_n := _d.Len()
|
||||
if _n == 0 {
|
||||
return nil
|
||||
}
|
||||
_v := make([]int, _n)
|
||||
for _i := range _v {
|
||||
_v[_i] = int(_d.Int())
|
||||
}
|
||||
return _v
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package uses_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/native/internal/roundtrip"
|
||||
"github.com/egoist/mygo/native/internal/roundtrip/uses"
|
||||
)
|
||||
|
||||
// mixer makes the module's implementation, skipping where it is not built:
|
||||
// mygo native build -target host native/internal/roundtrip/uses.
|
||||
func mixer(t *testing.T) uses.Mixer {
|
||||
t.Helper()
|
||||
m, err := uses.NewMixer()
|
||||
if errors.Is(err, errors.ErrUnsupported) {
|
||||
t.Skip("no implementation on this platform")
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), "mygo native build") {
|
||||
t.Skip(err)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestOtherModule(t *testing.T) {
|
||||
m := mixer(t)
|
||||
p, err := m.Pair(uses.Pair{R: roundtrip.Record{Name: "r", Counts: []int{1, 2, 3}, Inner: roundtrip.Inner{X: 1, Y: 2}, Kind: roundtrip.KindC}})
|
||||
if err != nil || p.N != 6 || p.R.Name != "r" || p.R.Kind != roundtrip.KindC || p.Inner == nil || *p.Inner != (roundtrip.Inner{X: 1, Y: 2}) {
|
||||
t.Fatalf("Pair = %+v, %v", p, err)
|
||||
}
|
||||
if got := m.Kinds([]roundtrip.Record{{Kind: roundtrip.KindB}, {Kind: roundtrip.KindA}}); !slices.Equal(got, []roundtrip.Kind{roundtrip.KindB, roundtrip.KindA}) {
|
||||
t.Fatalf("Kinds = %v", got)
|
||||
}
|
||||
e, err := roundtrip.NewEcho()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := e.Counter(7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a, b := m.Next(c), c.Next(); a != 7 || b != 8 {
|
||||
t.Fatalf("Next = %d, then %d", a, b)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/zig-out
|
||||
/.zig-cache
|
||||
/zig-pkg
|
||||
@@ -0,0 +1,11 @@
|
||||
const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.Build) void {
|
||||
const module = b.createModule(.{
|
||||
.root_source_file = b.path("src/mygo.zig"),
|
||||
.target = b.standardTargetOptions(.{}),
|
||||
.optimize = b.standardOptimizeOption(.{}),
|
||||
.link_libc = true,
|
||||
});
|
||||
b.installArtifact(b.addLibrary(.{ .name = "Roundtrip", .linkage = .dynamic, .root_module = module }));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,262 @@
|
||||
//! The implementation of package roundtrip in Zig: every value it is given,
|
||||
//! back, as its Swift and Rust implementations do.
|
||||
|
||||
const std = @import("std");
|
||||
const mygo = @import("mygo.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub fn makeEcho() mygo.Error!mygo.Echo {
|
||||
const e = try mygo.allocator.create(Echoer);
|
||||
e.* = .{};
|
||||
return mygo.Echo.of(e);
|
||||
}
|
||||
|
||||
const Echoer = struct {
|
||||
pub fn deinit(self: *Echoer) void {
|
||||
mygo.allocator.destroy(self);
|
||||
}
|
||||
|
||||
pub fn scalars(_: *Echoer, _: Allocator, i: i64, @"i8": i8, @"u16": u16, @"i32": i32, @"u64": u64, @"f32": f32, f: f64, b: bool) mygo.Scalars {
|
||||
return .{
|
||||
.i = i + 1,
|
||||
.@"i8" = @"i8" +% 1,
|
||||
.@"u16" = @"u16" +% 1,
|
||||
.@"i32" = @"i32" + 1,
|
||||
.@"u64" = @"u64" +% 1,
|
||||
.@"f32" = @"f32" + 1,
|
||||
.f = f + 1,
|
||||
.b = !b,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn add(_: *Echoer, _: Allocator, a: i64, b: i64) i64 {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
pub fn text(_: *Echoer, arena: Allocator, s: []const u8, b: []const u8) mygo.Texts {
|
||||
const twice = std.mem.concat(arena, u8, &.{ s, s }) catch @panic("out of memory");
|
||||
const rev = arena.dupe(u8, b) catch @panic("out of memory");
|
||||
std.mem.reverse(u8, rev);
|
||||
return .{ .s = twice, .b = rev };
|
||||
}
|
||||
|
||||
pub fn record(_: *Echoer, arena: Allocator, r: mygo.Record) mygo.Error!mygo.Record {
|
||||
var out = r;
|
||||
const counts = try arena.alloc(i64, r.counts.len);
|
||||
for (counts, r.counts) |*d, c| d.* = c * 2;
|
||||
out.counts = counts;
|
||||
return out;
|
||||
}
|
||||
|
||||
pub fn lists(_: *Echoer, arena: Allocator, words: []const []const u8, nested: []const []const i64) mygo.Error![]const mygo.Entry(i64) {
|
||||
var m: std.ArrayList(mygo.Entry(i64)) = .empty;
|
||||
for (words) |w| try m.append(arena, .{ .key = w, .value = @intCast(w.len) });
|
||||
var sum: i64 = 0;
|
||||
for (nested) |ns| for (ns) |n| {
|
||||
sum += n;
|
||||
};
|
||||
try m.append(arena, .{ .key = "nested", .value = sum });
|
||||
return m.items;
|
||||
}
|
||||
|
||||
pub fn maybe(_: *Echoer, _: Allocator, p: ?i64) ?i64 {
|
||||
return if (p) |v| v + 1 else null;
|
||||
}
|
||||
|
||||
pub fn times(_: *Echoer, _: Allocator, t: mygo.Time, d: i64) mygo.Error!mygo.Moment {
|
||||
return .{ .at = t.add(d), .twice = d * 2 };
|
||||
}
|
||||
|
||||
pub fn kind(_: *Echoer, _: Allocator, k: mygo.Kind, l: mygo.Level) mygo.Error!mygo.Kinds {
|
||||
const next: mygo.Kind = switch (k) {
|
||||
.kind_a => .kind_b,
|
||||
.kind_b => .kind_c,
|
||||
.kind_c => .kind_a,
|
||||
};
|
||||
return .{ .kind = next, .level = if (l == .low) .high else .low };
|
||||
}
|
||||
|
||||
pub fn fail(_: *Echoer, _: Allocator, name: []const u8) mygo.Error!void {
|
||||
if (name.len == 0) return;
|
||||
if (std.mem.eql(u8, name, "named")) return error.Named;
|
||||
if (std.mem.eql(u8, name, "unsupported")) return error.Unsupported;
|
||||
return mygo.fail("RoundtripDomain", 7, name);
|
||||
}
|
||||
|
||||
pub fn wait(_: *Echoer, _: Allocator, ctx: *mygo.Context, d: i64, s: []const u8) mygo.Error![]const u8 {
|
||||
try ctx.sleep(d);
|
||||
return s;
|
||||
}
|
||||
|
||||
const Count = struct {
|
||||
i: i64 = 0,
|
||||
n: i64,
|
||||
fail: i64,
|
||||
|
||||
pub fn next(self: *Count, _: Allocator) mygo.Error!?i64 {
|
||||
if (self.i >= self.n) return null;
|
||||
const i = self.i;
|
||||
self.i += 1;
|
||||
if (i == self.fail) return error.Named;
|
||||
return i;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Count) void {
|
||||
mygo.allocator.destroy(self);
|
||||
}
|
||||
};
|
||||
|
||||
pub fn count(_: *Echoer, _: Allocator, _: *mygo.Context, n: i64, fail_at: i64) mygo.Error!mygo.Iterator(i64) {
|
||||
const c = try mygo.allocator.create(Count);
|
||||
c.* = .{ .n = n, .fail = fail_at };
|
||||
return mygo.Iterator(i64).of(c);
|
||||
}
|
||||
|
||||
const Records = struct {
|
||||
i: i64 = 0,
|
||||
n: i64,
|
||||
|
||||
pub fn next(self: *Records, arena: Allocator) mygo.Error!?mygo.Record {
|
||||
if (self.i >= self.n) return null;
|
||||
const i = self.i;
|
||||
self.i += 1;
|
||||
const counts = try arena.alloc(i64, 1);
|
||||
counts[0] = i;
|
||||
const tags = try arena.alloc(mygo.Entry([]const u8), 1);
|
||||
tags[0] = .{ .key = "i", .value = try std.fmt.allocPrint(arena, "{d}", .{i}) };
|
||||
const data = try arena.alloc(u8, 1);
|
||||
data[0] = @intCast(i & 0xff);
|
||||
return .{
|
||||
.name = try std.fmt.allocPrint(arena, "r{d}", .{i}),
|
||||
.counts = counts,
|
||||
.tags = tags,
|
||||
.inner = .{ .x = @floatFromInt(i), .y = 0 },
|
||||
.next = null,
|
||||
.kind = .kind_a,
|
||||
.data = data,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Records) void {
|
||||
mygo.allocator.destroy(self);
|
||||
}
|
||||
};
|
||||
|
||||
pub fn records(_: *Echoer, _: Allocator, _: *mygo.Context, n: i64) mygo.Error!mygo.Iterator(mygo.Record) {
|
||||
const r = try mygo.allocator.create(Records);
|
||||
r.* = .{ .n = n };
|
||||
return mygo.Iterator(mygo.Record).of(r);
|
||||
}
|
||||
|
||||
pub fn counter(_: *Echoer, _: Allocator, n: i64) mygo.Error!mygo.Counter {
|
||||
return Counting.make(n);
|
||||
}
|
||||
|
||||
pub fn each(_: *Echoer, _: Allocator, words: []const []const u8, f: mygo.EchoEachF) i64 {
|
||||
for (words, 0..) |w, i| f.call(w, @intCast(i));
|
||||
return @intCast(words.len);
|
||||
}
|
||||
|
||||
pub fn ask(_: *Echoer, arena: Allocator, ns: []const i64, f: mygo.EchoAskF) mygo.Error!i64 {
|
||||
var sum: i64 = 0;
|
||||
for (ns) |n| sum += try f.call(arena, n);
|
||||
return sum;
|
||||
}
|
||||
|
||||
const Ticker = struct {
|
||||
stop: std.atomic.Value(bool) = .init(false),
|
||||
done: std.atomic.Value(bool) = .init(false),
|
||||
f: mygo.EchoTicksF,
|
||||
interval: i64,
|
||||
|
||||
fn main(t: *Ticker) void {
|
||||
var n: i64 = 0;
|
||||
while (!t.stop.load(.acquire)) {
|
||||
mygo.io().sleep(.fromNanoseconds(t.interval), .awake) catch {};
|
||||
if (t.stop.load(.acquire)) break;
|
||||
n += 1;
|
||||
t.f.call(n);
|
||||
}
|
||||
t.f.release();
|
||||
// The last of the ticker and its Closer frees it.
|
||||
if (t.done.swap(true, .acq_rel)) mygo.allocator.destroy(t);
|
||||
}
|
||||
|
||||
pub fn close(t: *Ticker) mygo.Error!void {
|
||||
t.stop.store(true, .release);
|
||||
}
|
||||
|
||||
pub fn deinit(t: *Ticker) void {
|
||||
t.stop.store(true, .release);
|
||||
if (t.done.swap(true, .acq_rel)) mygo.allocator.destroy(t);
|
||||
}
|
||||
};
|
||||
|
||||
pub fn ticks(_: *Echoer, _: Allocator, interval: i64, f: mygo.EchoTicksF) mygo.Error!mygo.Closer {
|
||||
const t = try mygo.allocator.create(Ticker);
|
||||
t.* = .{ .f = f.keep(), .interval = interval };
|
||||
const th = std.Thread.spawn(.{}, Ticker.main, .{t}) catch {
|
||||
f.release();
|
||||
mygo.allocator.destroy(t);
|
||||
return mygo.failGo("no thread for the ticker");
|
||||
};
|
||||
th.detach();
|
||||
return mygo.Closer.of(t);
|
||||
}
|
||||
|
||||
pub fn use(_: *Echoer, arena: Allocator, ctx: *mygo.Context, s: mygo.Scorer, words: []const []const u8) mygo.Error!f64 {
|
||||
var sum: f64 = 0;
|
||||
for (words) |w| sum += s.score(arena, w);
|
||||
if (words.len > 0) {
|
||||
const why = try s.explain(arena, ctx, words[0]);
|
||||
sum += @floatFromInt(why.len);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
pub fn fill(_: *Echoer, _: Allocator, buf: mygo.Buffer, x: i64) mygo.Error!i64 {
|
||||
for (buf.bytes(), 0..) |*b, i| b.* = @truncate(@as(u64, @bitCast(@as(i64, @intCast(i)) ^ x)));
|
||||
return @intCast(buf.len);
|
||||
}
|
||||
|
||||
pub fn mix(_: *Echoer, _: Allocator, f: f32, d: f64, b: bool, i: i8) f64 {
|
||||
return @as(f64, f) + d + @as(f64, if (b) 1 else 0) + @as(f64, @floatFromInt(i));
|
||||
}
|
||||
|
||||
pub fn box(_: *Echoer, _: Allocator, r: mygo.Rect) mygo.Error!mygo.Rect {
|
||||
return .{ .x = r.x + r.w, .y = r.y + r.h, .w = r.w, .h = r.h };
|
||||
}
|
||||
|
||||
pub fn nothing(_: *Echoer, _: Allocator, e: []const mygo.Empty) i64 {
|
||||
return @intCast(e.len);
|
||||
}
|
||||
|
||||
pub fn onMain(_: *Echoer, _: Allocator, r: mygo.Record, f: mygo.EchoOnMainF) mygo.Error!mygo.Texts {
|
||||
f.call(r.inner);
|
||||
return .{ .s = r.name, .b = r.data };
|
||||
}
|
||||
};
|
||||
|
||||
const Counting = struct {
|
||||
n: std.atomic.Value(i64),
|
||||
|
||||
fn make(n: i64) mygo.Error!mygo.Counter {
|
||||
const c = try mygo.allocator.create(Counting);
|
||||
c.* = .{ .n = .init(n) };
|
||||
return mygo.Counter.of(c);
|
||||
}
|
||||
|
||||
pub fn close(_: *Counting) mygo.Error!void {}
|
||||
|
||||
pub fn next(self: *Counting, _: Allocator) i64 {
|
||||
return self.n.fetchAdd(1, .seq_cst);
|
||||
}
|
||||
|
||||
pub fn same(self: *Counting, _: Allocator) mygo.Counter {
|
||||
return make(self.n.load(.seq_cst)) catch @panic("out of memory");
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Counting) void {
|
||||
mygo.allocator.destroy(self);
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user