Home | History | Annotate | Download | only in 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 range over strings.
      8 
      9 package main
     10 
     11 import (
     12 	"fmt"
     13 	"os"
     14 	"unicode/utf8"
     15 )
     16 
     17 func main() {
     18 	s := "\000\123\x00\xca\xFE\u0123\ubabe\U0000babe\U0010FFFFx"
     19 	expect := []rune{0, 0123, 0, 0xFFFD, 0xFFFD, 0x123, 0xbabe, 0xbabe, 0x10FFFF, 'x'}
     20 	offset := 0
     21 	var i int
     22 	var c rune
     23 	ok := true
     24 	cnum := 0
     25 	for i, c = range s {
     26 		r, size := utf8.DecodeRuneInString(s[i:len(s)]) // check it another way
     27 		if i != offset {
     28 			fmt.Printf("unexpected offset %d not %d\n", i, offset)
     29 			ok = false
     30 		}
     31 		if r != expect[cnum] {
     32 			fmt.Printf("unexpected rune %d from DecodeRuneInString: %x not %x\n", i, r, expect[cnum])
     33 			ok = false
     34 		}
     35 		if c != expect[cnum] {
     36 			fmt.Printf("unexpected rune %d from range: %x not %x\n", i, r, expect[cnum])
     37 			ok = false
     38 		}
     39 		offset += size
     40 		cnum++
     41 	}
     42 	if i != len(s)-1 {
     43 		fmt.Println("after loop i is", i, "not", len(s)-1)
     44 		ok = false
     45 	}
     46 
     47 	i = 12345
     48 	c = 23456
     49 	for i, c = range "" {
     50 	}
     51 	if i != 12345 {
     52 		fmt.Println("range empty string assigned to index:", i)
     53 		ok = false
     54 	}
     55 	if c != 23456 {
     56 		fmt.Println("range empty string assigned to value:", c)
     57 		ok = false
     58 	}
     59 
     60 	for _, c := range "a\xed\xa0\x80a" {
     61 		if c != 'a' && c != utf8.RuneError {
     62 			fmt.Printf("surrogate UTF-8 does not error: %U\n", c)
     63 			ok = false
     64 		}
     65 	}
     66 
     67 	if !ok {
     68 		fmt.Println("BUG: stringrange")
     69 		os.Exit(1)
     70 	}
     71 }
     72