Skip to content

Commit 46b0acf

Browse files
authored
Merge pull request #473 from TheHippo/reusable-slices
`ToArray` with pre-allocated slices: `ToExistingArray`
2 parents 773047c + ae117dc commit 46b0acf

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

roaring.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,18 +421,30 @@ func FromBitSet(bitset *bitset.BitSet) *Bitmap {
421421
// ToArray creates a new slice containing all of the integers stored in the Bitmap in sorted order
422422
func (rb *Bitmap) ToArray() []uint32 {
423423
array := make([]uint32, rb.GetCardinality())
424+
ar := rb.toArray(&array)
425+
return *ar
426+
}
427+
428+
func (rb *Bitmap) toArray(array *[]uint32) *[]uint32 {
424429
pos := 0
425430
pos2 := 0
426431

427432
for pos < rb.highlowcontainer.size() {
428433
hs := uint32(rb.highlowcontainer.getKeyAtIndex(pos)) << 16
429434
c := rb.highlowcontainer.getContainerAtIndex(pos)
430435
pos++
431-
pos2 = c.fillLeastSignificant16bits(array, pos2, hs)
436+
pos2 = c.fillLeastSignificant16bits(*array, pos2, hs)
432437
}
433438
return array
434439
}
435440

441+
// ToExistingArray stores all of the integers stored in the Bitmap in sorted order in the
442+
// slice that is given to ToExistingArray. It is the callers duty to make sure the slice
443+
// has the right size.
444+
func (rb *Bitmap) ToExistingArray(array *[]uint32) *[]uint32 {
445+
return rb.toArray(array)
446+
}
447+
436448
// GetSizeInBytes estimates the memory usage of the Bitmap. Note that this
437449
// might differ slightly from the amount of bytes required for persistent storage
438450
func (rb *Bitmap) GetSizeInBytes() uint64 {

roaring_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1827,6 +1827,20 @@ func TestBitmap(t *testing.T) {
18271827

18281828
assert.True(t, valide)
18291829
})
1830+
1831+
t.Run("ToExistingArray-Test", func(t *testing.T) {
1832+
values := make([]uint32, 0, 110)
1833+
rb := NewBitmap()
1834+
1835+
for i := 10; i < 120; i++ {
1836+
values = append(values, uint32(i))
1837+
}
1838+
rb.AddMany(values)
1839+
assert.Equal(t, values, rb.ToArray())
1840+
existing := make([]uint32, len(values))
1841+
buf := rb.ToExistingArray(&existing)
1842+
assert.Equal(t, values, *buf)
1843+
})
18301844
}
18311845

18321846
func TestXORtest4(t *testing.T) {

0 commit comments

Comments
 (0)