github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/luastrings/utf8_test.go (about) 1 package luastrings 2 3 import ( 4 "fmt" 5 "reflect" 6 "testing" 7 ) 8 9 type Utf8Map struct { 10 r rune 11 str string 12 } 13 14 var utf8map = []Utf8Map{ 15 {0x00, "\x00"}, 16 {0x55, "\x55"}, 17 {0x7f, "\x7f"}, 18 {0x80, "\xc2\x80"}, 19 {0x7ff, "\xdf\xbf"}, 20 {0x800, "\xe0\xa0\x80"}, 21 {0xffff, "\xef\xbf\xbf"}, 22 {0x10000, "\xf0\x90\x80\x80"}, 23 {0x1fffff, "\xf7\xbf\xbf\xbf"}, 24 {0x200000, "\xf8\x88\x80\x80\x80"}, 25 {0x3ffffff, "\xfb\xbf\xbf\xbf\xbf"}, 26 {0x4000000, "\xfc\x84\x80\x80\x80\x80"}, 27 {0x7fffffff, "\xfd\xbf\xbf\xbf\xbf\xbf"}, 28 } 29 30 func TestUTF8EncodeInt32(t *testing.T) { 31 for _, tt := range utf8map { 32 t.Run(fmt.Sprintf("%x", tt.r), func(t *testing.T) { 33 var p [6]byte 34 n := UTF8EncodeInt32(p[:], tt.r) 35 if n != len(tt.str) { 36 t.Errorf("UTF8EncodeInt32() = %v, want %v", n, len(tt.str)) 37 } 38 if n > 0 { 39 if !reflect.DeepEqual(p[:n], []byte(tt.str)) { 40 t.Errorf("UTF8EncodeInt32() bytes = %v, want %v", p[:n], []byte(tt.str)) 41 42 } 43 } 44 }) 45 } 46 t.Run(fmt.Sprintf("%x", -1), func(t *testing.T) { 47 var p [6]byte 48 n := UTF8EncodeInt32(p[:], -1) 49 if n != 0 { 50 t.Errorf("UTF8EncodeInt32() = %v, want %v", n, 0) 51 } 52 }) 53 54 } 55 56 func TestDecodeRuneInString(t *testing.T) { 57 for _, tt := range utf8map { 58 t.Run(fmt.Sprintf("%x", tt.r), func(t *testing.T) { 59 gotR, gotSize := DecodeRuneInString(tt.str) 60 if gotR != tt.r { 61 t.Errorf("DecodeRuneInString() gotR = %v, want %v", gotR, tt.r) 62 } 63 if gotSize != len(tt.str) { 64 t.Errorf("DecodeRuneInString() gotSize = %v, want %v", gotSize, len(tt.str)) 65 } 66 }) 67 t.Run(fmt.Sprintf("byte missing %x", tt.r), func(t *testing.T) { 68 gotR, gotSize := DecodeRuneInString(tt.str[:len(tt.str)-1]) 69 if gotR != RuneError { 70 t.Errorf("DecodeRuneInString() gotR = %v, want %v", gotR, tt.r) 71 } 72 wantSize := 1 73 if len(tt.str) == 1 { 74 wantSize = 0 75 } 76 if gotSize != wantSize { 77 t.Errorf("DecodeRuneInString() gotSize = %v, want %v", gotSize, wantSize) 78 } 79 }) 80 t.Run(fmt.Sprintf("out of range %x", tt.r), func(t *testing.T) { 81 gotR, gotSize := DecodeRuneInString(tt.str[:len(tt.str)-1] + "\xff") 82 if gotR != RuneError { 83 t.Errorf("DecodeRuneInString() gotR = %v, want %v", gotR, tt.r) 84 } 85 if gotSize != 1 { 86 t.Errorf("DecodeRuneInString() gotSize = %v, want %v", gotSize, 1) 87 } 88 }) 89 } 90 }