Skip to content

Commit

Permalink
Merge pull request RoaringBitmap#340 from Oppen/intersect_interval
Browse files Browse the repository at this point in the history
Implement range intersection
  • Loading branch information
lemire authored Nov 30, 2021
2 parents f5fdda2 + a6ed238 commit c8a81be
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
21 changes: 21 additions & 0 deletions roaring.go
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,27 @@ main:
return answer
}

// IntersectsWithInterval checks whether a bitmap 'rb' and an open interval '[x,y)' intersect.
func (rb *Bitmap) IntersectsWithInterval(x, y uint64) bool {
if x >= y {
return false
}
if x > MaxUint32 {
return false
}

it := newIntIterator(rb)
it.AdvanceIfNeeded(uint32(x))
if !it.HasNext() {
return false
}
if uint64(it.Next()) >= y {
return false
}

return true
}

// Intersects checks whether two bitmap intersects, bitmaps are not modified
func (rb *Bitmap) Intersects(x2 *Bitmap) bool {
pos1 := 0
Expand Down
32 changes: 32 additions & 0 deletions roaring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,38 @@ func TestIntersects1(t *testing.T) {
assert.True(t, bm2.Intersects(bm))
}

func TestIntersectsWithInterval(t *testing.T) {
bm := NewBitmap()
bm.AddRange(21, 26)

// Empty interval in range
assert.False(t, bm.IntersectsWithInterval(22, 22))
// Empty interval out of range
assert.False(t, bm.IntersectsWithInterval(27, 27))

// Non-empty interval in range, fully included
assert.True(t, bm.IntersectsWithInterval(22, 23))
// Non-empty intervals partially overlapped
assert.True(t, bm.IntersectsWithInterval(19, 23))
assert.True(t, bm.IntersectsWithInterval(23, 30))
// Non-empty interval covering the full range
assert.True(t, bm.IntersectsWithInterval(19, 30))

// Non-empty interval before start of bitmap
assert.False(t, bm.IntersectsWithInterval(19, 20))
// Non-empty interval after end of bitmap
assert.False(t, bm.IntersectsWithInterval(28, 30))

// Non-empty interval inside "hole" in bitmap
bm.AddRange(30, 40)
assert.False(t, bm.IntersectsWithInterval(28, 29))

// Non-empty interval, non-overlapping on the open side
assert.False(t, bm.IntersectsWithInterval(28, 30))
// Non-empty interval, overlapping on the open side
assert.True(t, bm.IntersectsWithInterval(28, 31))
}

func TestRangePanic(t *testing.T) {
bm := NewBitmap()
bm.Add(1)
Expand Down

0 comments on commit c8a81be

Please sign in to comment.