github.com/F4RD1N/gomobile@v1.0.1/bind/testdata/testpkg/testpkg.go (about)

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package testpkg contains bound functions for testing the cgo-JNI interface.
     6  // This is used in tests of github.com/F4RD1N/gomobile/bind/java.
     7  package testpkg
     8  
     9  //go:generate gobind -lang=go -outdir=go_testpkg .
    10  //go:generate gobind -lang=java -outdir=. .
    11  import (
    12  	"context"
    13  	"errors"
    14  	"fmt"
    15  	"io/ioutil"
    16  	"log"
    17  	"math"
    18  	"os"
    19  	"runtime"
    20  	"syscall"
    21  	"time"
    22  
    23  	"github.com/F4RD1N/gomobile/asset"
    24  
    25  	"github.com/F4RD1N/gomobile/bind/testdata/testpkg/secondpkg"
    26  	"github.com/F4RD1N/gomobile/bind/testdata/testpkg/simplepkg"
    27  	"github.com/F4RD1N/gomobile/bind/testdata/testpkg/unboundpkg"
    28  )
    29  
    30  const (
    31  	AString = "a string"
    32  	AnInt   = 7
    33  	ABool   = true
    34  	AFloat  = 0.12345
    35  
    36  	MinInt32               int32   = math.MinInt32
    37  	MaxInt32               int32   = math.MaxInt32
    38  	MinInt64                       = math.MinInt64
    39  	MaxInt64                       = math.MaxInt64
    40  	SmallestNonzeroFloat64         = math.SmallestNonzeroFloat64
    41  	MaxFloat64                     = math.MaxFloat64
    42  	SmallestNonzeroFloat32 float32 = math.SmallestNonzeroFloat64
    43  	MaxFloat32             float32 = math.MaxFloat32
    44  	Log2E                          = math.Log2E
    45  )
    46  
    47  var (
    48  	StringVar     = "a string var"
    49  	IntVar        = 77
    50  	StructVar     = &S{name: "a struct var"}
    51  	InterfaceVar  I
    52  	InterfaceVar2 I2
    53  	NodeVar       = &Node{V: "a struct var"}
    54  )
    55  
    56  type Nummer interface {
    57  	Num()
    58  }
    59  
    60  type I interface {
    61  	F()
    62  
    63  	E() error
    64  	V() int
    65  	VE() (int, error)
    66  	I() I
    67  	S() *S
    68  	StoString(seq *S) string
    69  
    70  	String() string
    71  }
    72  
    73  func CallF(i I) {
    74  	i.F()
    75  }
    76  
    77  func CallE(i I) error {
    78  	return i.E()
    79  }
    80  
    81  func CallV(i I) int {
    82  	return i.V()
    83  }
    84  
    85  func CallVE(i I) (int, error) {
    86  	return i.VE()
    87  }
    88  
    89  func CallI(i I) I {
    90  	return i
    91  }
    92  
    93  func CallS(i I) *S {
    94  	return &S{}
    95  }
    96  
    97  var keep []I
    98  
    99  func Keep(i I) {
   100  	keep = append(keep, i)
   101  }
   102  
   103  var numSCollected int
   104  
   105  type S struct {
   106  	// *S already has a finalizer, so we need another object
   107  	// to count successful collections.
   108  	innerObj *int
   109  
   110  	name string
   111  }
   112  
   113  func (s *S) F() {
   114  	fmt.Printf("called F on *S{%s}\n", s.name)
   115  }
   116  
   117  func (s *S) String() string {
   118  	return s.name
   119  }
   120  
   121  func finalizeInner(a *int) {
   122  	numSCollected++
   123  }
   124  
   125  var seq = 0
   126  
   127  func New() *S {
   128  	s := &S{innerObj: new(int), name: fmt.Sprintf("new%d", seq)}
   129  	runtime.SetFinalizer(s.innerObj, finalizeInner)
   130  	return s
   131  }
   132  
   133  func GC() {
   134  	runtime.GC()
   135  	time.Sleep(10 * time.Millisecond)
   136  	runtime.GC()
   137  }
   138  
   139  func Add(x, y int) int {
   140  	return x + y
   141  }
   142  
   143  func NumSCollected() int {
   144  	return numSCollected
   145  }
   146  
   147  func I2Dup(i I2) I2 {
   148  	return i
   149  }
   150  
   151  func IDup(i I) I {
   152  	return i
   153  }
   154  
   155  func StrDup(s string) string {
   156  	return s
   157  }
   158  
   159  func Negate(x bool) bool {
   160  	return !x
   161  }
   162  
   163  func Err(s string) error {
   164  	if s != "" {
   165  		return errors.New(s)
   166  	}
   167  	return nil
   168  }
   169  
   170  func BytesAppend(a []byte, b []byte) []byte {
   171  	return append(a, b...)
   172  }
   173  
   174  func AppendToString(str string, someBytes []byte) []byte {
   175  	a := []byte(str)
   176  	fmt.Printf("str=%q (len=%d), someBytes=%v (len=%d)\n", str, len(str), someBytes, len(someBytes))
   177  	return append(a, someBytes...)
   178  }
   179  
   180  func UnnamedParams(_, _ int, p0 string) int {
   181  	return len(p0)
   182  }
   183  
   184  type Node struct {
   185  	V    string
   186  	Next *Node
   187  	Err  error
   188  }
   189  
   190  func NewNode(name string) *Node {
   191  	return &Node{V: name}
   192  }
   193  
   194  func (a *Node) String() string {
   195  	if a == nil {
   196  		return "<end>"
   197  	}
   198  	return a.V + ":" + a.Next.String()
   199  }
   200  
   201  type Receiver interface {
   202  	Hello(message string)
   203  }
   204  
   205  func Hello(r Receiver, name string) {
   206  	r.Hello(fmt.Sprintf("Hello, %s!\n", name))
   207  }
   208  
   209  func GarbageCollect() {
   210  	runtime.GC()
   211  }
   212  
   213  type (
   214  	Concrete struct{}
   215  
   216  	Interface interface {
   217  		F()
   218  	}
   219  )
   220  
   221  func (_ *Concrete) F() {
   222  }
   223  
   224  func NewConcrete() *Concrete {
   225  	return new(Concrete)
   226  }
   227  
   228  func ReadAsset() string {
   229  	rc, err := asset.Open("hello.txt")
   230  	if err != nil {
   231  		log.Fatal(err)
   232  	}
   233  	defer rc.Close()
   234  
   235  	b, err := ioutil.ReadAll(rc)
   236  	if err != nil {
   237  		log.Fatal(err)
   238  	}
   239  	return string(b)
   240  }
   241  
   242  type GoCallback interface {
   243  	VarUpdate()
   244  }
   245  
   246  func CallWithCallback(gcb GoCallback) {
   247  	for i := 0; i < 1000; i++ {
   248  		gcb.VarUpdate()
   249  	}
   250  }
   251  
   252  type NullTest interface {
   253  	Null() NullTest
   254  }
   255  
   256  func NewNullInterface() I {
   257  	return nil
   258  }
   259  
   260  func NewNullStruct() *S {
   261  	return nil
   262  }
   263  
   264  func CallWithNull(_null NullTest, nuller NullTest) bool {
   265  	return _null == nil && nuller.Null() == nil
   266  }
   267  
   268  type Issue20330 struct{}
   269  
   270  func NewIssue20330() *Issue20330 {
   271  	return new(Issue20330)
   272  }
   273  
   274  func (i *Issue20330) CallWithNull(_null *Issue20330) bool {
   275  	return _null == nil
   276  }
   277  
   278  type Issue14168 interface {
   279  	F(seq int32)
   280  }
   281  
   282  func ReadIntoByteArray(s []byte) (int, error) {
   283  	if len(s) != cap(s) {
   284  		return 0, fmt.Errorf("cap %d != len %d", cap(s), len(s))
   285  	}
   286  	for i := 0; i < len(s); i++ {
   287  		s[i] = byte(i)
   288  	}
   289  	return len(s), nil
   290  }
   291  
   292  type B interface {
   293  	B(b []byte)
   294  }
   295  
   296  func PassByteArray(b B) {
   297  	b.B([]byte{1, 2, 3, 4})
   298  }
   299  
   300  func GoroutineCallback(r Receiver) {
   301  	done := make(chan struct{})
   302  	go func() {
   303  		// Run it multiple times to increase the chance that the goroutine
   304  		// will use different threads for the call. Use a long argument string to
   305  		// make sure the JNI calls take more time.
   306  		for i := 0; i < 100000; i++ {
   307  			r.Hello("HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello")
   308  		}
   309  		close(done)
   310  	}()
   311  	<-done
   312  }
   313  
   314  func Hi() {
   315  	fmt.Println("Hi")
   316  }
   317  
   318  func Int(x int32) {
   319  	fmt.Println("Received int32", x)
   320  }
   321  
   322  type I2 interface {
   323  	Times(v int32) int64
   324  	Error(triggerError bool) error
   325  
   326  	StringError(s string) (string, error)
   327  }
   328  
   329  type myI2 struct{}
   330  
   331  func (_ *myI2) Times(v int32) int64 {
   332  	return int64(v) * 10
   333  }
   334  
   335  func (_ *myI2) Error(e bool) error {
   336  	if e {
   337  		return errors.New("some error")
   338  	}
   339  	return nil
   340  }
   341  
   342  func (_ *myI2) StringError(s string) (string, error) {
   343  	return s, nil
   344  }
   345  
   346  func CallIError(i I2, triggerError bool) error {
   347  	return i.Error(triggerError)
   348  }
   349  
   350  func CallIStringError(i I2, s string) (string, error) {
   351  	return i.StringError(s)
   352  }
   353  
   354  func NewI() I2 {
   355  	return &myI2{}
   356  }
   357  
   358  var pinnedI = make(map[int32]I2)
   359  
   360  func RegisterI(idx int32, i I2) {
   361  	pinnedI[idx] = i
   362  }
   363  
   364  func UnregisterI(idx int32) {
   365  	delete(pinnedI, idx)
   366  }
   367  
   368  func Multiply(idx int32, val int32) int64 {
   369  	i, ok := pinnedI[idx]
   370  	if !ok {
   371  		panic(fmt.Sprintf("unknown I2 with index %d", idx))
   372  	}
   373  	return i.Times(val)
   374  }
   375  
   376  func AppendHello(s string) string {
   377  	return fmt.Sprintf("Hello, %s!", s)
   378  }
   379  
   380  func ReturnsError(b bool) (string, error) {
   381  	if b {
   382  		return "", errors.New("Error")
   383  	}
   384  	return "OK", nil
   385  }
   386  
   387  var collectS2 = make(chan struct{}, 100)
   388  
   389  func finalizeS(a *S2) {
   390  	collectS2 <- struct{}{}
   391  }
   392  
   393  func CollectS2(want, timeoutSec int) int {
   394  	runtime.GC()
   395  
   396  	tick := time.NewTicker(time.Duration(timeoutSec) * time.Second)
   397  	defer tick.Stop()
   398  
   399  	for i := 0; i < want; i++ {
   400  		select {
   401  		case <-collectS2:
   402  		case <-tick.C:
   403  			fmt.Println("CollectS: timed out")
   404  			return i
   405  		}
   406  	}
   407  	return want
   408  }
   409  
   410  type S2 struct {
   411  	X, Y       float64
   412  	unexported bool
   413  }
   414  
   415  func NewS2(x, y float64) *S2 {
   416  	s := &S2{X: x, Y: y}
   417  	runtime.SetFinalizer(s, finalizeS)
   418  	return s
   419  }
   420  
   421  func (_ *S2) TryTwoStrings(first, second string) string {
   422  	return first + second
   423  }
   424  
   425  func (s *S2) Sum() float64 {
   426  	return s.X + s.Y
   427  }
   428  
   429  func CallSSum(s *S2) float64 {
   430  	return s.Sum()
   431  }
   432  
   433  // Issue #13033
   434  type NullFieldStruct struct {
   435  	F *S
   436  }
   437  
   438  func NewNullFieldStruct() *NullFieldStruct {
   439  	return &NullFieldStruct{}
   440  }
   441  
   442  var (
   443  	ImportedVarI secondpkg.I  = NewImportedI()
   444  	ImportedVarS *secondpkg.S = NewImportedS()
   445  )
   446  
   447  type (
   448  	ImportedFields struct {
   449  		I secondpkg.I
   450  		S *secondpkg.S
   451  	}
   452  
   453  	ImportedI interface {
   454  		F(_ secondpkg.I)
   455  	}
   456  
   457  	AnSer struct{}
   458  )
   459  
   460  func (_ *AnSer) S(_ *secondpkg.S) {
   461  }
   462  
   463  func NewImportedFields() *ImportedFields {
   464  	return &ImportedFields{
   465  		I: NewImportedI(),
   466  		S: NewImportedS(),
   467  	}
   468  }
   469  
   470  func NewImportedI() secondpkg.I {
   471  	return NewImportedS()
   472  }
   473  
   474  func NewImportedS() *secondpkg.S {
   475  	return new(secondpkg.S)
   476  }
   477  
   478  func WithImportedI(i secondpkg.I) secondpkg.I {
   479  	return i
   480  }
   481  
   482  func WithImportedS(s *secondpkg.S) *secondpkg.S {
   483  	return s
   484  }
   485  
   486  func CallImportedI(i secondpkg.I) {
   487  	i.F(0)
   488  }
   489  
   490  func NewSer() *AnSer {
   491  	return nil
   492  }
   493  
   494  func NewSimpleS() *simplepkg.S {
   495  	return nil
   496  }
   497  
   498  func UnboundS(_ *unboundpkg.S) {
   499  }
   500  
   501  func UnboundI(_ unboundpkg.I) {
   502  }
   503  
   504  type (
   505  	InterfaceDupper interface {
   506  		IDup(i Interface) Interface
   507  	}
   508  
   509  	ConcreteDupper interface {
   510  		CDup(c *Concrete) *Concrete
   511  	}
   512  )
   513  
   514  func CallIDupper(d InterfaceDupper) bool {
   515  	var want Interface = new(Concrete)
   516  	got := d.IDup(want)
   517  	return got == want
   518  }
   519  
   520  func CallCDupper(d ConcreteDupper) bool {
   521  	want := new(Concrete)
   522  	got := d.CDup(want)
   523  	return got == want
   524  }
   525  
   526  type EmptyErrorer interface {
   527  	EmptyError() error
   528  }
   529  
   530  func EmptyError() error {
   531  	return errors.New("")
   532  }
   533  
   534  func CallEmptyError(c EmptyErrorer) error {
   535  	return c.EmptyError()
   536  }
   537  
   538  func Init() {}
   539  
   540  type InitCaller struct{}
   541  
   542  func NewInitCaller() *InitCaller {
   543  	return new(InitCaller)
   544  }
   545  
   546  func (ic *InitCaller) Init() {}
   547  
   548  type Issue17073 interface {
   549  	OnError(err error)
   550  }
   551  
   552  func ErrorMessage(err error) string {
   553  	return err.Error()
   554  }
   555  
   556  var GlobalErr error = errors.New("global err")
   557  
   558  func IsGlobalErr(err error) bool {
   559  	return GlobalErr == err
   560  }
   561  
   562  type S3 struct {
   563  }
   564  
   565  type S4 struct {
   566  	I int
   567  }
   568  
   569  func NewS4WithInt(i int) *S4 {
   570  	return &S4{i}
   571  }
   572  
   573  func NewS4WithFloat(f float64) *S4 {
   574  	return &S4{int(f)}
   575  }
   576  
   577  func NewS4WithBoolAndError(b bool) (*S4, error) {
   578  	if b {
   579  		return nil, errors.New("some error")
   580  	}
   581  	return new(S4), nil
   582  }
   583  
   584  // Lifted from TestEPIPE in package os.
   585  func TestSIGPIPE() {
   586  	r, w, err := os.Pipe()
   587  	if err != nil {
   588  		panic(err)
   589  	}
   590  	if err := r.Close(); err != nil {
   591  		panic(err)
   592  	}
   593  
   594  	_, err = w.Write([]byte("hi"))
   595  	if err == nil {
   596  		panic("unexpected success of Write to broken pipe")
   597  	}
   598  	if pe, ok := err.(*os.PathError); ok {
   599  		err = pe.Err
   600  	}
   601  	if se, ok := err.(*os.SyscallError); ok {
   602  		err = se.Err
   603  	}
   604  	if err != syscall.EPIPE {
   605  		panic(fmt.Errorf("got %v, expected EPIPE", err))
   606  	}
   607  }
   608  
   609  // Testpkg is an empty interface with the same name as its package.
   610  type Testpkg interface{}
   611  
   612  func ClashingParameterFromOtherPackage(_ *secondpkg.Secondpkg) {}
   613  
   614  type MyStruct struct {
   615  }
   616  
   617  // Test that constructors with incompatible signatures are ignored.
   618  func NewMyStruct(ctx context.Context) *MyStruct {
   619  	return nil
   620  }
   621  
   622  type Int32Constructed struct{}
   623  
   624  // Test that constuctors that clash with the internal proxy constructor
   625  // are skipped.
   626  func NewInt32Constructed(i int32) *Int32Constructed {
   627  	return nil
   628  }