Skip to content

Commit

Permalink
Implement copy without reset function (#13)
Browse files Browse the repository at this point in the history
* Implement copy without reset function

* Copy the lookup acceleration structure

* Make Copy use New and respect useLocks, implement FullReset
  • Loading branch information
dhaifley authored Nov 28, 2018
1 parent 15a405f commit 87d4d00
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 12 deletions.
29 changes: 29 additions & 0 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,32 @@ func TestMinMaxMean(t *testing.T) {
t.Errorf("incorrect mean value")
}
}

func TestCopy(t *testing.T) {
h1 := hist.New()
for i := 0; i < 1000000; i++ {
if err := h1.RecordValue(float64(i)); err != nil {
t.Fatal(err)
}
}

h2 := h1.Copy()
if !h2.Equals(h1) {
t.Errorf("expected copy: %v to equal original: %v", h2, h1)
}
}

func TestFullReset(t *testing.T) {
h1 := hist.New()
for i := 0; i < 1000000; i++ {
if err := h1.RecordValue(float64(i)); err != nil {
t.Fatal(err)
}
}

h1.Reset()
h2 := hist.New()
if !h2.Equals(h1) {
t.Errorf("expected reset value: %v to equal new value: %v", h1, h2)
}
}
49 changes: 37 additions & 12 deletions circonusllhist.go
Original file line number Diff line number Diff line change
Expand Up @@ -795,28 +795,53 @@ func (h *Histogram) Equals(other *Histogram) bool {
return true
}

func (h *Histogram) CopyAndReset() *Histogram {
// Copy creates and returns an exact copy of a histogram.
func (h *Histogram) Copy() *Histogram {
if h.useLocks {
h.mutex.Lock()
defer h.mutex.Unlock()
}
newhist := &Histogram{
allocd: h.allocd,
used: h.used,
bvs: h.bvs,

newhist := New()
newhist.allocd = h.allocd
newhist.used = h.used
newhist.useLocks = h.useLocks

newhist.bvs = []bin{}
for _, v := range h.bvs {
newhist.bvs = append(newhist.bvs, v)
}

for i, u := range h.lookup {
for _, v := range u {
newhist.lookup[i] = append(newhist.lookup[i], v)
}
}

return newhist
}

// FullReset resets a histogram to default empty values.
func (h *Histogram) FullReset() {
if h.useLocks {
h.mutex.Lock()
defer h.mutex.Unlock()
}

h.allocd = defaultHistSize
h.bvs = make([]bin, defaultHistSize)
h.used = 0
for i := 0; i < 256; i++ {
if h.lookup[i] != nil {
for j := range h.lookup[i] {
h.lookup[i][j] = 0
}
}
}
h.lookup = [256][]uint16{}
}

// CopyAndReset creates and returns an exact copy of a histogram,
// and resets it to default empty values.
func (h *Histogram) CopyAndReset() *Histogram {
newhist := h.Copy()
h.FullReset()
return newhist
}

func (h *Histogram) DecStrings() []string {
if h.useLocks {
h.mutex.Lock()
Expand Down

0 comments on commit 87d4d00

Please sign in to comment.