meta/changed_fields.go

61 lines
1.1 KiB
Go

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
}
func (cf *ChangedFields) Reset() {
if cf.fieldNames == nil {
cf.fieldNames = make(map[string]struct{})
} else {
for k := range cf.fieldNames {
delete(cf.fieldNames, k)
}
}
}
func (cf ChangedFields) Changed(field string) bool {
_, ok := cf.fieldNames[field]
return ok
}
func (cf *ChangedFields) SetChanged(fields ...string) {
if cf.fieldNames == nil {
cf.fieldNames = make(map[string]struct{})
}
for _, field := range fields {
if _, exists := cf.fieldNames[field]; exists {
continue
}
cf.fieldNames[field] = struct{}{}
cf.fieldsKey.WriteString(field)
}
}
func (cf ChangedFields) Empty() bool {
return len(cf.fieldNames) == 0
}
func (cf ChangedFields) IsNil() bool {
return cf.fieldNames == nil
}
func (cf ChangedFields) GetFieldsKey() string {
return cf.fieldsKey.String()
}