Add string key for changed fields

This commit is contained in:
Sergey Polygalin 2023-12-17 11:42:39 +03:00
parent 19f50973f1
commit 9324aeae5f
2 changed files with 48 additions and 0 deletions

View File

@ -1,12 +1,18 @@
package meta package meta
import "bytes"
type ChangedFields struct { type ChangedFields struct {
fieldNames map[string]struct{} fieldNames map[string]struct{}
fieldsKey *bytes.Buffer
} }
func NewChangedFields(fieldCount int) ChangedFields { func NewChangedFields(fieldCount int) ChangedFields {
keyBuffer := bytes.NewBuffer(make([]byte, 0, fieldCount*2))
cf := ChangedFields{ cf := ChangedFields{
fieldNames: make(map[string]struct{}, fieldCount), fieldNames: make(map[string]struct{}, fieldCount),
fieldsKey: keyBuffer,
} }
return cf return cf
} }
@ -32,7 +38,12 @@ func (cf *ChangedFields) SetChanged(fields ...string) {
} }
for _, field := range fields { for _, field := range fields {
if _, exists := cf.fieldNames[field]; exists {
continue
}
cf.fieldNames[field] = struct{}{} cf.fieldNames[field] = struct{}{}
cf.fieldsKey.WriteString(field)
} }
} }
@ -43,3 +54,7 @@ func (cf ChangedFields) Empty() bool {
func (cf ChangedFields) IsNil() bool { func (cf ChangedFields) IsNil() bool {
return cf.fieldNames == nil return cf.fieldNames == nil
} }
func (cf ChangedFields) GetFieldsKey() string {
return cf.fieldsKey.String()
}

33
changed_fields_test.go Normal file
View File

@ -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)
})
}