Skip to content

Commit 80d1d62

Browse files
committed
use map to speedup lookup of fields
1 parent ab00980 commit 80d1d62

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

serialization/serialization.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ import (
1616

1717
// Message is a mysql::serialization message
1818
type Message struct {
19-
Version uint8 // >= 0
20-
Format Format
19+
Version uint8 // >= 0
20+
Format Format
21+
fieldIndex map[string]int
2122
}
2223

2324
func (m *Message) String() (text string) {
@@ -30,10 +31,8 @@ func (m *Message) String() (text string) {
3031

3132
// GetFieldByName returns a field if the name matches and an error if there is no match
3233
func (m *Message) GetFieldByName(name string) (Field, error) {
33-
for _, f := range m.Format.Fields {
34-
if f.Name == name {
35-
return f, nil
36-
}
34+
if idx, ok := m.fieldIndex[name]; ok {
35+
return m.Format.Fields[idx], nil
3736
}
3837
return Field{}, fmt.Errorf("field not found: %s", name)
3938
}
@@ -125,6 +124,12 @@ func Unmarshal(data []byte, v interface{}) error {
125124
if err != nil {
126125
return err
127126
}
127+
if m.fieldIndex == nil {
128+
m.fieldIndex = make(map[string]int, len(m.Format.Fields))
129+
}
130+
for _, field := range m.Format.Fields {
131+
m.fieldIndex[field.Name] = field.ID
132+
}
128133
case *Format:
129134
pos := uint64(0)
130135
m.Size = uint64(data[pos] >> 1)

serialization/serialization_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,20 @@ func TestUmarshal_event1(t *testing.T) {
382382
},
383383
},
384384
},
385+
fieldIndex: map[string]int{
386+
"gtid_flags": 0,
387+
"uuid": 1,
388+
"gno": 2,
389+
"tag": 3,
390+
"last_committed": 4,
391+
"sequence_number": 5,
392+
"immediate_commit_timestamp": 6,
393+
"original_commit_timestamp": 7,
394+
"transaction_length": 8,
395+
"immediate_server_version": 9,
396+
"original_server_version": 10,
397+
"commit_group_ticket": 11,
398+
},
385399
}
386400

387401
err := Unmarshal(data, &msg)
@@ -392,4 +406,8 @@ func TestUmarshal_event1(t *testing.T) {
392406
}
393407

394408
require.Equal(t, expected, msg)
409+
410+
sv, err := msg.GetFieldByName("immediate_server_version")
411+
require.NoError(t, err)
412+
require.Equal(t, 9, sv.ID)
395413
}

0 commit comments

Comments
 (0)