Source file
test/unsafebuiltins.go
1
2
3
4
5
6
7 package main
8
9 import (
10 "math"
11 "unsafe"
12 )
13
14 const maxUintptr = 1 << (8 * unsafe.Sizeof(uintptr(0)))
15
16 func main() {
17 var p [10]byte
18
19
20 {
21 p1 := unsafe.Pointer(&p[1])
22 assert(unsafe.Add(p1, 1) == unsafe.Pointer(&p[2]))
23 assert(unsafe.Add(p1, -1) == unsafe.Pointer(&p[0]))
24 }
25
26
27 {
28 s := unsafe.Slice(&p[0], len(p))
29 assert(&s[0] == &p[0])
30 assert(len(s) == len(p))
31 assert(cap(s) == len(p))
32
33
34 assert(unsafe.Slice((*int)(nil), 0) == nil)
35
36
37 mustPanic(func() { _ = unsafe.Slice((*int)(nil), 1) })
38
39
40 var neg int = -1
41 mustPanic(func() { _ = unsafe.Slice(new(byte), neg) })
42
43
44 var tooBig uint64 = math.MaxUint64
45 mustPanic(func() { _ = unsafe.Slice(new(byte), tooBig) })
46
47
48 mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8) })
49 mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8+1) })
50
51
52 last := (*byte)(unsafe.Pointer(^uintptr(0)))
53 _ = unsafe.Slice(last, 1)
54 mustPanic(func() { _ = unsafe.Slice(last, 2) })
55 }
56 }
57
58 func assert(ok bool) {
59 if !ok {
60 panic("FAIL")
61 }
62 }
63
64 func mustPanic(f func()) {
65 defer func() {
66 assert(recover() != nil)
67 }()
68 f()
69 }
70
View as plain text