From 5259284545fc48177fc5a0a49255c49cb41e2f06 Mon Sep 17 00:00:00 2001 From: Vincent Lee Date: Mon, 27 Nov 2017 16:02:55 +0800 Subject: [PATCH] add return bool to indicate changed --- common.go | 8 +++++++- hyperloglog.go | 5 ++++- hyperloglogplus.go | 11 ++++++++--- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/common.go b/common.go index 3aa310e..fa3da63 100644 --- a/common.go +++ b/common.go @@ -18,7 +18,13 @@ func (p sortableSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } type set map[uint32]bool -func (s set) Add(i uint32) { s[i] = true } +func (s set) Add(i uint32) bool { + if s[i] { + return false + } + s[i] = true + return true +} func alpha(m uint32) float64 { if m == 16 { diff --git a/hyperloglog.go b/hyperloglog.go index 1c7e120..bb5ef05 100644 --- a/hyperloglog.go +++ b/hyperloglog.go @@ -45,15 +45,18 @@ func (h *HyperLogLog) Clear() { } // Add adds a new item to HyperLogLog h. -func (h *HyperLogLog) Add(item Hash32) { +func (h *HyperLogLog) Add(item Hash32) bool { x := item.Sum32() i := eb32(x, 32, 32-h.p) // {x31,...,x32-p} w := x< h.reg[i] { h.reg[i] = zeroBits + changed = true } + return changed } // Merge takes another HyperLogLog and combines it with HyperLogLog h. diff --git a/hyperloglogplus.go b/hyperloglogplus.go index d8d8337..cc42e98 100644 --- a/hyperloglogplus.go +++ b/hyperloglogplus.go @@ -144,11 +144,14 @@ func (h *HyperLogLogPlus) toNormal() { } // Add adds a new item to HyperLogLogPlus h. -func (h *HyperLogLogPlus) Add(item Hash64) { +func (h *HyperLogLogPlus) Add(item Hash64) bool { x := item.Sum64() + changed := false if h.sparse { - h.tmpSet.Add(h.encodeHash(x)) - h.maybeMerge() + changed = h.tmpSet.Add(h.encodeHash(x)) + if changed { + h.maybeMerge() + } } else { i := eb64(x, 64, 64-h.p) // {x63,...,x64-p} w := x< h.reg[i] { h.reg[i] = zeroBits + changed = true } } + return changed } // Merge takes another HyperLogLogPlus and combines it with HyperLogLogPlus h.