github.com/mailru/activerecord@v1.12.2/pkg/activerecord/hash.go (about) 1 package activerecord 2 3 import ( 4 "encoding/binary" 5 "encoding/hex" 6 "fmt" 7 "hash" 8 ) 9 10 type GroupHash struct { 11 hash hash.Hash32 12 calculated bool 13 } 14 15 func NewGroupHash(hash hash.Hash32) *GroupHash { 16 return &GroupHash{hash: hash} 17 } 18 19 func (o *GroupHash) UpdateHash(data ...interface{}) error { 20 if o.calculated { 21 return fmt.Errorf("can't update hash after calculate") 22 } 23 24 for _, v := range data { 25 var err error 26 27 switch v := v.(type) { 28 case string: 29 err = binary.Write(o.hash, binary.LittleEndian, []byte(v)) 30 case int: 31 err = binary.Write(o.hash, binary.LittleEndian, int64(v)) 32 default: 33 err = binary.Write(o.hash, binary.LittleEndian, v) 34 } 35 36 if err != nil { 37 return fmt.Errorf("can't calculate connectionID: %w", err) 38 } 39 } 40 41 return nil 42 } 43 44 func (o *GroupHash) GetHash() string { 45 o.calculated = true 46 hashInBytes := o.hash.Sum(nil)[:] 47 48 return hex.EncodeToString(hashInBytes) 49 }