Skip to content

Commit

Permalink
Improve capacity allocation in DumpCoordinates for MultiPoint
Browse files Browse the repository at this point in the history
  • Loading branch information
peterstace committed Jul 27, 2021
1 parent e078fff commit c41162f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
11 changes: 11 additions & 0 deletions geom/bitset.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package geom

import "math/bits"

// BitSet is a set data structure that holds a mapping from non-negative
// integers to boolean values (bits). The zero value is the BitSet with all
// bits set to false.
Expand Down Expand Up @@ -36,6 +38,15 @@ func (b *BitSet) Set(i int, newVal bool) {
}
}

// CountTrue counts the number of elements in the set that are true.
func (b *BitSet) CountTrue() int {
var count int
for _, mask := range b.masks {
count += bits.OnesCount64(mask)
}
return count
}

// Clone makes a deep copy of the BitSet.
func (b *BitSet) Clone() BitSet {
return BitSet{append([]uint64(nil), b.masks...)}
Expand Down
7 changes: 7 additions & 0 deletions geom/bitset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ func TestBitSet(t *testing.T) {
expectFalse(t, s.Get(i))
s.Set(i, true)
expectTrue(t, s.Get(i))
expectIntEq(t, s.CountTrue(), 1)
s.Set(i, false)
expectFalse(t, s.Get(i))
expectIntEq(t, s.CountTrue(), 0)
})
}
})
Expand All @@ -30,9 +32,14 @@ func TestBitSet(t *testing.T) {
choice := rnd.Intn(n)
want[choice] = !want[choice]
s.Set(choice, want[choice])
var wantCountTrue int
for j := 0; j < n; j++ {
expectBoolEq(t, s.Get(j), want[j])
if want[j] {
wantCountTrue++
}
}
expectIntEq(t, s.CountTrue(), wantCountTrue)
}
})
}
9 changes: 1 addition & 8 deletions geom/type_multi_point.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,21 +299,14 @@ func (m MultiPoint) Dump() []Point {
// a Sequence.
func (m MultiPoint) DumpCoordinates() Sequence {
n := m.seq.Length()
var empty int
for i := 0; i < n; i++ {
if m.empty.Get(i) {
empty++
}
}

empty := m.empty.CountTrue()
nonEmpty := make([]float64, 0, n-empty)
for i := 0; i < n; i++ {
if m.empty.Get(i) {
continue
}
nonEmpty = m.seq.Get(i).appendFloat64s(nonEmpty)
}

seq := NewSequence(nonEmpty, m.seq.CoordinatesType())
seq.assertNoUnusedCapacity()
return seq
Expand Down

0 comments on commit c41162f

Please sign in to comment.