From 012fe52b6fa121d1d9e116cbefe9109e6c2359ec Mon Sep 17 00:00:00 2001 From: Mykhailo Lohachov Date: Sun, 25 Feb 2024 02:06:52 +0900 Subject: [PATCH] internal/atlas: use bit manipulation for function power of 2 -like functions (#2915) Closes #2914 --- internal/atlas/image.go | 7 ++----- internal/packing/packing.go | 8 +------- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/internal/atlas/image.go b/internal/atlas/image.go index 5bccc45bd..270063794 100644 --- a/internal/atlas/image.go +++ b/internal/atlas/image.go @@ -18,6 +18,7 @@ import ( "fmt" "image" "math" + "math/bits" "runtime" "sync" @@ -885,11 +886,7 @@ func floorPowerOf2(x int) int { if x <= 0 { return 0 } - p2 := 1 - for p2*2 <= x { - p2 *= 2 - } - return p2 + return 1 << (bits.Len(uint(x)) - 1) } func BeginFrame(graphicsDriver graphicsdriver.Graphics) error { diff --git a/internal/packing/packing.go b/internal/packing/packing.go index 1d9a5f36f..f656fc55e 100644 --- a/internal/packing/packing.go +++ b/internal/packing/packing.go @@ -32,13 +32,7 @@ func isPositivePowerOf2(x int) bool { if x <= 0 { return false } - for x > 1 { - if x/2*2 != x { - return false - } - x /= 2 - } - return true + return x&(x-1) == 0 } func NewPage(initWidth, initHeight int, maxSize int) *Page {