select method
The entry state selects among candidates, or null if none.
At each node, a set state bit prefers the right half when it holds a candidate; a clear bit prefers the left half when it holds one.
Implementation
int? select(int state, int candidates) {
if (candidates == 0) {
return null;
}
var node = 0;
var start = 0;
var end = entryCount;
while (end - start > 1) {
final middle = (start + end) >> 1;
final half = middle - start;
final leftHas = (candidates >> start) & ((1 << half) - 1) != 0;
final rightHas = (candidates >> middle) & ((1 << half) - 1) != 0;
final chooseRight =
(state >> node) & 1 == 1 ? rightHas : !leftHas && rightHas;
if (chooseRight) {
node = 2 * node + 2;
start = middle;
} else {
node = 2 * node + 1;
end = middle;
}
}
return start;
}