1 // `clear` on a slice or a map, in both compilers.
2 //
3 // stage4's builtin emitter had no `clear` arm at all, so every clear compiled
4 // to nothing. math/big's basicMul opens with `clear(z[0:len(x)+len(y)])` and
5 // then accumulates (`addMulVVWW`) into z, so a reused receiver kept the digits
6 // of its previous product: big.Int.Exp(10, 20) answered 10^20+10^5, and a
7 // 300-digit Text(10) walked a stale divisor and died with SIGFPE. Legacy has
8 // always cleared through an inline memset.
9 package main
10 11 import "fmt"
12 13 func main() {
14 a := []uint32{1, 2, 3, 4, 5}
15 clear(a)
16 if a[0] != 0 || a[1] != 0 || a[2] != 0 || a[3] != 0 || a[4] != 0 {
17 panic("clear on a slice")
18 }
19 // Through a view the length is the view's length, not the parent's.
20 b := []uint32{1, 2, 3, 4, 5}
21 clear(b[1:3])
22 if b[0] != 1 || b[1] != 0 || b[2] != 0 || b[3] != 4 || b[4] != 5 {
23 panic("clear on a subslice")
24 }
25 c := []uint32{1, 2, 3, 4, 5}
26 clear(c[2:])
27 if c[0] != 1 || c[1] != 2 || c[2] != 0 || c[4] != 0 {
28 panic("clear on a suffix")
29 }
30 d := []uint32{1, 2, 3, 4, 5}
31 clear(d[:2])
32 if d[0] != 0 || d[1] != 0 || d[2] != 3 {
33 panic("clear on a prefix")
34 }
35 // Multi-byte elements: the byte count is len*sizeof(elem). Clearing len
36 // elements instead would leave half of each word behind.
37 e := []uint64{0x1122334455667788, 0x99aabbccddeeff00}
38 clear(e)
39 if e[0] != 0 || e[1] != 0 {
40 panic("clear on uint64 elements")
41 }
42 // A nil slice is a no-op, not a fault.
43 var ns []int32
44 clear(ns)
45 m := map[string]int32{}
46 m["a"] = 1
47 m["b"] = 2
48 clear(m)
49 if len(m) != 0 {
50 panic("clear on a map")
51 }
52 var nm map[string]int32
53 clear(nm)
54 fmt.Println("ok")
55 }
56