refactor: make HashCode a generic utility

This commit is contained in:
Derrick Hammer 2024-01-03 08:27:04 -05:00
parent 3a251479e1
commit 355de2b65f
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
3 changed files with 15 additions and 7 deletions

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"git.lumeweb.com/LumeWeb/libs5-go/internal/bases" "git.lumeweb.com/LumeWeb/libs5-go/internal/bases"
"git.lumeweb.com/LumeWeb/libs5-go/types" "git.lumeweb.com/LumeWeb/libs5-go/types"
"git.lumeweb.com/LumeWeb/libs5-go/utils"
"github.com/multiformats/go-multibase" "github.com/multiformats/go-multibase"
"unicode/utf8" "unicode/utf8"
) )
@ -67,6 +68,7 @@ func (m *Multihash) Equals(other *Multihash) bool {
} }
func (m *Multihash) HashCode() MultihashCode { func (m *Multihash) HashCode() MultihashCode {
return utils.HashCode(m.FullBytes[:4])
return int(m.FullBytes[0]) + return int(m.FullBytes[0]) +
int(m.FullBytes[1])<<8 + int(m.FullBytes[1])<<8 +
int(m.FullBytes[2])<<16 + int(m.FullBytes[2])<<16 +

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"errors" "errors"
"git.lumeweb.com/LumeWeb/libs5-go/internal/bases" "git.lumeweb.com/LumeWeb/libs5-go/internal/bases"
"git.lumeweb.com/LumeWeb/libs5-go/utils"
"github.com/multiformats/go-multibase" "github.com/multiformats/go-multibase"
) )
@ -40,13 +41,7 @@ func (nodeId *NodeId) Equals(other interface{}) bool {
} }
func (nodeId *NodeId) HashCode() int { func (nodeId *NodeId) HashCode() int {
if len(nodeId.Bytes) < 4 { return utils.HashCode(nodeId.Bytes[:4])
return 0
}
return int(nodeId.Bytes[0]) +
int(nodeId.Bytes[1])<<8 +
int(nodeId.Bytes[2])<<16 +
int(nodeId.Bytes[3])<<24
} }
func (nodeId *NodeId) ToBase58() (string, error) { func (nodeId *NodeId) ToBase58() (string, error) {

View File

@ -5,3 +5,14 @@ import "bytes"
func ConcatBytes(slices ...[]byte) []byte { func ConcatBytes(slices ...[]byte) []byte {
return bytes.Join(slices, nil) return bytes.Join(slices, nil)
} }
func HashCode(bytes []byte) int {
if len(bytes) < 4 {
return 0
}
return int(bytes[0]) |
int(bytes[1])<<8 |
int(bytes[2])<<16 |
int(bytes[3])<<24
}