diff --git a/roaring.go b/roaring.go index 9972a51e..66f797ea 100644 --- a/roaring.go +++ b/roaring.go @@ -421,6 +421,11 @@ func FromBitSet(bitset *bitset.BitSet) *Bitmap { // ToArray creates a new slice containing all of the integers stored in the Bitmap in sorted order func (rb *Bitmap) ToArray() []uint32 { array := make([]uint32, rb.GetCardinality()) + ar := rb.toArray(&array) + return *ar +} + +func (rb *Bitmap) toArray(array *[]uint32) *[]uint32 { pos := 0 pos2 := 0 @@ -428,11 +433,18 @@ func (rb *Bitmap) ToArray() []uint32 { hs := uint32(rb.highlowcontainer.getKeyAtIndex(pos)) << 16 c := rb.highlowcontainer.getContainerAtIndex(pos) pos++ - pos2 = c.fillLeastSignificant16bits(array, pos2, hs) + pos2 = c.fillLeastSignificant16bits(*array, pos2, hs) } return array } +// ToExistingArray stores all of the integers stored in the Bitmap in sorted order in the +// slice that is given to ToExistingArray. It is the callers duty to make sure the slice +// has the right size. +func (rb *Bitmap) ToExistingArray(array *[]uint32) *[]uint32 { + return rb.toArray(array) +} + // GetSizeInBytes estimates the memory usage of the Bitmap. Note that this // might differ slightly from the amount of bytes required for persistent storage func (rb *Bitmap) GetSizeInBytes() uint64 { diff --git a/roaring_test.go b/roaring_test.go index 277c2796..eb739f0b 100644 --- a/roaring_test.go +++ b/roaring_test.go @@ -1827,6 +1827,20 @@ func TestBitmap(t *testing.T) { assert.True(t, valide) }) + + t.Run("ToExistingArray-Test", func(t *testing.T) { + values := make([]uint32, 0, 110) + rb := NewBitmap() + + for i := 10; i < 120; i++ { + values = append(values, uint32(i)) + } + rb.AddMany(values) + assert.Equal(t, values, rb.ToArray()) + existing := make([]uint32, len(values)) + buf := rb.ToExistingArray(&existing) + assert.Equal(t, values, *buf) + }) } func TestXORtest4(t *testing.T) {