net_buffers_api.mx raw

   1  /*
   2  net.Buffers is a named slice of runs, and its consuming methods consume.
   3  
   4  `type Buffers [][]byte` carries pointer-receiver methods, so Read and WriteTo
   5  see the caller's value and the consumption persists: a slice assigned through a
   6  free function's parameter would not write back. Construction is an ordinary
   7  slice literal, `net.Buffers{...}`, and the runs are reached as elements.
   8  
   9  This fixture pins the semantics: WriteTo drains the runs it wrote, and Read
  10  drains whole runs and the consumed part of a partial one, leaving the remainder
  11  in element 0.
  12  */
  13  package main
  14  
  15  import (
  16  	"bytes"
  17  	"net"
  18  )
  19  
  20  func main() {
  21  	// Termination: a batch program must still be stoppable, so the entry
  22  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  23  	select {
  24  	case <-shutdown:
  25  		return
  26  	default:
  27  	}
  28  
  29  	b := net.Buffers{[]byte("ab"), []byte("cd"), []byte("ef")}
  30  	var buf bytes.Buffer
  31  	n, err := b.WriteTo(&buf)
  32  	if err != nil {
  33  		panic("writeto")
  34  	}
  35  	if n != 6 {
  36  		panic("writeto n")
  37  	}
  38  	if buf.String() != "abcdef" {
  39  		panic("out: " | buf.String())
  40  	}
  41  	if len(b) != 0 {
  42  		panic("writeto does not consume")
  43  	}
  44  	c := net.Buffers{[]byte("ab"), []byte("cd")}
  45  	p := []byte{:3}
  46  	rn, rerr := c.Read(p)
  47  	if rerr != nil {
  48  		panic("read err")
  49  	}
  50  	if rn != 3 {
  51  		panic("read n")
  52  	}
  53  	if string(p) != "abc" {
  54  		panic("read: " | string(p))
  55  	}
  56  	if len(c) != 1 || string(c[0]) != "d" {
  57  		panic("remainder")
  58  	}
  59  	println("buffers ok")
  60  }
  61