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
Vendored
+58
@@ -0,0 +1,58 @@
|
||||
package native
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Buffer is memory that Go and the implementation both use, which crosses
|
||||
// without a copy: pass one to have the implementation fill it, as
|
||||
// io.Reader fills a slice, or range over the buffers a stream yields. In
|
||||
// Swift it is a NativeBuffer, whose bytes are the same memory.
|
||||
type Buffer struct {
|
||||
p uintptr
|
||||
n int
|
||||
// keep is the Go memory of a buffer where nothing native holds it.
|
||||
keep []byte
|
||||
}
|
||||
|
||||
// NewBuffer makes a buffer of n bytes, zeroed.
|
||||
func NewBuffer(n int) *Buffer {
|
||||
if n < 0 {
|
||||
panic("native: NewBuffer with a negative size")
|
||||
}
|
||||
p := allocate(n)
|
||||
if p == 0 {
|
||||
b := make([]byte, n)
|
||||
return &Buffer{keep: b, n: n, p: bytesPointer(b)}
|
||||
}
|
||||
b := &Buffer{p: p, n: n}
|
||||
clear(b.Bytes())
|
||||
runtime.AddCleanup(b, func(p uintptr) { deallocate(p) }, p)
|
||||
return b
|
||||
}
|
||||
|
||||
// Bytes returns the buffer's contents. A buffer a stream yields is lent
|
||||
// until the loop asks for the next value: copy what you keep, as with
|
||||
// bufio.Scanner.Bytes.
|
||||
func (b *Buffer) Bytes() []byte {
|
||||
if b == nil || b.n == 0 {
|
||||
return nil
|
||||
}
|
||||
if b.keep != nil {
|
||||
return b.keep
|
||||
}
|
||||
return unsafe.Slice(bytesAt(b.p), b.n)
|
||||
}
|
||||
|
||||
// Len returns the size of the buffer.
|
||||
func (b *Buffer) Len() int {
|
||||
if b == nil {
|
||||
return 0
|
||||
}
|
||||
return b.n
|
||||
}
|
||||
|
||||
// bytesAt converts the address of native memory, which Go's collector
|
||||
// does not manage, to a pointer.
|
||||
func bytesAt(p uintptr) *byte { return *(**byte)(unsafe.Pointer(&p)) }
|
||||
Vendored
+392
@@ -0,0 +1,392 @@
|
||||
package native
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/nativehost"
|
||||
"github.com/egoist/mygo/internal/texture"
|
||||
)
|
||||
|
||||
// The status of a result, in the block that carries it both ways.
|
||||
const (
|
||||
statusOK = 0
|
||||
statusError = 1
|
||||
statusPending = 2 // an asynchronous call or a stream started
|
||||
statusEnd = 3 // a stream finished
|
||||
)
|
||||
|
||||
// What the platform tells Go through the one callback every module shares.
|
||||
const (
|
||||
kindResult = 1 // the result of an asynchronous call: id is the call
|
||||
kindItem = 2 // a value of a stream, its error or its end
|
||||
kindNotify = 3 // a callback without results: id is the function
|
||||
kindAsk = 4 // a callback with results, answered at once
|
||||
kindRelease = 5 // the platform let go of a function or an object of Go's
|
||||
kindInvoke = 6 // a method of an object Go implements, answered at once
|
||||
kindInvokeAsync = 7 // one taking a context, answered with resume
|
||||
kindCancel = 8 // the platform canceled what kindInvokeAsync started
|
||||
kindPresent = 9 // a frame for a texture: id is the texture, status the IOSurfaceRef
|
||||
)
|
||||
|
||||
type reply struct {
|
||||
status int64
|
||||
data []byte
|
||||
// block is the platform's memory data is in, freed with free.
|
||||
block uintptr
|
||||
}
|
||||
|
||||
func (r reply) free() {
|
||||
if r.block != 0 {
|
||||
freeBlock(r.block)
|
||||
}
|
||||
}
|
||||
|
||||
// pending holds the calls and streams waiting for the platform.
|
||||
var pending sync.Map // uint64 → chan reply
|
||||
|
||||
var errNotMain = errors.New("native: the method runs on the main thread, which is not running the app's event loop: call it once the app runs (App.Run), or from the main goroutine")
|
||||
|
||||
// onMain runs fn on the main thread when flags say so.
|
||||
func onMain(flags Flags, fn func()) error {
|
||||
if flags&MainThread == 0 {
|
||||
fn()
|
||||
return nil
|
||||
}
|
||||
if ui := nativehost.OnUI; ui != nil {
|
||||
// On phones Go's main thread is its own, and the system's views and
|
||||
// Swift's main actor live on the UI thread.
|
||||
ui(fn)
|
||||
return nil
|
||||
}
|
||||
if mygo.App.IsReady() {
|
||||
ran := false
|
||||
mygo.RunOnMain(func() { fn(); ran = true })
|
||||
if !ran {
|
||||
return errors.New("native: the app has quit")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if isMainThread() {
|
||||
fn()
|
||||
return nil
|
||||
}
|
||||
return errNotMain
|
||||
}
|
||||
|
||||
// call calls a function of the implementation that returns at once, with
|
||||
// the arguments args, which it releases.
|
||||
func (m *Module) call(ctx context.Context, h uint64, sym string, flags Flags, args *Encoder) (*Decoder, error) {
|
||||
lib, err := m.load()
|
||||
if err != nil {
|
||||
args.release()
|
||||
return nil, err
|
||||
}
|
||||
var r reply
|
||||
if flags&MainThread == 0 {
|
||||
r = lib.invoke(m, sym, h, args.bytes(), 0)
|
||||
} else {
|
||||
err = onMain(flags, func() { r = lib.invoke(m, sym, h, args.bytes(), 0) })
|
||||
}
|
||||
args.release()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.result(ctx, sym, r)
|
||||
}
|
||||
|
||||
// callNone calls a function that returns nothing.
|
||||
func (m *Module) callNone(h uint64, sym string, flags Flags) error {
|
||||
d, err := m.call(context.Background(), h, sym, flags, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.Close()
|
||||
}
|
||||
|
||||
// direct calls the C function of a method of numbers.
|
||||
func (m *Module) direct(h uint64, sym string, args []uintptr) uintptr {
|
||||
lib, err := m.load()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return lib.directSym(m, sym, h, args)
|
||||
}
|
||||
|
||||
func (m *Module) result(ctx context.Context, sym string, r reply) (*Decoder, error) {
|
||||
switch r.status {
|
||||
case statusOK:
|
||||
return newDecoder(r.data, r.block), nil
|
||||
case statusError:
|
||||
err := m.decodeError(ctx, r.data)
|
||||
r.free()
|
||||
return nil, err
|
||||
}
|
||||
r.free()
|
||||
return nil, fmt.Errorf("native: %s answered with status %d", sym, r.status)
|
||||
}
|
||||
|
||||
// callAsync calls an asynchronous function of the implementation: it
|
||||
// starts a task, which ctx cancels, and reports through the callback.
|
||||
// Main-thread methods start their task from any thread: it runs on the
|
||||
// main actor.
|
||||
func (m *Module) callAsync(ctx context.Context, h uint64, sym string, args *Encoder) (*Decoder, error) {
|
||||
lib, err := m.load()
|
||||
if err != nil {
|
||||
args.release()
|
||||
return nil, err
|
||||
}
|
||||
id := nextID.Add(1)
|
||||
ch := make(chan reply, 1)
|
||||
pending.Store(id, ch)
|
||||
defer pending.Delete(id)
|
||||
r := lib.invoke(m, sym, h, args.bytes(), id)
|
||||
args.release()
|
||||
if r.status != statusPending {
|
||||
return m.result(ctx, sym, r)
|
||||
}
|
||||
r.free()
|
||||
select {
|
||||
case r = <-ch:
|
||||
case <-ctx.Done():
|
||||
lib.cancel(m, id)
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return m.result(ctx, sym, r)
|
||||
}
|
||||
|
||||
type stream struct {
|
||||
m *Module
|
||||
lib *library
|
||||
sym string
|
||||
id uint64
|
||||
ch chan reply
|
||||
}
|
||||
|
||||
func (m *Module) startStream(h uint64, sym string, flags Flags, args *Encoder) (*stream, error) {
|
||||
lib, err := m.load()
|
||||
if err != nil {
|
||||
args.release()
|
||||
return nil, err
|
||||
}
|
||||
s := &stream{m: m, lib: lib, sym: sym, id: nextID.Add(1), ch: make(chan reply, 1)}
|
||||
pending.Store(s.id, s.ch)
|
||||
var r reply
|
||||
err = onMain(flags, func() { r = lib.invoke(m, sym, h, args.bytes(), s.id) })
|
||||
args.release()
|
||||
if err != nil {
|
||||
pending.Delete(s.id)
|
||||
return nil, err
|
||||
}
|
||||
if r.status != statusPending {
|
||||
pending.Delete(s.id)
|
||||
d, err := m.result(context.Background(), sym, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.Close()
|
||||
return nil, fmt.Errorf("native: %s did not start its stream", sym)
|
||||
}
|
||||
r.free()
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// next asks for the stream's next value; done reports its end.
|
||||
func (s *stream) next(ctx context.Context) (data []byte, err error, done bool) {
|
||||
s.lib.next(s.m, s.id)
|
||||
select {
|
||||
case r := <-s.ch:
|
||||
switch r.status {
|
||||
case statusOK:
|
||||
return r.data, nil, false
|
||||
case statusEnd:
|
||||
return nil, nil, true
|
||||
default:
|
||||
return nil, s.m.decodeError(ctx, r.data), false
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err(), false
|
||||
}
|
||||
}
|
||||
|
||||
// stop cancels the stream's task, which runs its onTermination.
|
||||
func (s *stream) stop() {
|
||||
s.lib.cancel(s.m, s.id)
|
||||
pending.Delete(s.id)
|
||||
}
|
||||
|
||||
// The notifications of callbacks run in order, on the main thread when the
|
||||
// app runs.
|
||||
var notes struct {
|
||||
mu sync.Mutex
|
||||
queue []func()
|
||||
running bool
|
||||
}
|
||||
|
||||
func notify(fn func()) {
|
||||
notes.mu.Lock()
|
||||
notes.queue = append(notes.queue, fn)
|
||||
if notes.running {
|
||||
notes.mu.Unlock()
|
||||
return
|
||||
}
|
||||
notes.running = true
|
||||
notes.mu.Unlock()
|
||||
go func() {
|
||||
for {
|
||||
notes.mu.Lock()
|
||||
if len(notes.queue) == 0 {
|
||||
notes.running = false
|
||||
notes.mu.Unlock()
|
||||
return
|
||||
}
|
||||
fn := notes.queue[0]
|
||||
notes.queue[0] = nil
|
||||
notes.queue = notes.queue[1:]
|
||||
notes.mu.Unlock()
|
||||
if mygo.App.IsReady() {
|
||||
mygo.RunOnMain(fn)
|
||||
} else {
|
||||
fn()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// asyncs are the calls of Go's methods taking a context that the platform
|
||||
// is waiting for, by its continuation. A continuation's id is unique in
|
||||
// the process: its high bits are its module's index (Module.index), which
|
||||
// Go gives each module as it loads it.
|
||||
var asyncs sync.Map // uint64 → context.CancelFunc
|
||||
|
||||
// contBits is where a continuation's module index starts.
|
||||
const contBits = 48
|
||||
|
||||
// modules are the modules loaded, by index.
|
||||
var modules sync.Map // uint64 → *Module
|
||||
|
||||
// moduleOf returns the module of a continuation, or nil.
|
||||
func moduleOf(cont uint64) *Module {
|
||||
m, ok := modules.Load(cont >> contBits)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return m.(*Module)
|
||||
}
|
||||
|
||||
// handle answers the platform; the encoder it returns, if any, holds the
|
||||
// answer of a question.
|
||||
func handle(kind, id uint64, status int64, data []byte) (int64, *Encoder, bool) {
|
||||
switch kind {
|
||||
case kindResult, kindItem:
|
||||
if ch, ok := pending.Load(id); ok {
|
||||
select {
|
||||
case ch.(chan reply) <- reply{status: status, data: data}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
case kindNotify:
|
||||
v := lookupGo(id)
|
||||
if v == nil || v.dead.Load() {
|
||||
return 0, nil, false
|
||||
}
|
||||
d := &Decoder{b: data}
|
||||
notify(func() {
|
||||
if !v.dead.Load() {
|
||||
_ = v.fn(d, nil)
|
||||
}
|
||||
})
|
||||
case kindAsk:
|
||||
v := lookupGo(id)
|
||||
if v == nil || v.dead.Load() {
|
||||
return answer(nil, ErrClosed)
|
||||
}
|
||||
e := NewEncoder()
|
||||
return answer(e, v.fn(&Decoder{b: data}, e))
|
||||
case kindRelease:
|
||||
goValues.Delete(id)
|
||||
case kindInvoke:
|
||||
v := lookupGo(id)
|
||||
if v == nil {
|
||||
return answer(nil, ErrClosed)
|
||||
}
|
||||
d := &Decoder{b: data}
|
||||
method := int(d.Int())
|
||||
e := NewEncoder()
|
||||
return answer(e, v.dispatch(context.Background(), method, d, e))
|
||||
case kindInvokeAsync:
|
||||
// status is the continuation, which waits for an answer even
|
||||
// when there is no method to call.
|
||||
cont := uint64(status)
|
||||
m := moduleOf(cont)
|
||||
v := lookupGo(id)
|
||||
if v == nil {
|
||||
if m != nil {
|
||||
go resume(m, cont, statusError, errorBlock(ErrClosed))
|
||||
}
|
||||
return 0, nil, false
|
||||
}
|
||||
d := &Decoder{b: data}
|
||||
method := int(d.Int())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
asyncs.Store(cont, cancel)
|
||||
go func() {
|
||||
defer cancel()
|
||||
e := NewEncoder()
|
||||
st, out, _ := answer(e, v.dispatch(ctx, method, d, e))
|
||||
asyncs.Delete(cont)
|
||||
resume(v.m, cont, st, out.b)
|
||||
out.release()
|
||||
}()
|
||||
case kindPresent:
|
||||
// The surface comes retained, for the texture to keep.
|
||||
if t := texture.Lookup(id); t != nil {
|
||||
t.Present(uintptr(status))
|
||||
} else {
|
||||
releaseSurface(uintptr(status))
|
||||
}
|
||||
case kindCancel:
|
||||
if c, ok := asyncs.Load(id); ok {
|
||||
c.(context.CancelFunc)()
|
||||
}
|
||||
}
|
||||
return 0, nil, false
|
||||
}
|
||||
|
||||
// resume answers the continuation cont of module m.
|
||||
func resume(m *Module, cont uint64, status int64, data []byte) {
|
||||
if lib, err := m.load(); err == nil {
|
||||
lib.resume(m, cont, status, data)
|
||||
}
|
||||
}
|
||||
|
||||
// answer is the answer of a question: what e holds, or err.
|
||||
func answer(e *Encoder, err error) (int64, *Encoder, bool) {
|
||||
if err != nil {
|
||||
if e == nil {
|
||||
e = NewEncoder()
|
||||
}
|
||||
e.b = e.b[:0]
|
||||
encodeError(e, err)
|
||||
return statusError, e, true
|
||||
}
|
||||
return statusOK, e, true
|
||||
}
|
||||
|
||||
// Flush waits until the notifications of callbacks the platform has made
|
||||
// so far have run, for tools such as mygo native call that exit next.
|
||||
func Flush() {
|
||||
for {
|
||||
notes.mu.Lock()
|
||||
idle := !notes.running && len(notes.queue) == 0
|
||||
notes.mu.Unlock()
|
||||
if idle {
|
||||
return
|
||||
}
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
Vendored
+234
@@ -0,0 +1,234 @@
|
||||
package native
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Values cross between Go and the implementation in a binary encoding,
|
||||
// in the order of the declarations, which the generated code of both
|
||||
// sides writes and reads: every integer as 8 bytes, little-endian, two's
|
||||
// complement; floats as float64; a bool as one byte; strings and []byte
|
||||
// as their length then their bytes; slices and maps as their length then
|
||||
// their elements (a map's as key, value); a pointer as a bool then the
|
||||
// value if any; a struct as its fields; an enum as its value; a time as
|
||||
// its Unix seconds and nanoseconds; a duration as nanoseconds; a buffer
|
||||
// as its address and size; a texture, an object, a window, a view or a
|
||||
// callback as its handle.
|
||||
|
||||
// Encoder writes the values of a call, for generated code.
|
||||
type Encoder struct{ b []byte }
|
||||
|
||||
var encoders = sync.Pool{New: func() any { return &Encoder{b: make([]byte, 0, 128)} }}
|
||||
|
||||
// NewEncoder returns an empty encoder, which the call it is given to
|
||||
// releases.
|
||||
func NewEncoder() *Encoder {
|
||||
e := encoders.Get().(*Encoder)
|
||||
e.b = e.b[:0]
|
||||
return e
|
||||
}
|
||||
|
||||
// release puts the encoder back for another call.
|
||||
func (e *Encoder) release() {
|
||||
if e != nil && cap(e.b) <= 64<<10 {
|
||||
encoders.Put(e)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Encoder) bytes() []byte {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.b
|
||||
}
|
||||
|
||||
func (e *Encoder) Bool(v bool) {
|
||||
var b byte
|
||||
if v {
|
||||
b = 1
|
||||
}
|
||||
e.b = append(e.b, b)
|
||||
}
|
||||
|
||||
func (e *Encoder) Int(v int64) { e.b = binary.LittleEndian.AppendUint64(e.b, uint64(v)) }
|
||||
func (e *Encoder) Uint(v uint64) { e.b = binary.LittleEndian.AppendUint64(e.b, v) }
|
||||
func (e *Encoder) Float(v float64) { e.Uint(math.Float64bits(v)) }
|
||||
|
||||
// Len writes the length of a slice or a map, whose elements follow.
|
||||
func (e *Encoder) Len(n int) { e.Int(int64(n)) }
|
||||
|
||||
func (e *Encoder) String(s string) {
|
||||
e.Len(len(s))
|
||||
e.b = append(e.b, s...)
|
||||
}
|
||||
|
||||
func (e *Encoder) Bytes(b []byte) {
|
||||
e.Len(len(b))
|
||||
e.b = append(e.b, b...)
|
||||
}
|
||||
|
||||
func (e *Encoder) Time(t time.Time) {
|
||||
e.Int(t.Unix())
|
||||
e.Int(int64(t.Nanosecond()))
|
||||
}
|
||||
|
||||
func (e *Encoder) Duration(d time.Duration) { e.Int(int64(d)) }
|
||||
|
||||
// Rect writes a ui.Rect.
|
||||
func (e *Encoder) Rect(x, y, w, h float32) {
|
||||
e.Float(float64(x))
|
||||
e.Float(float64(y))
|
||||
e.Float(float64(w))
|
||||
e.Float(float64(h))
|
||||
}
|
||||
|
||||
// Buffer writes a buffer's address and size, which the implementation
|
||||
// uses without a copy.
|
||||
func (e *Encoder) Buffer(b *Buffer) {
|
||||
if b == nil {
|
||||
e.Uint(0)
|
||||
e.Uint(0)
|
||||
return
|
||||
}
|
||||
e.Uint(uint64(b.p))
|
||||
e.Uint(uint64(b.n))
|
||||
}
|
||||
|
||||
func (e *Encoder) Texture(t *Texture) {
|
||||
if t == nil {
|
||||
e.Uint(0)
|
||||
return
|
||||
}
|
||||
e.Uint(t.ID())
|
||||
}
|
||||
|
||||
var errShort = errors.New("native: a value from the implementation ends early")
|
||||
|
||||
// Decoder reads the values the implementation returned, for generated
|
||||
// code. A value that does not decode reads as its zero, and Close and Err
|
||||
// report it.
|
||||
type Decoder struct {
|
||||
b []byte
|
||||
err error
|
||||
// block is the memory the implementation gave the values in, freed
|
||||
// with Close.
|
||||
block uintptr
|
||||
}
|
||||
|
||||
var decoders = sync.Pool{New: func() any { return new(Decoder) }}
|
||||
|
||||
func newDecoder(b []byte, block uintptr) *Decoder {
|
||||
d := decoders.Get().(*Decoder)
|
||||
d.b, d.err, d.block = b, nil, block
|
||||
return d
|
||||
}
|
||||
|
||||
// Close lets go of what the decoder read from, and reports whether every
|
||||
// value decoded.
|
||||
func (d *Decoder) Close() error {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
err := d.err
|
||||
if d.block != 0 {
|
||||
freeBlock(d.block)
|
||||
}
|
||||
d.b, d.err, d.block = nil, nil, 0
|
||||
decoders.Put(d)
|
||||
return err
|
||||
}
|
||||
|
||||
// Err reports whether a value failed to decode.
|
||||
func (d *Decoder) Err() error { return d.err }
|
||||
|
||||
func (d *Decoder) take(n int) []byte {
|
||||
if n < 0 || n > len(d.b) {
|
||||
if d.err == nil {
|
||||
d.err = errShort
|
||||
}
|
||||
d.b = nil
|
||||
return nil
|
||||
}
|
||||
v := d.b[:n:n]
|
||||
d.b = d.b[n:]
|
||||
return v
|
||||
}
|
||||
|
||||
func (d *Decoder) Bool() bool {
|
||||
b := d.take(1)
|
||||
return len(b) == 1 && b[0] != 0
|
||||
}
|
||||
|
||||
func (d *Decoder) Uint() uint64 {
|
||||
b := d.take(8)
|
||||
if len(b) < 8 {
|
||||
return 0
|
||||
}
|
||||
return binary.LittleEndian.Uint64(b)
|
||||
}
|
||||
|
||||
func (d *Decoder) Int() int64 { return int64(d.Uint()) }
|
||||
func (d *Decoder) Float() float64 { return math.Float64frombits(d.Uint()) }
|
||||
|
||||
// Len reads the length of a slice or a map. It is no more than the bytes
|
||||
// left, as every element takes one at least (a struct without fields
|
||||
// crosses as a zero byte), so that a value that does not decode makes
|
||||
// nothing large.
|
||||
func (d *Decoder) Len() int {
|
||||
n := d.Int()
|
||||
if n < 0 || n > int64(len(d.b)) {
|
||||
d.take(-1)
|
||||
return 0
|
||||
}
|
||||
return int(n)
|
||||
}
|
||||
|
||||
func (d *Decoder) String() string {
|
||||
n := d.Int()
|
||||
if n > int64(len(d.b)) {
|
||||
d.take(-1)
|
||||
return ""
|
||||
}
|
||||
return string(d.take(int(n)))
|
||||
}
|
||||
|
||||
// Bytes reads a []byte, nil when empty.
|
||||
func (d *Decoder) Bytes() []byte {
|
||||
n := d.Int()
|
||||
if n > int64(len(d.b)) {
|
||||
d.take(-1)
|
||||
return nil
|
||||
}
|
||||
b := d.take(int(n))
|
||||
if len(b) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append([]byte(nil), b...)
|
||||
}
|
||||
|
||||
// Time reads a time, in UTC.
|
||||
func (d *Decoder) Time() time.Time {
|
||||
s, ns := d.Int(), d.Int()
|
||||
return time.Unix(s, ns).UTC()
|
||||
}
|
||||
|
||||
func (d *Decoder) Duration() time.Duration { return time.Duration(d.Int()) }
|
||||
|
||||
// Buffer reads a buffer the implementation lends.
|
||||
func (d *Decoder) Buffer() *Buffer {
|
||||
p, n := d.Uint(), d.Uint()
|
||||
return &Buffer{p: uintptr(p), n: int(n)}
|
||||
}
|
||||
|
||||
// bytesOf returns the n bytes at p, memory of the platform's.
|
||||
func bytesOf(p uintptr, n int) []byte {
|
||||
if n <= 0 {
|
||||
return nil
|
||||
}
|
||||
return unsafe.Slice(bytesAt(p), n)
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
//go:build android
|
||||
|
||||
package native
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/egoist/mygo/internal/nativehost"
|
||||
)
|
||||
|
||||
// On Android a module is implemented in Kotlin, which Go calls through
|
||||
// JNI (nativehost.Kotlin, which the host's Go side sets): the generated
|
||||
// Kotlin object of the module decodes the arguments, calls the
|
||||
// implementation and encodes its answer, as a Swift library's C functions
|
||||
// do elsewhere. Kotlin tells Go what happens later through one native
|
||||
// method, which reaches handle as purego's callback does on desktops.
|
||||
|
||||
// lastModule numbers the modules as they load.
|
||||
var lastModule atomic.Uint64
|
||||
|
||||
// library is a module's Kotlin, by the name it registered under.
|
||||
type library struct{ name string }
|
||||
|
||||
func init() {
|
||||
nativehost.Handle = func(kind, id uint64, status int64, data []byte) (int64, []byte, bool) {
|
||||
st, out, ok := handle(kind, id, status, data)
|
||||
if !ok {
|
||||
return 0, nil, false
|
||||
}
|
||||
b := append([]byte(nil), out.bytes()...)
|
||||
out.release()
|
||||
return st, b, true
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Module) load() (*library, error) {
|
||||
m.once.Do(func() { m.lib, m.err = m.open() })
|
||||
return m.lib, m.err
|
||||
}
|
||||
|
||||
func (m *Module) open() (*library, error) {
|
||||
k := nativehost.Kotlin
|
||||
if !m.supported() {
|
||||
return nil, errors.ErrUnsupported
|
||||
}
|
||||
if k == nil {
|
||||
return nil, errors.New("native: the app's host has no native modules: build it with mygo build -platform android")
|
||||
}
|
||||
for _, name := range m.Deps {
|
||||
dep := registered(name)
|
||||
if dep == nil {
|
||||
return nil, fmt.Errorf("native: %s uses the native module %s, which the program does not link", m.Name, name)
|
||||
}
|
||||
if _, err := dep.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
idx := lastModule.Add(1)
|
||||
modules.Store(idx, m)
|
||||
if msg := k.Init(m.Name, m.Kotlin, idx<<contBits); msg != "" {
|
||||
modules.Delete(idx)
|
||||
return nil, fmt.Errorf("native: %s", msg)
|
||||
}
|
||||
return &library{name: m.Name}, nil
|
||||
}
|
||||
|
||||
// isMainThread reports whether this is Go's main thread, which on phones
|
||||
// is not the UI thread: main-thread methods run on the UI thread (onMain).
|
||||
func isMainThread() bool { return false }
|
||||
|
||||
// LibraryName is the name of a module's implementation on Android: its
|
||||
// Gradle library in the app.
|
||||
func LibraryName(module string) string { return module }
|
||||
|
||||
func (l *library) sym(m *Module, name string) (uintptr, error) { return 1, nil }
|
||||
|
||||
func (l *library) invoke(m *Module, name string, h uint64, args []byte, call uint64) reply {
|
||||
b := nativehost.Kotlin.Invoke(l.name, name, h, args, call)
|
||||
if len(b) < 8 {
|
||||
return reply{status: statusOK}
|
||||
}
|
||||
return reply{status: int64(binary.LittleEndian.Uint64(b)), data: b[8:]}
|
||||
}
|
||||
|
||||
// direct calls a method of numbers by its name.
|
||||
func (l *library) directSym(m *Module, name string, h uint64, args []uintptr) uintptr {
|
||||
a := make([]uint64, len(args))
|
||||
for i, v := range args {
|
||||
a[i] = uint64(v)
|
||||
}
|
||||
return uintptr(nativehost.Kotlin.Direct(l.name, name, h, a))
|
||||
}
|
||||
|
||||
func (l *library) release(m *Module, h uint64) { nativehost.Kotlin.Op(l.name, "release", h, 0, nil) }
|
||||
func (l *library) cancel(m *Module, call uint64) {
|
||||
nativehost.Kotlin.Op(l.name, "cancel", call, 0, nil)
|
||||
}
|
||||
func (l *library) next(m *Module, call uint64) { nativehost.Kotlin.Op(l.name, "next", call, 0, nil) }
|
||||
func (l *library) resume(m *Module, cont uint64, status int64, data []byte) {
|
||||
nativehost.Kotlin.Op(l.name, "resume", cont, status, data)
|
||||
}
|
||||
|
||||
// The replies of Kotlin are Go's memory.
|
||||
func freeBlock(uintptr) {}
|
||||
|
||||
func allocate(n int) uintptr {
|
||||
if k := nativehost.Kotlin; k != nil {
|
||||
return k.Malloc(max(n, 1))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func deallocate(p uintptr) {
|
||||
if k := nativehost.Kotlin; k != nil {
|
||||
k.Free(p)
|
||||
}
|
||||
}
|
||||
|
||||
// releaseSurface has no surfaces to release: Kotlin implementations take
|
||||
// no textures.
|
||||
func releaseSurface(uintptr) {}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package native
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
const (
|
||||
libcPath = "/usr/lib/libSystem.B.dylib"
|
||||
isMainSymbol = "pthread_main_np"
|
||||
)
|
||||
|
||||
func mainThread() bool {
|
||||
r, _, _ := purego.SyscallN(libc.isMain)
|
||||
return r != 0
|
||||
}
|
||||
|
||||
// olderMacOS reports whether the system, macOS or iOS, is older than
|
||||
// version, as "12" or "13.3".
|
||||
func olderMacOS(version string) bool {
|
||||
have, err := syscall.Sysctl("kern.osproductversion")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return compareVersions(have, version) < 0
|
||||
}
|
||||
|
||||
func compareVersions(a, b string) int {
|
||||
as, bs := strings.Split(a, "."), strings.Split(b, ".")
|
||||
for i := range max(len(as), len(bs)) {
|
||||
var x, y int
|
||||
if i < len(as) {
|
||||
x, _ = strconv.Atoi(as[i])
|
||||
}
|
||||
if i < len(bs) {
|
||||
y, _ = strconv.Atoi(bs[i])
|
||||
}
|
||||
if x != y {
|
||||
if x < y {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// releaseSurface lets go of a surface presented to a texture that is gone.
|
||||
func releaseSurface(s uintptr) {
|
||||
if s == 0 {
|
||||
return
|
||||
}
|
||||
cf, err := purego.Dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if release, err := purego.Dlsym(cf, "CFRelease"); err == nil {
|
||||
purego.SyscallN(release, s)
|
||||
}
|
||||
}
|
||||
Vendored
+308
@@ -0,0 +1,308 @@
|
||||
//go:build (darwin || linux || windows) && !android
|
||||
|
||||
package native
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/ffi"
|
||||
"github.com/egoist/mygo/internal/nativelib"
|
||||
)
|
||||
|
||||
// lastModule numbers the modules as they load.
|
||||
var lastModule atomic.Uint64
|
||||
|
||||
// library is the loaded implementation of a module: a native library,
|
||||
// found and loaded as package ffi finds and loads any (see ffi.Library.Path).
|
||||
type library struct {
|
||||
lib *ffi.Library
|
||||
syms sync.Map // name → uintptr
|
||||
}
|
||||
|
||||
var libc struct {
|
||||
once sync.Once
|
||||
malloc uintptr
|
||||
free uintptr
|
||||
isMain uintptr
|
||||
callback uintptr
|
||||
err error
|
||||
}
|
||||
|
||||
func loadLibc() error {
|
||||
libc.once.Do(func() {
|
||||
if libc.malloc, libc.free, libc.isMain, libc.err = openLibc(); libc.err != nil {
|
||||
return
|
||||
}
|
||||
// One callback for every module, created once: purego's
|
||||
// callbacks are never freed.
|
||||
libc.callback = purego.NewCallback(func(kind, id, status, data, n uintptr) uintptr {
|
||||
var in []byte
|
||||
if n > 0 {
|
||||
in = append([]byte(nil), unsafe.Slice(bytesAt(data), n)...)
|
||||
}
|
||||
st, out, ok := handle(uint64(kind), uint64(id), int64(status), in)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
p := newBlock(st, out.bytes())
|
||||
out.release()
|
||||
return p
|
||||
})
|
||||
})
|
||||
return libc.err
|
||||
}
|
||||
|
||||
func isMainThread() bool {
|
||||
if loadLibc() != nil {
|
||||
return false
|
||||
}
|
||||
return mainThread()
|
||||
}
|
||||
|
||||
// newBlock copies a result into memory the platform frees: its status, its
|
||||
// length, then its bytes.
|
||||
func newBlock(status int64, data []byte) uintptr {
|
||||
p, _, _ := purego.SyscallN(libc.malloc, uintptr(16+len(data)))
|
||||
if p == 0 {
|
||||
return 0
|
||||
}
|
||||
b := unsafe.Slice(bytesAt(p), 16+len(data))
|
||||
binary.LittleEndian.PutUint64(b, uint64(status))
|
||||
binary.LittleEndian.PutUint64(b[8:], uint64(len(data)))
|
||||
copy(b[16:], data)
|
||||
return p
|
||||
}
|
||||
|
||||
// readBlock reads a block the platform made, which the reply frees.
|
||||
func readBlock(p uintptr) reply {
|
||||
if p == 0 {
|
||||
return reply{}
|
||||
}
|
||||
head := unsafe.Slice(bytesAt(p), 16)
|
||||
n := binary.LittleEndian.Uint64(head[8:])
|
||||
return reply{status: int64(binary.LittleEndian.Uint64(head)), data: bytesOf(p+16, int(n)), block: p}
|
||||
}
|
||||
|
||||
func freeBlock(p uintptr) { purego.SyscallN(libc.free, p) }
|
||||
|
||||
func (m *Module) load() (*library, error) {
|
||||
m.once.Do(func() { m.lib, m.err = m.open() })
|
||||
return m.lib, m.err
|
||||
}
|
||||
|
||||
func (m *Module) open() (*library, error) {
|
||||
min := m.MinMacOS
|
||||
if runtime.GOOS == "ios" {
|
||||
min = m.MinIOS
|
||||
}
|
||||
if !m.supported() || min != "" && olderMacOS(min) {
|
||||
return nil, errors.ErrUnsupported
|
||||
}
|
||||
if err := loadLibc(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The modules it uses first, whose libraries it links to: dyld then
|
||||
// finds them loaded, by their install names, wherever they are.
|
||||
for _, name := range m.Deps {
|
||||
dep := registered(name)
|
||||
if dep == nil {
|
||||
return nil, fmt.Errorf("native: %s uses the native module %s, which the program does not link", m.Name, name)
|
||||
}
|
||||
if _, err := dep.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
fl := ffi.New(m.Name, m.published()).From(m.Dir)
|
||||
if err := m.checkFresh(fl); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fl.Load(); err != nil {
|
||||
return nil, fmt.Errorf("native: %w", err)
|
||||
}
|
||||
lib := &library{lib: fl}
|
||||
init, err := lib.sym(m, "init")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The module's index makes its continuations' ids unique.
|
||||
idx := lastModule.Add(1)
|
||||
modules.Store(idx, m)
|
||||
// The implementation allocates the blocks it gives Go, and frees those
|
||||
// Go gives it, with the C library's malloc and free, as Go does.
|
||||
purego.SyscallN(init, libc.callback, uintptr(idx<<contBits), libc.malloc, libc.free)
|
||||
return lib, nil
|
||||
}
|
||||
|
||||
// LibraryName is the file of a module's implementation on this system.
|
||||
func LibraryName(module string) string { return nativelib.FileName(module, runtime.GOOS) }
|
||||
|
||||
// published returns the manifest of a module that a dependency of the
|
||||
// program declares, in the module cache, where the files it publishes are
|
||||
// built from the sources there: go run and go test then download its
|
||||
// library, as the CLI does. A module of the program's own is built from its
|
||||
// sources instead, which may have changed since they were published.
|
||||
func (m *Module) published() []byte {
|
||||
if m.Dir == "" || mygo.App.IsPackaged() || !inModuleCache(m.Dir) {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(m.Dir, nativelib.ManifestFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if man, err := nativelib.Parse(data); err != nil {
|
||||
return nil
|
||||
} else if _, ok := man.Lookup(m.Name); !ok {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// inModuleCache reports whether dir is in Go's module cache, whose
|
||||
// directories are named module@version.
|
||||
func inModuleCache(dir string) bool {
|
||||
for _, e := range strings.Split(filepath.ToSlash(dir), "/") {
|
||||
if i := strings.LastIndex(e, "@v"); i > 0 && i+2 < len(e) && e[i+2] >= '0' && e[i+2] <= '9' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkFresh refuses a build of the implementation that mygo dev or
|
||||
// mygo native build -target host made for go test and go run, in the module's .mygo/native, once the
|
||||
// Swift sources are newer: the build would not be what they say.
|
||||
func (m *Module) checkFresh(l *ffi.Library) error {
|
||||
if m.Dir == "" || mygo.App.IsPackaged() {
|
||||
return nil
|
||||
}
|
||||
path, err := l.Path()
|
||||
if err != nil {
|
||||
return fmt.Errorf("native: the implementation of %s is not built: run mygo dev, or mygo native build -target host %s (%w)", m.Name, m.Dir, err)
|
||||
}
|
||||
if !strings.Contains(filepath.ToSlash(path), "/.mygo/native/") {
|
||||
return nil
|
||||
}
|
||||
st, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var newer time.Time
|
||||
for _, lang := range m.Langs {
|
||||
if t := newestSource(filepath.Join(m.Dir, lang)); t.After(newer) {
|
||||
newer = t
|
||||
}
|
||||
}
|
||||
if newer.After(st.ModTime()) {
|
||||
return fmt.Errorf("native: the implementation of %s is older than its sources: run mygo dev, or mygo native build -target host %s", m.Name, m.Dir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newestSource returns when a source of the implementation in dir last
|
||||
// changed: its Swift, Rust or Zig, or what builds it.
|
||||
func newestSource(dir string) time.Time {
|
||||
var t time.Time
|
||||
_ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() {
|
||||
if (strings.HasPrefix(d.Name(), ".") || d.Name() == "target" || d.Name() == "zig-out") && path != dir {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if ext := filepath.Ext(path); ext == ".swift" || ext == ".rs" || ext == ".zig" || ext == ".toml" || ext == ".zon" {
|
||||
if info, err := d.Info(); err == nil && info.ModTime().After(t) {
|
||||
t = info.ModTime()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return t
|
||||
}
|
||||
|
||||
func (l *library) sym(m *Module, name string) (uintptr, error) {
|
||||
if p, ok := l.syms.Load(name); ok {
|
||||
return p.(uintptr), nil
|
||||
}
|
||||
full := "mygo_" + m.Symbol + "_" + name
|
||||
p, err := l.lib.Symbol(full)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("native: %s has no %s: rebuild it: run mygo dev, or mygo native build -target host %s", LibraryName(m.Name), full, m.Dir)
|
||||
}
|
||||
l.syms.Store(name, p)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (l *library) invoke(m *Module, name string, h uint64, args []byte, call uint64) reply {
|
||||
fn, err := l.sym(m, name)
|
||||
if err != nil {
|
||||
return reply{status: statusError, data: errorBlock(err)}
|
||||
}
|
||||
p, _, _ := purego.SyscallN(fn, uintptr(h), bytesPointer(args), uintptr(len(args)), uintptr(call))
|
||||
runtime.KeepAlive(args)
|
||||
if p == 0 {
|
||||
return reply{status: statusOK}
|
||||
}
|
||||
return readBlock(p)
|
||||
}
|
||||
|
||||
func (l *library) simple(m *Module, name string, args ...uintptr) {
|
||||
if fn, err := l.sym(m, name); err == nil {
|
||||
purego.SyscallN(fn, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *library) release(m *Module, h uint64) { l.simple(m, "release", uintptr(h)) }
|
||||
func (l *library) cancel(m *Module, call uint64) { l.simple(m, "cancel", uintptr(call)) }
|
||||
func (l *library) next(m *Module, call uint64) { l.simple(m, "next", uintptr(call)) }
|
||||
|
||||
// resume answers a continuation with a block the platform frees.
|
||||
func (l *library) resume(m *Module, cont uint64, status int64, data []byte) {
|
||||
l.simple(m, "resume", uintptr(cont), newBlock(status, data))
|
||||
}
|
||||
|
||||
// directSym calls the C function of a method of numbers, by its name.
|
||||
func (l *library) directSym(m *Module, name string, h uint64, args []uintptr) uintptr {
|
||||
fn, err := l.sym(m, name)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return l.direct(fn, h, args)
|
||||
}
|
||||
|
||||
// direct calls fn, a method of numbers, on the object h.
|
||||
func (l *library) direct(fn uintptr, h uint64, args []uintptr) uintptr {
|
||||
// SyscallN's arguments escape, whatever their size: the fewer, the
|
||||
// less it allocates.
|
||||
a := make([]uintptr, 1+len(args))
|
||||
a[0] = uintptr(h)
|
||||
copy(a[1:], args)
|
||||
r, _, _ := purego.SyscallN(fn, a...)
|
||||
return r
|
||||
}
|
||||
|
||||
func allocate(n int) uintptr {
|
||||
if loadLibc() != nil {
|
||||
return 0
|
||||
}
|
||||
p, _, _ := purego.SyscallN(libc.malloc, uintptr(max(n, 1)))
|
||||
return p
|
||||
}
|
||||
|
||||
func deallocate(p uintptr) { purego.SyscallN(libc.free, p) }
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
//go:build (darwin || linux || windows) && !android
|
||||
|
||||
package native
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestInModuleCache(t *testing.T) {
|
||||
for dir, want := range map[string]bool{
|
||||
"/home/u/go/pkg/mod/github.com/egoist/mygo@v0.9.0/plugins/sqlite/internal/sqlitecore": true,
|
||||
`C:\Users\u\go\pkg\mod\github.com\egoist\mygo@v0.9.0-0.20261108-abcdef\plugins\sqlite`: true,
|
||||
"/home/u/src/mygo/plugins/sqlite/internal/sqlitecore": false,
|
||||
"/home/u/src/me@work/app/modules/language": false,
|
||||
"/home/u/go/pkg/mod/example.com/m@vx/language": false,
|
||||
} {
|
||||
if got := inModuleCache(dir); got != want {
|
||||
t.Errorf("inModuleCache(%q) = %v, want %v", dir, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
//go:build linux && !android
|
||||
|
||||
package native
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// Swift's main actor is the main thread, the process's first. Linux runs a
|
||||
// module's Swift under go test and go run, and its Rust or Zig anywhere.
|
||||
const (
|
||||
libcPath = "libc.so.6"
|
||||
isMainSymbol = "gettid"
|
||||
)
|
||||
|
||||
func mainThread() bool {
|
||||
r, _, _ := purego.SyscallN(libc.isMain)
|
||||
return int(r) == os.Getpid()
|
||||
}
|
||||
|
||||
// olderMacOS is false off macOS: a module's minimum is macOS's.
|
||||
func olderMacOS(string) bool { return false }
|
||||
|
||||
// releaseSurface has no surfaces to release off macOS.
|
||||
func releaseSurface(uintptr) {}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
//go:build !darwin && !linux && !windows
|
||||
|
||||
package native
|
||||
|
||||
import "errors"
|
||||
|
||||
// library is the loaded implementation of a module, which this system
|
||||
// cannot load.
|
||||
type library struct{}
|
||||
|
||||
func (m *Module) load() (*library, error) { return nil, errors.ErrUnsupported }
|
||||
|
||||
func isMainThread() bool { return false }
|
||||
|
||||
func (l *library) invoke(m *Module, name string, h uint64, args []byte, call uint64) reply {
|
||||
return reply{status: statusError, data: errorBlock(errors.ErrUnsupported)}
|
||||
}
|
||||
|
||||
func (l *library) sym(m *Module, name string) (uintptr, error) { return 0, errors.ErrUnsupported }
|
||||
|
||||
func (l *library) direct(fn uintptr, h uint64, args []uintptr) uintptr { return 0 }
|
||||
|
||||
func (l *library) directSym(m *Module, name string, h uint64, args []uintptr) uintptr { return 0 }
|
||||
|
||||
func freeBlock(uintptr) {}
|
||||
|
||||
func (l *library) release(m *Module, h uint64) {}
|
||||
func (l *library) cancel(m *Module, call uint64) {}
|
||||
func (l *library) next(m *Module, call uint64) {}
|
||||
func (l *library) resume(m *Module, cont uint64, status int64, data []byte) {}
|
||||
|
||||
// LibraryName is the file of a module's implementation on Linux.
|
||||
func LibraryName(module string) string { return "lib" + module + ".so" }
|
||||
|
||||
func allocate(n int) uintptr { return 0 }
|
||||
func deallocate(p uintptr) {}
|
||||
|
||||
func releaseSurface(uintptr) {}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
//go:build (darwin || linux) && !android
|
||||
|
||||
package native
|
||||
|
||||
import "github.com/ebitengine/purego"
|
||||
|
||||
// openLibc returns the C library's malloc and free, with which Go and the
|
||||
// implementations allocate the blocks they give each other, and the
|
||||
// function that tells the main thread.
|
||||
func openLibc() (malloc, free, isMain uintptr, err error) {
|
||||
h, err := purego.Dlopen(libcPath, purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
for name, p := range map[string]*uintptr{"malloc": &malloc, "free": &free, isMainSymbol: &isMain} {
|
||||
if *p, err = purego.Dlsym(h, name); err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
}
|
||||
return malloc, free, isMain, nil
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package native
|
||||
|
||||
import "syscall"
|
||||
|
||||
// openLibc returns the malloc and free of the Universal C Runtime, which
|
||||
// every Windows MyGo runs on has, with which Go and the implementations
|
||||
// allocate the blocks they give each other.
|
||||
func openLibc() (malloc, free, isMain uintptr, err error) {
|
||||
dll, err := syscall.LoadDLL("ucrtbase.dll")
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
m, err := dll.FindProc("malloc")
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
f, err := dll.FindProc("free")
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
return m.Addr(), f.Addr(), 0, nil
|
||||
}
|
||||
|
||||
// mainThread is false: on Windows, the methods of the main thread run once
|
||||
// the app runs, which takes them there.
|
||||
func mainThread() bool { return false }
|
||||
|
||||
// olderMacOS is false off macOS: a module's minimum is macOS's.
|
||||
func olderMacOS(string) bool { return false }
|
||||
|
||||
// releaseSurface has no surfaces to release off macOS.
|
||||
func releaseSurface(uintptr) {}
|
||||
Vendored
+637
@@ -0,0 +1,637 @@
|
||||
// Package native runs native modules: Go interfaces implemented in Swift,
|
||||
// Kotlin, Rust or Zig (see docs/native-modules.md).
|
||||
//
|
||||
// Native modules are experimental: this package, the code MyGo generates
|
||||
// and the mygo native commands may change in breaking ways in any
|
||||
// release.
|
||||
//
|
||||
// A module's package declares its interfaces, and MyGo generates the
|
||||
// rest (`mygo dev` keeps it up to date): the constructors and the values that call the implementation,
|
||||
// which use this package. An app calls a module's constructor, NewT, and
|
||||
// never this package directly, except for its types: errors made with
|
||||
// NewError, Buffer and View.
|
||||
package native
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"iter"
|
||||
"math"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/nativehost"
|
||||
)
|
||||
|
||||
// ErrClosed is returned by the methods of an object that was closed.
|
||||
var ErrClosed = errors.New("native: object closed")
|
||||
|
||||
// Error is an error an implementation returned. The errors a module
|
||||
// declares are made with NewError and compare by their code, so
|
||||
// errors.Is(err, language.ErrUndetermined) holds for the error the
|
||||
// platform threw as LanguageError.undetermined. Any other error the
|
||||
// platform throws has no code, and says what the platform said of it.
|
||||
type Error struct {
|
||||
// Code is the code of an error the module declares, else empty.
|
||||
Code string
|
||||
// Domain is the error's domain or type, as NSCocoaErrorDomain or
|
||||
// ParseError, for an error the module does not declare.
|
||||
Domain string
|
||||
// Number is the error's code in its domain.
|
||||
Number int
|
||||
// Message describes the error.
|
||||
Message string
|
||||
}
|
||||
|
||||
// NewError makes an error a module declares, which its implementations
|
||||
// throw by code: in Swift, a case of the enum <Module>Error.
|
||||
func NewError(code string) *Error { return &Error{Code: code} }
|
||||
|
||||
func (e *Error) Error() string {
|
||||
switch {
|
||||
case e.Message != "":
|
||||
return e.Message
|
||||
case e.Domain != "":
|
||||
return fmt.Sprintf("%s error %d", e.Domain, e.Number)
|
||||
}
|
||||
return e.Code
|
||||
}
|
||||
|
||||
// Is reports whether target is an error the module declares with the same
|
||||
// code.
|
||||
func (e *Error) Is(target error) bool {
|
||||
t, ok := target.(*Error)
|
||||
return ok && t.Code != "" && t.Code == e.Code
|
||||
}
|
||||
|
||||
// View is embedded by the interfaces of a module that a view of the
|
||||
// platform implements, which ui.NativeView shows in native UI.
|
||||
type View interface {
|
||||
// NativeView returns the platform's view: an NSView* on macOS. It is
|
||||
// 0 once the view is closed, which takes it out of the windows
|
||||
// showing it.
|
||||
NativeView() uintptr
|
||||
}
|
||||
|
||||
// object is what every value a module returns implements.
|
||||
type object interface {
|
||||
NativeObject() *Object
|
||||
}
|
||||
|
||||
// Module describes a module to the runtime. Generated code declares one
|
||||
// per package; its fields are not for apps.
|
||||
type Module struct {
|
||||
// Name is the Swift module's: Language.
|
||||
Name string
|
||||
// Symbol prefixes the functions the implementation exports: language.
|
||||
Symbol string
|
||||
// Dir is the directory of the package, when the binary knows it
|
||||
// (built without -trimpath), where mygo dev builds the
|
||||
// implementation for go test and go run.
|
||||
Dir string
|
||||
// Langs are the languages the module is implemented in: swift,
|
||||
// kotlin, rust, zig.
|
||||
Langs []string
|
||||
// SwiftOS are the systems its Swift runs on, from the platforms of its
|
||||
// Package.swift: macos, ios.
|
||||
SwiftOS []string
|
||||
// MinMacOS and MinIOS are the oldest macOS and iOS the Swift runs on,
|
||||
// from the platforms of its Package.swift.
|
||||
MinMacOS, MinIOS string
|
||||
// Kotlin is the class of its Kotlin's generated object, which Android
|
||||
// loads.
|
||||
Kotlin string
|
||||
// Errors are the errors the module declares.
|
||||
Errors []*Error
|
||||
// Deps are the Swift modules of the native modules whose types it
|
||||
// uses, which load before it.
|
||||
Deps []string
|
||||
|
||||
once sync.Once
|
||||
lib *library
|
||||
err error
|
||||
}
|
||||
|
||||
// supported reports whether an implementation of the module runs here:
|
||||
// on phones their own language, Swift on iOS and Kotlin on Android;
|
||||
// elsewhere Rust and Zig everywhere package ffi loads libraries, Swift on
|
||||
// macOS, and on Linux under go test and go run.
|
||||
func (m *Module) supported() bool {
|
||||
return supportedOn(runtime.GOOS, m.Langs, m.SwiftOS, mygo.App.IsPackaged())
|
||||
}
|
||||
|
||||
func supportedOn(goos string, langs, swiftOS []string, packaged bool) bool {
|
||||
if len(swiftOS) == 0 {
|
||||
swiftOS = []string{"macos"}
|
||||
}
|
||||
for _, l := range langs {
|
||||
switch goos {
|
||||
case "ios":
|
||||
if l == "swift" && slices.Contains(swiftOS, "ios") {
|
||||
return true
|
||||
}
|
||||
case "android":
|
||||
if l == "kotlin" {
|
||||
return true
|
||||
}
|
||||
default:
|
||||
switch l {
|
||||
case "rust", "zig":
|
||||
return true
|
||||
case "swift":
|
||||
if goos == "darwin" && slices.Contains(swiftOS, "macos") || goos == "linux" && !packaged {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Wrapper makes the value of an interface of the platform's around an
|
||||
// object, for other modules returning it.
|
||||
type Wrapper struct {
|
||||
Flags Flags
|
||||
Wrap func(*Object) any
|
||||
}
|
||||
|
||||
var registry struct {
|
||||
sync.Mutex
|
||||
modules map[string]*Module
|
||||
wraps map[string]map[string]Wrapper
|
||||
}
|
||||
|
||||
// Register records a module and how to wrap the values of its interfaces,
|
||||
// for the modules that use them. Generated code calls it as the package
|
||||
// initializes.
|
||||
func Register(m *Module, wraps map[string]Wrapper) {
|
||||
registry.Lock()
|
||||
defer registry.Unlock()
|
||||
if registry.modules == nil {
|
||||
registry.modules = map[string]*Module{}
|
||||
registry.wraps = map[string]map[string]Wrapper{}
|
||||
}
|
||||
registry.modules[m.Name] = m
|
||||
registry.wraps[m.Name] = wraps
|
||||
}
|
||||
|
||||
// Wrap returns the value of the interface iface of the module named module
|
||||
// around the handle h, which another module returned, or nil.
|
||||
func Wrap(h uint64, module, iface string) any {
|
||||
registry.Lock()
|
||||
m, w := registry.modules[module], registry.wraps[module][iface]
|
||||
registry.Unlock()
|
||||
if h == 0 || m == nil || w.Wrap == nil {
|
||||
return nil
|
||||
}
|
||||
return w.Wrap(m.object(h, w.Flags))
|
||||
}
|
||||
|
||||
// registered returns the module named name, as Register recorded it.
|
||||
func registered(name string) *Module {
|
||||
registry.Lock()
|
||||
defer registry.Unlock()
|
||||
return registry.modules[name]
|
||||
}
|
||||
|
||||
// Flags say how a method is called.
|
||||
type Flags int
|
||||
|
||||
const (
|
||||
// MainThread runs the method on the main thread.
|
||||
MainThread Flags = 1 << iota
|
||||
)
|
||||
|
||||
// Object is a value of the platform: what a constructor made, or a method
|
||||
// returned. Its methods are for generated code.
|
||||
type Object struct {
|
||||
m *Module
|
||||
h uint64
|
||||
closed atomic.Bool
|
||||
// funcs are the callbacks passed to the call that returned it, for a
|
||||
// subscription, released when it closes.
|
||||
funcs []uint64
|
||||
flags Flags
|
||||
}
|
||||
|
||||
// View returns the object's view, for the NativeView of the proxies of
|
||||
// views: the object itself, or 0 once closed.
|
||||
func (o *Object) View() uintptr {
|
||||
if o == nil || o.closed.Load() {
|
||||
return 0
|
||||
}
|
||||
return uintptr(o.h)
|
||||
}
|
||||
|
||||
// Handle returns the object's handle, to pass it back to the platform.
|
||||
func (o *Object) Handle() uint64 {
|
||||
if o == nil {
|
||||
return 0
|
||||
}
|
||||
return o.h
|
||||
}
|
||||
|
||||
// Module returns the module the object belongs to.
|
||||
func (o *Object) Module() *Module { return o.m }
|
||||
|
||||
// object wraps a handle the platform returned, released once the Go value
|
||||
// is unreachable unless closed before. Objects of flags MainThread are
|
||||
// released on the main thread.
|
||||
func (m *Module) object(h uint64, flags Flags) *Object {
|
||||
if h == 0 {
|
||||
return nil
|
||||
}
|
||||
o := &Object{m: m, h: h, flags: flags}
|
||||
type gone struct {
|
||||
h uint64
|
||||
flags Flags
|
||||
}
|
||||
runtime.AddCleanup(o, func(g gone) { m.release(g.h, g.flags) }, gone{h, flags})
|
||||
return o
|
||||
}
|
||||
|
||||
// release lets go of the object, on the main thread for one of the main
|
||||
// thread's.
|
||||
func (m *Module) release(h uint64, flags Flags) {
|
||||
lib, err := m.load()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if flags&MainThread != 0 {
|
||||
// Posted, never waited for: the runtime runs cleanups on one
|
||||
// goroutine. Before the app runs, it waits for it to.
|
||||
mygo.App.WhenReady(func() {
|
||||
viewGone(uintptr(h))
|
||||
if post := nativehost.PostUI; post != nil {
|
||||
post(func() { lib.release(m, h) })
|
||||
return
|
||||
}
|
||||
lib.release(m, h)
|
||||
})
|
||||
return
|
||||
}
|
||||
lib.release(m, h)
|
||||
}
|
||||
|
||||
// New makes the implementation of an entry point.
|
||||
func (m *Module) New(entry string, flags Flags) (*Object, error) {
|
||||
d, err := m.call(context.Background(), 0, "new_"+entry, flags, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := d.Uint()
|
||||
if err := d.Close(); err != nil {
|
||||
return nil, fmt.Errorf("native: %s's make%s: %w", m.Name, entry, err)
|
||||
}
|
||||
if h == 0 {
|
||||
return nil, fmt.Errorf("native: %s's make%s returned nothing", m.Name, entry)
|
||||
}
|
||||
return m.object(h, flags), nil
|
||||
}
|
||||
|
||||
// Object wraps the handle of an object the platform returned, whose
|
||||
// methods flags describe.
|
||||
func (m *Module) Object(h uint64, flags Flags) *Object { return m.object(h, flags) }
|
||||
|
||||
// Call calls a method of the object that returns at once, with the
|
||||
// arguments args, which it releases. Its result is read from the decoder,
|
||||
// which the caller closes.
|
||||
func (o *Object) Call(sym string, flags Flags, args *Encoder) (*Decoder, error) {
|
||||
if o.closed.Load() {
|
||||
args.release()
|
||||
return nil, ErrClosed
|
||||
}
|
||||
d, err := o.m.call(context.Background(), o.h, sym, flags, args)
|
||||
runtime.KeepAlive(o)
|
||||
return d, err
|
||||
}
|
||||
|
||||
// CallContext calls an asynchronous method of the object, which ctx
|
||||
// cancels.
|
||||
func (o *Object) CallContext(ctx context.Context, sym string, flags Flags, args *Encoder) (*Decoder, error) {
|
||||
if o.closed.Load() {
|
||||
args.release()
|
||||
return nil, ErrClosed
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
args.release()
|
||||
return nil, err
|
||||
}
|
||||
d, err := o.m.callAsync(ctx, o.h, sym, args)
|
||||
runtime.KeepAlive(o)
|
||||
return d, err
|
||||
}
|
||||
|
||||
// Direct calls a method whose arguments and result are numbers, as the
|
||||
// registers of a C function, without encoding them: integers as their
|
||||
// bits, floats as those of a float64 (FloatArg), bools as 0 or 1
|
||||
// (BoolArg). It returns 0 if the object is closed or the implementation
|
||||
// does not load, as such methods return no error.
|
||||
func (o *Object) Direct(sym string, args ...uintptr) uintptr {
|
||||
if o.closed.Load() {
|
||||
return 0
|
||||
}
|
||||
r := o.m.direct(o.h, sym, args)
|
||||
runtime.KeepAlive(o)
|
||||
return r
|
||||
}
|
||||
|
||||
// BoolArg is a bool as Direct passes it.
|
||||
func BoolArg(b bool) uintptr {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// FloatArg is a float as Direct passes it.
|
||||
func FloatArg(f float64) uintptr { return uintptr(math.Float64bits(f)) }
|
||||
|
||||
// FloatResult is the float a Direct call returned.
|
||||
func FloatResult(r uintptr) float64 { return math.Float64frombits(uint64(r)) }
|
||||
|
||||
// Subscribe calls a method that returns a Closer, which stops what it
|
||||
// started and releases the callbacks funcs, those the call passed.
|
||||
func (o *Object) Subscribe(sym string, flags Flags, args *Encoder, funcs ...uint64) io.Closer {
|
||||
var h uint64
|
||||
d, err := o.Call(sym, flags, args)
|
||||
if err == nil {
|
||||
h = d.Uint()
|
||||
err = d.Close()
|
||||
}
|
||||
if err != nil || h == 0 {
|
||||
// The platform kept none of them.
|
||||
Forget(funcs...)
|
||||
return nopCloser{err}
|
||||
}
|
||||
c := o.m.object(h, flags)
|
||||
c.funcs = funcs
|
||||
return c
|
||||
}
|
||||
|
||||
type nopCloser struct{ err error }
|
||||
|
||||
func (c nopCloser) Close() error { return c.err }
|
||||
|
||||
// Close closes the object: the platform's close(), then its release. Later
|
||||
// calls return ErrClosed.
|
||||
func (o *Object) Close() error {
|
||||
if o == nil || !o.closed.CompareAndSwap(false, true) {
|
||||
return ErrClosed
|
||||
}
|
||||
var err error
|
||||
if o.flags&MainThread != 0 && nativehost.OnUI != nil {
|
||||
// The windows let go of a view on Go's main thread, and the view
|
||||
// closes on the UI thread.
|
||||
if mygo.App.IsReady() {
|
||||
mygo.RunOnMain(func() { viewGone(uintptr(o.h)) })
|
||||
}
|
||||
var cerr error
|
||||
err = onMain(o.flags, func() { cerr = o.m.callNone(o.h, "close", 0) })
|
||||
if err == nil {
|
||||
err = cerr
|
||||
}
|
||||
} else if o.flags&MainThread != 0 {
|
||||
var cerr error
|
||||
err = onMain(o.flags, func() {
|
||||
viewGone(uintptr(o.h))
|
||||
cerr = o.m.callNone(o.h, "close", o.flags)
|
||||
})
|
||||
if err == nil {
|
||||
err = cerr
|
||||
}
|
||||
} else {
|
||||
err = o.m.callNone(o.h, "close", 0)
|
||||
}
|
||||
releaseFuncs(o.funcs)
|
||||
runtime.KeepAlive(o)
|
||||
return err
|
||||
}
|
||||
|
||||
// Stream calls a method that returns a stream, as an iterator that starts
|
||||
// it. prepare makes the call's arguments as the loop starts, and returns
|
||||
// the handles of the callbacks and values of Go's among them, which are
|
||||
// forgotten if the stream does not start; dec reads a value; keep are the
|
||||
// arguments that stand for memory or objects of the platform's, kept
|
||||
// reachable until the stream ends.
|
||||
func Stream[T any](ctx context.Context, o *Object, sym string, flags Flags, prepare func() (*Encoder, []uint64), dec func(*Decoder) T, keep ...any) iter.Seq2[T, error] {
|
||||
return func(yield func(T, error) bool) {
|
||||
defer runtime.KeepAlive(keep)
|
||||
var zero T
|
||||
if o.closed.Load() {
|
||||
yield(zero, ErrClosed)
|
||||
return
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
yield(zero, err)
|
||||
return
|
||||
}
|
||||
args, funcs := prepare()
|
||||
s, err := o.m.startStream(o.h, sym, flags, args)
|
||||
if err != nil {
|
||||
Forget(funcs...)
|
||||
yield(zero, err)
|
||||
return
|
||||
}
|
||||
defer s.stop()
|
||||
for {
|
||||
data, err, done := s.next(ctx)
|
||||
if done {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
yield(zero, err)
|
||||
return
|
||||
}
|
||||
d := Decoder{b: data}
|
||||
v := dec(&d)
|
||||
if d.err != nil {
|
||||
yield(zero, fmt.Errorf("native: %s: %w", sym, d.err))
|
||||
return
|
||||
}
|
||||
if !yield(v, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Seq turns a stream of values that cannot fail into an iter.Seq.
|
||||
func Seq[T any](s iter.Seq2[T, error]) iter.Seq[T] {
|
||||
return func(yield func(T) bool) {
|
||||
for v, err := range s {
|
||||
if err != nil || !yield(v) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Func registers a callback, which the platform calls with its arguments,
|
||||
// and returns its handle: fn reads them from d, and writes its result to
|
||||
// e. A notification (notify) returns nothing and runs later, in order, on
|
||||
// the main thread when the app runs, with e nil; a question runs at once on
|
||||
// the thread that asks and returns its answer.
|
||||
func Func(fn func(d *Decoder, e *Encoder) error, notify bool) uint64 {
|
||||
return registerGo(&goValue{fn: fn, notify: notify})
|
||||
}
|
||||
|
||||
// Export registers a value of an interface Go implements, which the
|
||||
// platform calls through dispatch, and returns its handle. dispatch calls
|
||||
// its method number method with the arguments in d, and writes its result
|
||||
// to e; ctx is that of a method taking one.
|
||||
func Export(m *Module, v any, dispatch func(ctx context.Context, method int, d *Decoder, e *Encoder) error) uint64 {
|
||||
if v == nil {
|
||||
return 0
|
||||
}
|
||||
return registerGo(&goValue{m: m, v: v, dispatch: dispatch})
|
||||
}
|
||||
|
||||
// goValue is a callback or an object Go implements that the platform
|
||||
// holds.
|
||||
type goValue struct {
|
||||
m *Module
|
||||
fn func(*Decoder, *Encoder) error
|
||||
notify bool
|
||||
v any
|
||||
dispatch func(ctx context.Context, method int, d *Decoder, e *Encoder) error
|
||||
dead atomic.Bool
|
||||
}
|
||||
|
||||
var (
|
||||
goValues sync.Map // uint64 → *goValue
|
||||
nextID atomic.Uint64
|
||||
)
|
||||
|
||||
func registerGo(v *goValue) uint64 {
|
||||
id := nextID.Add(1)
|
||||
goValues.Store(id, v)
|
||||
return id
|
||||
}
|
||||
|
||||
func lookupGo(id uint64) *goValue {
|
||||
v, ok := goValues.Load(id)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return v.(*goValue)
|
||||
}
|
||||
|
||||
// releaseFuncs marks callbacks dead: the platform calling them does
|
||||
// nothing. They go once the platform releases them.
|
||||
func releaseFuncs(ids []uint64) {
|
||||
for _, id := range ids {
|
||||
if v := lookupGo(id); v != nil {
|
||||
v.dead.Store(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The kinds of errors, as they cross both ways: the kind, then the code,
|
||||
// domain, number and message.
|
||||
const (
|
||||
errOther = 0 // the platform's own, of a domain
|
||||
errCode = 1 // one the module declares
|
||||
errUnsupported = 2
|
||||
errClosed = 3
|
||||
errCanceled = 4
|
||||
errGo = 5 // an error of Go's, which only says what it is
|
||||
)
|
||||
|
||||
// decodeError turns an error the platform threw into Go's.
|
||||
func (m *Module) decodeError(ctx context.Context, data []byte) error {
|
||||
d := Decoder{b: data}
|
||||
kind := d.take(1)
|
||||
code, domain, number, message := d.String(), d.String(), int(d.Int()), d.String()
|
||||
if d.err != nil {
|
||||
return fmt.Errorf("native: %s threw an error that does not decode: %x", m.Name, data)
|
||||
}
|
||||
switch kind[0] {
|
||||
case errUnsupported:
|
||||
return errors.ErrUnsupported
|
||||
case errClosed:
|
||||
return ErrClosed
|
||||
case errCanceled:
|
||||
if ctx != nil && ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return context.Canceled
|
||||
case errCode:
|
||||
for _, e := range m.Errors {
|
||||
if e.Code == code {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return &Error{Code: code, Message: message}
|
||||
case errGo:
|
||||
return &Error{Message: message}
|
||||
}
|
||||
return &Error{Domain: domain, Number: number, Message: message}
|
||||
}
|
||||
|
||||
// encodeError writes a Go error as the platform throws it.
|
||||
func encodeError(e *Encoder, err error) {
|
||||
var ne *Error
|
||||
kind, code := errGo, ""
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
|
||||
kind = errCanceled
|
||||
case errors.Is(err, errors.ErrUnsupported):
|
||||
kind = errUnsupported
|
||||
case errors.Is(err, ErrClosed):
|
||||
kind = errClosed
|
||||
case errors.As(err, &ne) && ne.Code != "":
|
||||
kind, code = errCode, ne.Code
|
||||
}
|
||||
e.b = append(e.b, byte(kind))
|
||||
e.String(code)
|
||||
e.String("")
|
||||
e.Int(0)
|
||||
e.String(err.Error())
|
||||
}
|
||||
|
||||
// errorBlock is the encoding of err.
|
||||
func errorBlock(err error) []byte {
|
||||
var e Encoder
|
||||
encodeError(&e, err)
|
||||
return e.b
|
||||
}
|
||||
|
||||
// bytesPointer returns the address of data's first byte, or 0.
|
||||
func bytesPointer(data []byte) uintptr {
|
||||
if len(data) == 0 {
|
||||
return 0
|
||||
}
|
||||
return uintptr(unsafe.Pointer(&data[0]))
|
||||
}
|
||||
|
||||
// HandleOf returns the handle of v when a module returned it, else 0: a
|
||||
// value Go made cannot stand for the platform's.
|
||||
func HandleOf(v any) uint64 {
|
||||
if n, ok := v.(object); ok && n != nil {
|
||||
return n.NativeObject().Handle()
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// WindowHandle returns the native window of w, NSWindow* on macOS, or 0.
|
||||
func WindowHandle(w *mygo.Window) uint64 {
|
||||
if w == nil {
|
||||
return 0
|
||||
}
|
||||
return uint64(w.NativeHandle())
|
||||
}
|
||||
|
||||
// Forget releases callbacks and values of Go's that a call failed to give
|
||||
// the platform.
|
||||
func Forget(ids ...uint64) {
|
||||
for _, id := range ids {
|
||||
goValues.Delete(id)
|
||||
}
|
||||
}
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
package native
|
||||
|
||||
import "github.com/egoist/mygo/internal/texture"
|
||||
|
||||
// Texture is an image on the GPU that a module's implementation draws
|
||||
// into, and that native UI shows with no copy through the CPU: it is a
|
||||
// ui.ImageSource, as a *ui.Bitmap is, so ui.Image shows it, and it can be
|
||||
// covered, clipped, scaled, rotated and faded like any image. Pass it to a
|
||||
// method of the module; in Swift it is a NativeTexture, whose present
|
||||
// shows a frame (an IOSurface, or a CVPixelBuffer backed by one) in the
|
||||
// next frame of the windows showing the texture, without the app calling
|
||||
// Invalidate.
|
||||
type Texture = texture.Texture
|
||||
|
||||
// NewTexture makes a texture, which shows nothing until the implementation
|
||||
// presents a frame.
|
||||
func NewTexture() *Texture { return texture.New() }
|
||||
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
package native
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/internal/viewhost"
|
||||
)
|
||||
|
||||
// The windows of apps that use native modules host their views, which
|
||||
// ui.NativeView shows.
|
||||
func init() { viewhost.Embed = embed }
|
||||
|
||||
// gone are what to run as a view hosted in windows closes or is released,
|
||||
// by the view, which takes it out of them. Main thread only.
|
||||
var gone = map[uintptr][]func(){}
|
||||
|
||||
func embed(s platform.Surface, view uintptr, onGone func()) platform.WebView {
|
||||
vs, ok := s.(platform.ViewSurface)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
e, err := vs.EmbedView(view)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
gone[view] = append(gone[view], onGone)
|
||||
return e
|
||||
}
|
||||
|
||||
// viewGone tells the windows hosting view that it is closed or released.
|
||||
// Main thread only.
|
||||
func viewGone(view uintptr) {
|
||||
fs := gone[view]
|
||||
delete(gone, view)
|
||||
for _, f := range fs {
|
||||
f()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user