From 5ec1b4baaf01dae0b22567db53886c83b74e0e76 Mon Sep 17 00:00:00 2001 From: Renning Bruns Date: Tue, 28 Feb 2023 09:36:58 -0800 Subject: [PATCH] make hashmod a lot easier to read and a little faster (#11551) Previous code was effectively doing BigEndian.Uint64, so call that and save time. An md5.Sum result is always 16 bytes. The first 8 are not used in the result, just as before. Signed-off-by: Renning Bruns --- model/relabel/relabel.go | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/model/relabel/relabel.go b/model/relabel/relabel.go index 0cc6eeeb7..eb05817c0 100644 --- a/model/relabel/relabel.go +++ b/model/relabel/relabel.go @@ -15,6 +15,7 @@ package relabel import ( "crypto/md5" + "encoding/binary" "fmt" "strings" @@ -268,7 +269,9 @@ func relabel(lset labels.Labels, cfg *Config, lb *labels.Builder) (ret labels.La case Uppercase: lb.Set(cfg.TargetLabel, strings.ToUpper(val)) case HashMod: - mod := sum64(md5.Sum([]byte(val))) % cfg.Modulus + hash := md5.Sum([]byte(val)) + // Use only the last 8 bytes of the hash to give the same result as earlier versions of this code. + mod := binary.BigEndian.Uint64(hash[8:]) % cfg.Modulus lb.Set(cfg.TargetLabel, fmt.Sprintf("%d", mod)) case LabelMap: lset.Range(func(l labels.Label) { @@ -295,15 +298,3 @@ func relabel(lset labels.Labels, cfg *Config, lb *labels.Builder) (ret labels.La return lb.Labels(lset), true } - -// sum64 sums the md5 hash to an uint64. -func sum64(hash [md5.Size]byte) uint64 { - var s uint64 - - for i, b := range hash { - shift := uint64((md5.Size - i - 1) * 8) - - s |= uint64(b) << shift - } - return s -}