Skip to content

Commit

Permalink
improve: GetAllCharsets and GetCharsetInfoByID (#247)
Browse files Browse the repository at this point in the history
  • Loading branch information
hawkingrei authored and ngaut committed Mar 19, 2019
1 parent 2575f2d commit 551b517
Showing 1 changed file with 13 additions and 19 deletions.
32 changes: 13 additions & 19 deletions charset/charset.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ type Collation struct {
}

var charsets = make(map[string]*Charset)
var collationsMap = make(map[int]*Collation)
var descs = make([]*Desc, 0, len(charsetInfos))

// All the supported charsets should be in the following table.
var charsetInfos = []*Charset{
Expand All @@ -60,21 +62,6 @@ type Desc struct {

// GetAllCharsets gets all charset descriptions in the local charsets.
func GetAllCharsets() []*Desc {
descs := make([]*Desc, 0, len(charsets))
// The charsetInfos is an array, so the iterate order will be stable.
for _, ci := range charsetInfos {
c, ok := charsets[ci.Name]
if !ok {
continue
}
desc := &Desc{
Name: c.Name,
DefaultCollation: c.DefaultCollation,
Desc: c.Desc,
Maxlen: c.Maxlen,
}
descs = append(descs, desc)
}
return descs
}

Expand Down Expand Up @@ -150,10 +137,8 @@ func GetCharsetInfoByID(coID int) (string, string, error) {
if coID == mysql.DefaultCollationID {
return mysql.DefaultCharset, mysql.DefaultCollationName, nil
}
for _, collation := range collations {
if coID == collation.ID {
return collation.CharsetName, collation.Name, nil
}
if collation, ok := collationsMap[coID]; ok {
return collation.CharsetName, collation.Name, nil
}
return "", "", errors.Errorf("Unknown charset id %d", coID)
}
Expand Down Expand Up @@ -412,8 +397,17 @@ var collations = []*Collation{
func init() {
for _, c := range charsetInfos {
charsets[c.Name] = c
desc := &Desc{
Name: c.Name,
DefaultCollation: c.DefaultCollation,
Desc: c.Desc,
Maxlen: c.Maxlen,
}
descs = append(descs, desc)
}

for _, c := range collations {
collationsMap[c.ID] = c
charset, ok := charsets[c.CharsetName]
if !ok {
continue
Expand Down

0 comments on commit 551b517

Please sign in to comment.