blob: f8b3150c3eafa119e65c2c518f68333c109b1048 [file] [log] [blame]
Martin Möhrmann0dae9dfb2016-08-26 15:00:46 +02001// run
2
3// Copyright 2016 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// Ensure that range loops over a string have the requisite side-effects.
8
9package main
10
11import (
12 "fmt"
13 "os"
14)
15
16func check(n int) {
17 var i int
18 var r rune
19
20 b := make([]byte, n)
21 for i = range b {
22 b[i] = byte(i + 1)
23 }
24 s := string(b)
25
26 // When n == 0, i is untouched by the range loop.
27 // Picking an initial value of -1 for i makes the
28 // "want" calculation below correct in all cases.
29 i = -1
30 for i = range s {
31 b[i] = s[i]
32 }
33 if want := n - 1; i != want {
34 fmt.Printf("index after range with side-effect = %d want %d\n", i, want)
35 os.Exit(1)
36 }
37
38 i = -1
39 r = '\x00'
40 for i, r = range s {
41 b[i] = byte(r)
42 }
43 if want := n - 1; i != want {
44 fmt.Printf("index after range with side-effect = %d want %d\n", i, want)
45 os.Exit(1)
46 }
47 if want := rune(n); r != want {
48 fmt.Printf("rune after range with side-effect = %q want %q\n", r, want)
49 os.Exit(1)
50 }
51
52 i = -1
53 // i is shadowed here, so its value should be unchanged.
54 for i := range s {
55 b[i] = s[i]
56 }
57 if want := -1; i != want {
58 fmt.Printf("index after range without side-effect = %d want %d\n", i, want)
59 os.Exit(1)
60 }
61
62 i = -1
63 r = -1
64 // i and r are shadowed here, so their values should be unchanged.
65 for i, r := range s {
66 b[i] = byte(r)
67 }
68 if want := -1; i != want {
69 fmt.Printf("index after range without side-effect = %d want %d\n", i, want)
70 os.Exit(1)
71 }
72 if want := rune(-1); r != want {
73 fmt.Printf("rune after range without side-effect = %q want %q\n", r, want)
74 os.Exit(1)
75 }
76}
77
78func main() {
79 check(0)
80 check(1)
81 check(15)
82}