modernc.org/gc@v1.0.1-0.20240304020402-f0dba7c97c2b/testdata/errchk/test/slicecap.go (about) 1 // run 2 3 // Copyright 2014 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package main 8 9 import "unsafe" 10 11 var ( 12 hello = "hello" 13 bytes = []byte{1, 2, 3, 4, 5} 14 ints = []int32{1, 2, 3, 4, 5} 15 16 five = 5 17 18 ok = true 19 ) 20 21 func notOK() { 22 if ok { 23 println("BUG:") 24 ok = false 25 } 26 } 27 28 func checkString(desc, s string) { 29 p1 := *(*uintptr)(unsafe.Pointer(&s)) 30 p2 := *(*uintptr)(unsafe.Pointer(&hello)) 31 if p1-p2 >= 5 { 32 notOK() 33 println("string", desc, "has invalid base") 34 } 35 } 36 37 func checkBytes(desc string, s []byte) { 38 p1 := *(*uintptr)(unsafe.Pointer(&s)) 39 p2 := *(*uintptr)(unsafe.Pointer(&bytes)) 40 if p1-p2 >= 5 { 41 println("byte slice", desc, "has invalid base") 42 } 43 } 44 45 func checkInts(desc string, s []int32) { 46 p1 := *(*uintptr)(unsafe.Pointer(&s)) 47 p2 := *(*uintptr)(unsafe.Pointer(&ints)) 48 if p1-p2 >= 5*4 { 49 println("int slice", desc, "has invalid base") 50 } 51 } 52 53 func main() { 54 { 55 x := hello 56 checkString("x", x) 57 checkString("x[5:]", x[5:]) 58 checkString("x[five:]", x[five:]) 59 checkString("x[5:five]", x[5:five]) 60 checkString("x[five:5]", x[five:5]) 61 checkString("x[five:five]", x[five:five]) 62 checkString("x[1:][2:][2:]", x[1:][2:][2:]) 63 y := x[4:] 64 checkString("y[1:]", y[1:]) 65 } 66 { 67 x := bytes 68 checkBytes("x", x) 69 checkBytes("x[5:]", x[5:]) 70 checkBytes("x[five:]", x[five:]) 71 checkBytes("x[5:five]", x[5:five]) 72 checkBytes("x[five:5]", x[five:5]) 73 checkBytes("x[five:five]", x[five:five]) 74 checkBytes("x[1:][2:][2:]", x[1:][2:][2:]) 75 y := x[4:] 76 checkBytes("y[1:]", y[1:]) 77 } 78 { 79 x := ints 80 checkInts("x", x) 81 checkInts("x[5:]", x[5:]) 82 checkInts("x[five:]", x[five:]) 83 checkInts("x[5:five]", x[5:five]) 84 checkInts("x[five:5]", x[five:5]) 85 checkInts("x[five:five]", x[five:five]) 86 checkInts("x[1:][2:][2:]", x[1:][2:][2:]) 87 y := x[4:] 88 checkInts("y[1:]", y[1:]) 89 } 90 }