| 1 |
// run |
| 2 |
|
| 3 |
// Copyright 2023 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 |
"strings" |
| 11 |
"unsafe" |
| 12 |
) |
| 13 |
|
| 14 |
func shift[T any]() int64 { |
| 15 |
return 1 << unsafe.Sizeof(*new(T)) |
| 16 |
} |
| 17 |
|
| 18 |
func div[T any]() uintptr { |
| 19 |
return 1 / unsafe.Sizeof(*new(T)) |
| 20 |
} |
| 21 |
|
| 22 |
func add[T any]() int64 { |
| 23 |
return 1<<63 - 1 + int64(unsafe.Sizeof(*new(T))) |
| 24 |
} |
| 25 |
|
| 26 |
func main() { |
| 27 |
shift[[62]byte]() |
| 28 |
shift[[63]byte]() |
| 29 |
shift[[64]byte]() |
| 30 |
shift[[100]byte]() |
| 31 |
shift[[1e6]byte]() |
| 32 |
|
| 33 |
add[[1]byte]() |
| 34 |
shouldPanic("divide by zero", func() { div[[0]byte]() }) |
| 35 |
} |
| 36 |
|
| 37 |
func shouldPanic(str string, f func()) { |
| 38 |
defer func() { |
| 39 |
err := recover() |
| 40 |
if err == nil { |
| 41 |
panic("did not panic") |
| 42 |
} |
| 43 |
s := err.(error).Error() |
| 44 |
if !strings.Contains(s, str) { |
| 45 |
panic("got panic " + s + ", want " + str) |
| 46 |
} |
| 47 |
}() |
| 48 |
|
| 49 |
f() |
| 50 |
} |