...
Run Format

Source file test/chancap.go

Documentation: test

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

View as plain text