blob: 3ac79447e635fcfcb43f819508b0f6bbf2558685 [file] [log] [blame]
Russ Cox57eb06f2012-02-16 23:51:04 -05001// run
Rob Pikea703c9a2008-07-15 19:19:50 -07002
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
Rob Pike80a97832012-02-24 11:48:19 +11007// Test UTF-8 in strings and character constants.
8
Rob Pikea703c9a2008-07-15 19:19:50 -07009package main
10
Rob Pikef9489be2011-11-08 15:43:02 -080011import "unicode/utf8"
Russ Cox36096242009-01-16 14:58:14 -080012
Rob Pikea703c9a2008-07-15 19:19:50 -070013func main() {
Russ Coxdb339592011-10-25 22:20:02 -070014 var chars [6]rune
Rob Pike4f61fc92010-09-04 10:36:13 +100015 chars[0] = 'a'
16 chars[1] = 'b'
17 chars[2] = 'c'
18 chars[3] = '\u65e5'
19 chars[4] = '\u672c'
20 chars[5] = '\u8a9e'
21 s := ""
Rob Pikea703c9a2008-07-15 19:19:50 -070022 for i := 0; i < 6; i++ {
Rob Pike4f61fc92010-09-04 10:36:13 +100023 s += string(chars[i])
Rob Pikea703c9a2008-07-15 19:19:50 -070024 }
Rob Pike4f61fc92010-09-04 10:36:13 +100025 var l = len(s)
Russ Coxdb339592011-10-25 22:20:02 -070026 for w, i, j := 0, 0, 0; i < l; i += w {
27 var r rune
Rob Pike4f61fc92010-09-04 10:36:13 +100028 r, w = utf8.DecodeRuneInString(s[i:len(s)])
Russ Coxdb339592011-10-25 22:20:02 -070029 if w == 0 {
30 panic("zero width in string")
31 }
32 if r != chars[j] {
33 panic("wrong value from string")
34 }
Rob Pike4f61fc92010-09-04 10:36:13 +100035 j++
Rob Pikea703c9a2008-07-15 19:19:50 -070036 }
37 // encoded as bytes: 'a' 'b' 'c' e6 97 a5 e6 9c ac e8 aa 9e
Rob Pike4f61fc92010-09-04 10:36:13 +100038 const L = 12
Russ Coxdb339592011-10-25 22:20:02 -070039 if L != l {
40 panic("wrong length constructing array")
41 }
Rob Pike4f61fc92010-09-04 10:36:13 +100042 a := make([]byte, L)
43 a[0] = 'a'
44 a[1] = 'b'
45 a[2] = 'c'
46 a[3] = 0xe6
47 a[4] = 0x97
48 a[5] = 0xa5
49 a[6] = 0xe6
50 a[7] = 0x9c
51 a[8] = 0xac
52 a[9] = 0xe8
53 a[10] = 0xaa
54 a[11] = 0x9e
Russ Coxdb339592011-10-25 22:20:02 -070055 for w, i, j := 0, 0, 0; i < L; i += w {
56 var r rune
Rob Pike4f61fc92010-09-04 10:36:13 +100057 r, w = utf8.DecodeRune(a[i:L])
Russ Coxdb339592011-10-25 22:20:02 -070058 if w == 0 {
59 panic("zero width in bytes")
60 }
61 if r != chars[j] {
62 panic("wrong value from bytes")
63 }
Rob Pike4f61fc92010-09-04 10:36:13 +100064 j++
Rob Pikea703c9a2008-07-15 19:19:50 -070065 }
66}