Skip to content

roaring64: compare sign-extended planes in BSI Equals - #613

Merged
lemire merged 2 commits into
masterfrom
bsi64-equals-sign-extend
Dec 5, 2026
Merged

lemire merged 2 commits into
masterfrom
bsi64-equals-sign-extend

Conversation

@lemire

@lemire lemire commented Dec 4, 2026

Copy link
Copy Markdown
Member

Bug

BSI.Equals handled BSIs of different widths by requiring the extra planes of the wider one to be empty. That is only right when the narrower BSI holds no negative values. In two's complement, a BSI's planes past its top repeat its sign plane. This causes two errors:

  • False negative: the same negative value at two widths compares unequal.

    a := roaring64.NewDefaultBSI();               a.SetValue(1, -1)  // 2 planes
    b := roaring64.NewBSI(1<<40, -(1 << 40));     b.SetValue(1, -1)  // 42 planes
    a.Equals(b) // false
  • False positive: a 2-plane BSI holding -1 (planes 11) and a 3-plane BSI holding 3 (planes 011) compare equal, because their two low planes match and the third plane of the wider one is empty.

Different widths are common. They come from NewBSI bounds, from SetValue widening an auto-sized BSI, and from Add.

Fix

Compare the planes sign-extended to the wider width: past the top of a BSI, its sign plane is used. A BSI with no planes counts as all zeros. When neither BSI holds a negative value this is the same as before, and BSIs of the same width are compared exactly as before.

Testing

TestEqualsDifferentWidths covers:

  • the values -5 to 5 at two widths, in both directions;
  • the -1 vs 3 false positive, at mixed widths and at one width;
  • a BSI with no planes compared with zero and with -1.

On master, the test fails on both the false-negative and the false-positive checks. go test ./roaring64, go vet and gofmt pass.

Equals compared the planes of the wider BSI past the top of the
narrower one against an empty plane. That is only right when the
narrower BSI holds no negative values. Two BSIs of different widths
holding the same negative value compared unequal, and a 2-plane BSI
holding -1 compared equal to a 3-plane BSI holding 3, since their two
low planes match. Compare each plane past the top of a BSI against its
sign plane instead.
Keep the sign-extension Equals tests and the tests already on master.
@lemire
lemire merged commit 84c892f into master Dec 5, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant