]> Cypherpunks.ru repositories - gostls13.git/blob - test/unsafebuiltins.go
[dev.boringcrypto] all: merge commit 9d0819b27c (CL 314609) into dev.boringcrypto
[gostls13.git] / test / unsafebuiltins.go
1 // run
2
3 // Copyright 2021 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 (
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         // unsafe.Add
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         // unsafe.Slice
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                 // nil pointer
34                 mustPanic(func() { _ = unsafe.Slice((*int)(nil), 0) })
35
36                 // negative length
37                 var neg int = -1
38                 mustPanic(func() { _ = unsafe.Slice(new(byte), neg) })
39
40                 // length too large
41                 var tooBig uint64 = math.MaxUint64
42                 mustPanic(func() { _ = unsafe.Slice(new(byte), tooBig) })
43
44                 // size overflows address space
45                 mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8) })
46                 mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8+1) })
47         }
48 }
49
50 func assert(ok bool) {
51         if !ok {
52                 panic("FAIL")
53         }
54 }
55
56 func mustPanic(f func()) {
57         defer func() {
58                 assert(recover() != nil)
59         }()
60         f()
61 }