diff --git a/stream/mts/meta/meta.go b/stream/mts/meta/meta.go index 7a863d0c..eaa0713e 100644 --- a/stream/mts/meta/meta.go +++ b/stream/mts/meta/meta.go @@ -45,8 +45,7 @@ const ( // Indices of bytes for uint16 metadata length. const ( - dataLenIdx1 = 2 - dataLenIdx2 = 3 + dataLenIdx = 2 ) var ( @@ -58,9 +57,10 @@ var ( // Metadata provides functionality for the storage and encoding of metadata // using a map. type Metadata struct { - mu sync.RWMutex - data map[string]string - enc []byte + mu sync.RWMutex + data map[string]string + order []string + enc []byte } // New returns a pointer to a new Metadata. @@ -80,6 +80,7 @@ func New() *Metadata { func (m *Metadata) Add(key, val string) { m.mu.Lock() m.data[key] = val + m.order = append(m.order, key) m.mu.Unlock() } @@ -111,6 +112,12 @@ func (m *Metadata) Delete(key string) error { defer m.mu.Unlock() if _, ok := m.data[key]; ok { delete(m.data, key) + for i, k := range m.order { + if k == key { + m.order = append(m.order[:i], m.order[i+1:]...) + break + } + } return nil } return errKeyAbsent @@ -123,12 +130,11 @@ func (m *Metadata) Encode() []byte { // Iterate over map and append entries, only adding tab if we're not on the // last entry. - var i int var entry string - for k, v := range m.data { - i++ + for i, k := range m.order { + v := m.data[k] entry += k + "=" + v - if i < len(m.data) { + if i+1 < len(m.data) { entry += "\t" } } @@ -136,9 +142,7 @@ func (m *Metadata) Encode() []byte { // Calculate and set data length in encoded meta header. dataLen := len(m.enc[headSize:]) - m.enc[dataLenIdx1] = byte(dataLen >> 8) - m.enc[dataLenIdx2] = byte(dataLen) - + binary.BigEndian.PutUint16(m.enc[dataLenIdx:dataLenIdx+2], uint16(dataLen)) return m.enc }