]> Cypherpunks.ru repositories - gostls13.git/blob - test/range.go
Test evaluation of range variables.
[gostls13.git] / test / range.go
1 // $G $D/$F.go && $L $F.$A && ./$A.out
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 package main
8
9 // test range over channels
10
11 func gen(c chan int, lo, hi int) {
12         for i := lo; i <= hi; i++ {
13                 c <- i;
14         }
15         close(c);
16 }
17
18 func seq(lo, hi int) chan int {
19         c := make(chan int);
20         go gen(c, lo, hi);
21         return c;
22 }
23
24 func testchan() {
25         s := "";
26         for i := range seq('a', 'z') {
27                 s += string(i);
28         }
29         if s != "abcdefghijklmnopqrstuvwxyz" {
30                 panicln("Wanted lowercase alphabet; got", s);
31         }
32 }
33
34 // test that range over array only evaluates
35 // the expression after "range" once.
36
37 var nmake = 0;
38 func makearray() []int {
39         nmake++;
40         return []int{1,2,3,4,5};
41 }
42
43 func testarray() {
44         s := 0;
45         for _, v := range makearray() {
46                 s += v;
47         }
48         if nmake != 1 {
49                 panicln("range called makearray", nmake, "times");
50         }
51         if s != 15 {
52                 panicln("wrong sum ranging over makearray");
53         }
54 }
55
56 // test that range evaluates the index and value expressions
57 // exactly once per iteration.
58
59 var ncalls = 0
60 func getvar(p *int) *int {
61         ncalls++
62         return p
63 }
64
65 func testcalls() {
66         var i, v int
67         si := 0
68         sv := 0
69         for *getvar(&i), *getvar(&v) = range [2]int{1, 2} {
70                 si += i
71                 sv += v
72         }
73         if ncalls != 4 {
74                 panicln("wrong number of calls:", ncalls, "!= 4")
75         }
76         if si != 1 || sv != 3 {
77                 panicln("wrong sum in testcalls", si, sv)
78         }
79
80         ncalls = 0
81         for *getvar(&i), *getvar(&v) = range [0]int{} {
82                 panicln("loop ran on empty array")
83         }
84         if ncalls != 0 {
85                 panicln("wrong number of calls:", ncalls, "!= 0")
86         }
87 }
88
89 func main() {
90         testchan();
91         testarray();
92         testcalls();
93 }