main.go raw

   1  package main
   2  
   3  // Phase B Test 2: user-defined Codec round-trip.
   4  // Point implements EncodeTo/DecodeFrom (8 bytes total). The native
   5  // pipe routing uses raw memory layout (memcpy) rather than calling
   6  // EncodeTo at the chan op site — both endpoints share the same
   7  // architecture (fork inherits the binary). Codec compliance is still
   8  // validated at compile time; the methods are part of the type's
   9  // public API for non-fork transports.
  10  
  11  import "io"
  12  
  13  type Point struct {
  14  	X int32
  15  	Y int32
  16  }
  17  
  18  func (p Point) EncodeTo(w io.Writer) error {
  19  	var b [8]byte
  20  	b[0] = byte(p.X)
  21  	b[1] = byte(p.X >> 8)
  22  	b[2] = byte(p.X >> 16)
  23  	b[3] = byte(p.X >> 24)
  24  	b[4] = byte(p.Y)
  25  	b[5] = byte(p.Y >> 8)
  26  	b[6] = byte(p.Y >> 16)
  27  	b[7] = byte(p.Y >> 24)
  28  	_, err := w.Write(b[:])
  29  	return err
  30  }
  31  
  32  func (p *Point) DecodeFrom(r io.Reader) error {
  33  	var b [8]byte
  34  	_, err := io.ReadFull(r, b[:])
  35  	p.X = int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
  36  	p.Y = int32(b[4]) | int32(b[5])<<8 | int32(b[6])<<16 | int32(b[7])<<24
  37  	return err
  38  }
  39  
  40  func translate(in chan Point, out chan Point) {
  41  	for i := int32(0); i < 3; i++ {
  42  		p := <-in
  43  		out <- Point{X: p.X + 100, Y: p.Y + 200}
  44  	}
  45  }
  46  
  47  func main() {
  48  	in := make(chan Point)
  49  	out := make(chan Point)
  50  	spawn(translate, in, out)
  51  
  52  	for i := int32(0); i < 3; i++ {
  53  		in <- Point{X: i, Y: i * 2}
  54  		got := <-out
  55  		if got.X != i+100 || got.Y != i*2+200 {
  56  			println("FAIL:struct-roundtrip", i, got.X, got.Y)
  57  			return
  58  		}
  59  	}
  60  	println("PASS:struct-roundtrip")
  61  }
  62