From 0dd24ab19e2e07fb1a77e139aadf6d8d4f65ab27 Mon Sep 17 00:00:00 2001 From: Philipp Klose Date: Tue, 30 Jun 2026 18:28:44 +0200 Subject: [PATCH] bitmap: use bits.LeadingZeros64 intrinsic in maximum() bitmapContainer.maximum() relied on a hand-rolled clz() to find the highest set bit in the most significant non-empty word. That helper reimplemented, in portable shift/compare arithmetic, what the standard library already exposes as math/bits.LeadingZeros64, which the Go compiler lowers to a single hardware instruction (LZCNT on amd64, CLZ on arm64). The package already wraps it as countLeadingZeros (clz.go), so maximum() now calls that and the redundant clz() helper is deleted. --- bitmapcontainer.go | 30 +----------------------------- 1 file changed, 1 insertion(+), 29 deletions(-) diff --git a/bitmapcontainer.go b/bitmapcontainer.go index 99729634..a4804f9f 100644 --- a/bitmapcontainer.go +++ b/bitmapcontainer.go @@ -69,39 +69,11 @@ func (bc *bitmapContainer) safeMinimum() (uint16, error) { return val, nil } -// i should be non-zero -func clz(i uint64) int { - n := 1 - x := uint32(i >> 32) - if x == 0 { - n += 32 - x = uint32(i) - } - if x>>16 == 0 { - n += 16 - x = x << 16 - } - if x>>24 == 0 { - n += 8 - x = x << 8 - } - if x>>28 == 0 { - n += 4 - x = x << 4 - } - if x>>30 == 0 { - n += 2 - x = x << 2 - } - return n - int(x>>31) -} - func (bc *bitmapContainer) maximum() uint16 { for i := len(bc.bitmap); i > 0; i-- { w := bc.bitmap[i-1] if w != 0 { - r := clz(w) - return uint16((i-1)*64 + 63 - r) + return uint16((i-1)*64 + 63 - countLeadingZeros(w)) } } return uint16(0)