slice_copy_rule.mx raw

   1  // The slice rule: a sub-slice is a fresh slice. It allocates, copies, and its
   2  // capacity is its length; a write through it does not reach the parent, and an
   3  // empty sub-slice refers to nothing. resize is the capacity-preserving form
   4  // and is not a sub-slice.
   5  //
   6  // This is the rule the cursor directive asked for: `x[n:]` is a copy, so it
   7  // cannot be used as a cursor. Read with an index or an offset, write into the
   8  // destination with push, and grow with resize.
   9  package main
  10  
  11  import "os"
  12  
  13  func tailOf() (t []byte) {
  14  	b := []byte{:3}
  15  	b[0] = 'x'
  16  	b[1] = 'y'
  17  	b[2] = 'z'
  18  	t = b[1:]
  19  	return t
  20  }
  21  
  22  func main() {
  23  	// Termination: a batch program must still be stoppable, so the entry
  24  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  25  	select {
  26  	case <-shutdown:
  27  		return
  28  	default:
  29  	}
  30  
  31  	base := []byte{:5}
  32  	base[0] = 'a'
  33  	base[1] = 'b'
  34  	base[2] = 'c'
  35  	base[3] = 'd'
  36  	base[4] = 'e'
  37  
  38  	tail := base[1:4]
  39  	if len(tail) != 3 || cap(tail) != 3 {
  40  		os.Exit(1)
  41  	}
  42  	tail[0] = 'Z'
  43  	if base[1] != 'b' {
  44  		os.Exit(2) // the write reached the parent
  45  	}
  46  
  47  	empty := base[:0]
  48  	if len(empty) != 0 || cap(empty) != 0 {
  49  		os.Exit(3)
  50  	}
  51  
  52  	whole := base[:]
  53  	if len(whole) != 5 || cap(whole) != 5 {
  54  		os.Exit(4)
  55  	}
  56  	whole[0] = 'Q'
  57  	if base[0] != 'a' {
  58  		os.Exit(5)
  59  	}
  60  
  61  	// a sub-slice of a sub-slice copies again
  62  	mid := base[1:4]
  63  	sub := mid[1:3]
  64  	sub[0] = 'W'
  65  	if mid[1] != 'c' {
  66  		os.Exit(6)
  67  	}
  68  
  69  	// a sub-slice of a returned buffer is a copy of the callee's buffer
  70  	got := tailOf()
  71  	if len(got) != 2 || got[0] != 'y' || got[1] != 'z' {
  72  		os.Exit(7)
  73  	}
  74  
  75  	// resize keeps the buffer: capacity survives and writes are shared
  76  	buf := []byte{:0:8}
  77  	buf = push(buf, 'x')
  78  	buf = push(buf, 'y')
  79  	r := resize(buf, 1)
  80  	if len(r) != 1 || cap(r) != 8 {
  81  		os.Exit(8)
  82  	}
  83  	r[0] = 'z'
  84  	if buf[0] != 'z' {
  85  		os.Exit(9) // resize copied instead of reusing
  86  	}
  87  
  88  	// slicing a slice value held in a variable, not just a name
  89  	cur := base
  90  	step := cur[2:5]
  91  	step[0] = 'R'
  92  	if base[2] != 'c' {
  93  		os.Exit(10)
  94  	}
  95  
  96  	// The success path prints instead of calling os.Exit: exit() on the wasm
  97  	// target is a wasi proc_exit, which the browser harness sees as the module
  98  	// trapping, and phase 5 compares OUTPUT - a program whose only success
  99  	// signal is an exit code cannot pass there.
 100  	println("slice copy rule ok")
 101  }
 102