Skip to content

Commit

Permalink
improve:GetCharsetDesc (pingcap#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
hhu-cc authored and kennytm committed Apr 12, 2019
1 parent 6a2dce8 commit a73b469
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 9 deletions.
21 changes: 12 additions & 9 deletions charset/charset.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,17 +119,20 @@ func GetCharsetInfo(cs string) (string, string, error) {

// GetCharsetDesc gets charset descriptions in the local charsets.
func GetCharsetDesc(cs string) (*Desc, error) {
c, ok := charsets[strings.ToLower(cs)]
if !ok {
switch strings.ToLower(cs) {
case CharsetUTF8:
return descs[0], nil
case CharsetUTF8MB4:
return descs[1], nil
case CharsetASCII:
return descs[2], nil
case CharsetLatin1:
return descs[3], nil
case CharsetBin:
return descs[4], nil
default:
return nil, errors.Errorf("Unknown charset %s", cs)
}
desc := &Desc{
Name: c.Name,
DefaultCollation: c.DefaultCollation,
Desc: c.Desc,
Maxlen: c.Maxlen,
}
return desc, nil
}

// GetCharsetInfoByID returns charset and collation for id as cs_number.
Expand Down
38 changes: 38 additions & 0 deletions charset/charset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package charset

import (
"math/rand"
"testing"

. "github.com/pingcap/check"
Expand Down Expand Up @@ -98,3 +99,40 @@ func (s *testCharsetSuite) TestGetDefaultCollation(c *C) {
testGetDefaultCollation(c, tt.cs, tt.co, tt.succ)
}
}

func (s *testCharsetSuite) TestGetCharsetDesc(c *C) {
defer testleak.AfterTest(c)()
tests := []struct {
cs string
result string
succ bool
}{
{"utf8", "utf8", true},
{"UTF8", "utf8", true},
{"utf8mb4", "utf8mb4", true},
{"ascii", "ascii", true},
{"binary", "binary", true},
{"latin1", "latin1", true},
{"invalid_cs", "", false},
{"", "utf8_bin", false},
}
for _, tt := range tests {
desc, err := GetCharsetDesc(tt.cs)
if !tt.succ {
c.Assert(err, NotNil)
} else {
c.Assert(desc.Name, Equals, tt.result)
}
}
}

func BenchmarkGetCharsetDesc(b *testing.B) {
b.ResetTimer()
charsets := []string{CharsetUTF8, CharsetUTF8MB4, CharsetASCII, CharsetLatin1, CharsetBin}
index := rand.Intn(len(charsets))
cs := charsets[index]

for i := 0; i < b.N; i++ {
GetCharsetDesc(cs)
}
}

0 comments on commit a73b469

Please sign in to comment.