blob: b08478a13c2336625796c0afd5566712912ea065 [file] [log] [blame]
Russ Cox0b477ef2012-02-16 23:48:57 -05001// run
Russ Cox8a459172009-08-20 11:12:04 -07002
3// Copyright 2009 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
Rob Pikefc0dc042012-02-19 13:19:43 +11007// Test the cap predeclared function applied to channels.
8
Russ Cox8a459172009-08-20 11:12:04 -07009package main
10
Martin Möhrmann8a6e51a2017-08-13 20:03:02 +020011import (
12 "strings"
13 "unsafe"
14)
15
16type T chan int
17
18const ptrSize = unsafe.Sizeof((*byte)(nil))
19
Russ Cox8a459172009-08-20 11:12:04 -070020func main() {
Martin Möhrmann8a6e51a2017-08-13 20:03:02 +020021 c := make(T, 10)
Russ Cox8a459172009-08-20 11:12:04 -070022 if len(c) != 0 || cap(c) != 10 {
Rob Pike325cf8e2010-03-24 16:46:53 -070023 println("chan len/cap ", len(c), cap(c), " want 0 10")
24 panic("fail")
Russ Cox8a459172009-08-20 11:12:04 -070025 }
26
27 for i := 0; i < 3; i++ {
Rob Pike325cf8e2010-03-24 16:46:53 -070028 c <- i
Russ Cox8a459172009-08-20 11:12:04 -070029 }
30 if len(c) != 3 || cap(c) != 10 {
Rob Pike325cf8e2010-03-24 16:46:53 -070031 println("chan len/cap ", len(c), cap(c), " want 3 10")
32 panic("fail")
Russ Cox8a459172009-08-20 11:12:04 -070033 }
Rob Pike325cf8e2010-03-24 16:46:53 -070034
Martin Möhrmann8a6e51a2017-08-13 20:03:02 +020035 c = make(T)
Russ Cox8a459172009-08-20 11:12:04 -070036 if len(c) != 0 || cap(c) != 0 {
Rob Pike325cf8e2010-03-24 16:46:53 -070037 println("chan len/cap ", len(c), cap(c), " want 0 0")
38 panic("fail")
Russ Cox8a459172009-08-20 11:12:04 -070039 }
Martin Möhrmann8a6e51a2017-08-13 20:03:02 +020040
41 n := -1
42 shouldPanic("makechan: size out of range", func() { _ = make(T, n) })
43 shouldPanic("makechan: size out of range", func() { _ = make(T, int64(n)) })
44 if ptrSize == 8 {
45 n = 1 << 20
46 n <<= 20
47 shouldPanic("makechan: size out of range", func() { _ = make(T, n) })
48 n <<= 20
49 shouldPanic("makechan: size out of range", func() { _ = make(T, n) })
50 } else {
51 n = 1<<31 - 1
52 shouldPanic("makechan: size out of range", func() { _ = make(T, n) })
53 shouldPanic("makechan: size out of range", func() { _ = make(T, int64(n)) })
54 }
55}
56
57func shouldPanic(str string, f func()) {
58 defer func() {
59 err := recover()
60 if err == nil {
61 panic("did not panic")
62 }
63 s := err.(error).Error()
64 if !strings.Contains(s, str) {
65 panic("got panic " + s + ", want " + str)
66 }
67 }()
68
69 f()
Russ Cox8a459172009-08-20 11:12:04 -070070}