]> Cypherpunks repositories - gostls13.git/commitdiff
[dev.regabi] go/constant: optimize BitLen
authorMatthew Dempsky <mdempsky@google.com>
Tue, 17 Nov 2020 20:53:34 +0000 (12:53 -0800)
committerMatthew Dempsky <mdempsky@google.com>
Tue, 24 Nov 2020 19:17:41 +0000 (19:17 +0000)
Avoids an unnecessary heap allocation when computing the bit length of
int64 values.

Change-Id: I69dfc510e461daf3e83b0b7b6c0707f6526a32d0
Reviewed-on: https://go-review.googlesource.com/c/go/+/272646
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Trust: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Robert Griesemer <gri@golang.org>
src/go/constant/value.go
src/go/constant/value_test.go

index 116c7575d9eeb1dd595805901b4434f7baef5969..59606dc479572a60d9ef903324fa0cdd9b9bd91c 100644 (file)
@@ -17,6 +17,7 @@ import (
        "go/token"
        "math"
        "math/big"
+       "math/bits"
        "strconv"
        "strings"
        "sync"
@@ -610,7 +611,11 @@ func Make(x interface{}) Value {
 func BitLen(x Value) int {
        switch x := x.(type) {
        case int64Val:
-               return i64toi(x).val.BitLen()
+               u := uint64(x)
+               if x < 0 {
+                       u = uint64(-x)
+               }
+               return 64 - bits.LeadingZeros64(u)
        case intVal:
                return x.val.BitLen()
        case unknownVal:
index 1a5025cbbd4920b5115dfbeec1ec3b5f0417074b..1ad6784f9a1645fceca313fb6ce13d049e4fbfed 100644 (file)
@@ -655,3 +655,24 @@ func BenchmarkStringAdd(b *testing.B) {
                })
        }
 }
+
+var bitLenTests = []struct {
+       val  int64
+       want int
+}{
+       {0, 0},
+       {1, 1},
+       {-16, 5},
+       {1 << 61, 62},
+       {1 << 62, 63},
+       {-1 << 62, 63},
+       {-1 << 63, 64},
+}
+
+func TestBitLen(t *testing.T) {
+       for _, test := range bitLenTests {
+               if got := BitLen(MakeInt64(test.val)); got != test.want {
+                       t.Errorf("%v: got %v, want %v", test.val, got, test.want)
+               }
+       }
+}