Source file test/chancap.go

     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  		// Test mem > maxAlloc
    46  		var n2 int64 = 1 << 59
    47  		shouldPanic("makechan: size out of range", func() { _ = make(T, int(n2)) })
    48  		// Test elem.size*cap overflow
    49  		n2 = 1<<63 - 1
    50  		shouldPanic("makechan: size out of range", func() { _ = make(T, int(n2)) })
    51  	} else {
    52  		n = 1<<31 - 1
    53  		shouldPanic("makechan: size out of range", func() { _ = make(T, n) })
    54  		shouldPanic("makechan: size out of range", func() { _ = make(T, int64(n)) })
    55  	}
    56  }
    57  
    58  func shouldPanic(str string, f func()) {
    59  	defer func() {
    60  		err := recover()
    61  		if err == nil {
    62  			panic("did not panic")
    63  		}
    64  		s := err.(error).Error()
    65  		if !strings.Contains(s, str) {
    66  			panic("got panic " + s + ", want " + str)
    67  		}
    68  	}()
    69  
    70  	f()
    71  }
    72  

View as plain text