edge_roundtrip.mx raw

   1  // Phase 0c step 5: a pair outlives the frame that declared it.
   2  //
   3  // The declaration allocates both rings and all four handles in the ROOT arena
   4  // (section 4: the storage cannot be a frame's), so returning the two Edges from
   5  // the function that declared them leaves a working pair: the return relocation
   6  // copies the channel handles as handles and the pair word as an integer. The
   7  // child is then spawned from the caller and both directions run.
   8  //
   9  //:wasmtest skip
  10  package main
  11  
  12  import "fmt"
  13  
  14  type Req struct {
  15  	Body []byte `cap:"1024"`
  16  }
  17  
  18  func worker(ep Edge[Req, int32]) (closed chan struct{}) {
  19  	for {
  20  		select {
  21  		case <-closed:
  22  			return closed
  23  		case r := <-ep.Recv:
  24  			if len(r.Body) == 0 {
  25  				return closed
  26  			}
  27  			ep.Send <- int32(len(r.Body))
  28  		}
  29  	}
  30  }
  31  
  32  func makePair() (parent Edge[int32, Req], child Edge[Req, int32]) {
  33  	p, c := edge[int32, Req]{2}
  34  	return p, c
  35  }
  36  
  37  func main() {
  38  	select {
  39  	case <-shutdown:
  40  		return
  41  	default:
  42  	}
  43  	parent, child := makePair()
  44  	done := spawn(worker, child)
  45  	for _, n := range []int32{1, 64, 300, 1024} {
  46  		parent.Send <- Req{Body: []byte{:n}}
  47  		if got := <-parent.Recv; got != n {
  48  			panic("edge roundtrip lost a reply")
  49  		}
  50  	}
  51  	close(parent.Send)
  52  	<-done
  53  	fmt.Println("edge roundtrip ok")
  54  }
  55