From 9324aeae5faf24e11c59a6c3db711248c009a266 Mon Sep 17 00:00:00 2001 From: Sergey Polygalin Date: Sun, 17 Dec 2023 11:42:39 +0300 Subject: [PATCH] Add string key for changed fields --- changed_fields.go | 15 +++++++++++++++ changed_fields_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 changed_fields_test.go diff --git a/changed_fields.go b/changed_fields.go index 41e0fe6..4d1de4e 100644 --- a/changed_fields.go +++ b/changed_fields.go @@ -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() +} diff --git a/changed_fields_test.go b/changed_fields_test.go new file mode 100644 index 0000000..263b93d --- /dev/null +++ b/changed_fields_test.go @@ -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) + }) +}