Add string key for changed fields
This commit is contained in:
parent
19f50973f1
commit
9324aeae5f
|
@ -1,12 +1,18 @@
|
|||
package meta
|
||||
|
||||
import "bytes"
|
||||
|
||||
type ChangedFields struct {
|
||||
fieldNames map[string]struct{}
|
||||
fieldsKey *bytes.Buffer
|
||||
}
|
||||
|
||||
func NewChangedFields(fieldCount int) ChangedFields {
|
||||
keyBuffer := bytes.NewBuffer(make([]byte, 0, fieldCount*2))
|
||||
|
||||
cf := ChangedFields{
|
||||
fieldNames: make(map[string]struct{}, fieldCount),
|
||||
fieldsKey: keyBuffer,
|
||||
}
|
||||
return cf
|
||||
}
|
||||
|
@ -32,7 +38,12 @@ func (cf *ChangedFields) SetChanged(fields ...string) {
|
|||
}
|
||||
|
||||
for _, field := range fields {
|
||||
if _, exists := cf.fieldNames[field]; exists {
|
||||
continue
|
||||
}
|
||||
|
||||
cf.fieldNames[field] = struct{}{}
|
||||
cf.fieldsKey.WriteString(field)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -43,3 +54,7 @@ func (cf ChangedFields) Empty() bool {
|
|||
func (cf ChangedFields) IsNil() bool {
|
||||
return cf.fieldNames == nil
|
||||
}
|
||||
|
||||
func (cf ChangedFields) GetFieldsKey() string {
|
||||
return cf.fieldsKey.String()
|
||||
}
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package meta
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestChangedFields(t *testing.T) {
|
||||
t.Run("#SetChanged", func(t *testing.T) {
|
||||
changedFields := NewChangedFields(3)
|
||||
|
||||
expectedFieldsMap := map[string]struct{}{
|
||||
"a": {},
|
||||
"b": {},
|
||||
"c": {},
|
||||
}
|
||||
|
||||
changedFields.SetChanged("a", "b", "c", "a")
|
||||
|
||||
assert.Equal(t, expectedFieldsMap, changedFields.fieldNames)
|
||||
})
|
||||
|
||||
t.Run("#GetFieldsKey", func(t *testing.T) {
|
||||
changedFields := NewChangedFields(3)
|
||||
changedFields.SetChanged("b", "c", "a")
|
||||
expectedKey := "bca"
|
||||
|
||||
actualKey := changedFields.GetFieldsKey()
|
||||
|
||||
assert.Equal(t, expectedKey, actualKey)
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue