1 // run 2 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 7 // Test the cap predeclared function applied to channels. 8 9 package main 10 11 import ( 12 "strings" 13 "unsafe" 14 ) 15 16 type T chan int 17 18 const ptrSize = unsafe.Sizeof((*byte)(nil)) 19 20 func main() { 21 c := make(T, 10) 22 if len(c) != 0 || cap(c) != 10 { 23 println("chan len/cap ", len(c), cap(c), " want 0 10") 24 panic("fail") 25 } 26 27 for i := 0; i < 3; i++ { 28 c <- i 29 } 30 if len(c) != 3 || cap(c) != 10 { 31 println("chan len/cap ", len(c), cap(c), " want 3 10") 32 panic("fail") 33 } 34 35 c = make(T) 36 if len(c) != 0 || cap(c) != 0 { 37 println("chan len/cap ", len(c), cap(c), " want 0 0") 38 panic("fail") 39 } 40 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 57 func 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() 70 } 71