Skip to content

Commit 551b517

Browse files
hawkingreingaut
authored andcommitted
improve: GetAllCharsets and GetCharsetInfoByID (#247)
1 parent 2575f2d commit 551b517

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

charset/charset.go

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ type Collation struct {
4040
}
4141

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

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

6163
// GetAllCharsets gets all charset descriptions in the local charsets.
6264
func GetAllCharsets() []*Desc {
63-
descs := make([]*Desc, 0, len(charsets))
64-
// The charsetInfos is an array, so the iterate order will be stable.
65-
for _, ci := range charsetInfos {
66-
c, ok := charsets[ci.Name]
67-
if !ok {
68-
continue
69-
}
70-
desc := &Desc{
71-
Name: c.Name,
72-
DefaultCollation: c.DefaultCollation,
73-
Desc: c.Desc,
74-
Maxlen: c.Maxlen,
75-
}
76-
descs = append(descs, desc)
77-
}
7865
return descs
7966
}
8067

@@ -150,10 +137,8 @@ func GetCharsetInfoByID(coID int) (string, string, error) {
150137
if coID == mysql.DefaultCollationID {
151138
return mysql.DefaultCharset, mysql.DefaultCollationName, nil
152139
}
153-
for _, collation := range collations {
154-
if coID == collation.ID {
155-
return collation.CharsetName, collation.Name, nil
156-
}
140+
if collation, ok := collationsMap[coID]; ok {
141+
return collation.CharsetName, collation.Name, nil
157142
}
158143
return "", "", errors.Errorf("Unknown charset id %d", coID)
159144
}
@@ -412,8 +397,17 @@ var collations = []*Collation{
412397
func init() {
413398
for _, c := range charsetInfos {
414399
charsets[c.Name] = c
400+
desc := &Desc{
401+
Name: c.Name,
402+
DefaultCollation: c.DefaultCollation,
403+
Desc: c.Desc,
404+
Maxlen: c.Maxlen,
405+
}
406+
descs = append(descs, desc)
415407
}
408+
416409
for _, c := range collations {
410+
collationsMap[c.ID] = c
417411
charset, ok := charsets[c.CharsetName]
418412
if !ok {
419413
continue

0 commit comments

Comments
 (0)