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.
14 const maxUintptr = 1 << (8 * unsafe.Sizeof(uintptr(0)))
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]))
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))
33 // nil pointer with zero length returns nil
34 assert(unsafe.Slice((*int)(nil), 0) == nil)
36 // nil pointer with positive length panics
37 mustPanic(func() { _ = unsafe.Slice((*int)(nil), 1) })
41 mustPanic(func() { _ = unsafe.Slice(new(byte), neg) })
44 var tooBig uint64 = math.MaxUint64
45 mustPanic(func() { _ = unsafe.Slice(new(byte), tooBig) })
47 // size overflows address space
48 mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8) })
49 mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8+1) })
51 // sliced memory overflows address space
52 last := (*byte)(unsafe.Pointer(^uintptr(0)))
53 _ = unsafe.Slice(last, 1)
54 mustPanic(func() { _ = unsafe.Slice(last, 2) })
59 s := unsafe.String(&p[0], len(p))
60 assert(s == string(p[:]))
61 assert(len(s) == len(p))
64 assert(unsafe.String(nil, 0) == "")
66 // nil pointer with positive length panics
67 mustPanic(func() { _ = unsafe.String(nil, 1) })
71 mustPanic(func() { _ = unsafe.String(new(byte), neg) })
74 var tooBig uint64 = math.MaxUint64
75 mustPanic(func() { _ = unsafe.String(new(byte), tooBig) })
77 // string memory overflows address space
78 last := (*byte)(unsafe.Pointer(^uintptr(0)))
79 _ = unsafe.String(last, 1)
80 mustPanic(func() { _ = unsafe.String(last, 2) })
86 assert(string(unsafe.Slice(unsafe.StringData(s), len(s))) == s)
91 var s = []byte("slice")
92 assert(unsafe.String(unsafe.SliceData(s), len(s)) == string(s))
96 func assert(ok bool) {
102 func mustPanic(f func()) {
104 assert(recover() != nil)