testpkg.go 10 KB

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