| 1 |
// pow10table writes the table of the powers of ten which the decoder multiplies a mantissa by |
| 2 |
// ( internal/decoder/pow10_table.go ). |
| 3 |
// |
| 4 |
// The power 10^q of every q in [minExp10, maxExp10] is written as a 128-bit significand T and an exponent E, |
| 5 |
// such that T * 2^E <= 10^q < (T+1) * 2^E and 2^127 <= T < 2^128: the significand is truncated, never rounded, |
| 6 |
// which is what the decoder relies on to bound the product. They are computed by math/big, exactly. |
| 7 |
package main |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"fmt" |
| 12 |
"go/format" |
| 13 |
"math/big" |
| 14 |
"os" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
minExp10 = -348 |
| 19 |
maxExp10 = 347 |
| 20 |
) |
| 21 |
|
| 22 |
func main() { |
| 23 |
out := "internal/decoder/pow10_table.go" |
| 24 |
if len(os.Args) > 1 { |
| 25 |
out = os.Args[1] |
| 26 |
} |
| 27 |
var b bytes.Buffer |
| 28 |
fmt.Fprintln(&b, "// Code generated by internal/cmd/pow10table. DO NOT EDIT.") |
| 29 |
fmt.Fprintln(&b) |
| 30 |
fmt.Fprintln(&b, "package decoder") |
| 31 |
fmt.Fprintln(&b) |
| 32 |
fmt.Fprintf(&b, "const (\n\tminPow10Exp10 = %d\n\tmaxPow10Exp10 = %d\n)\n\n", minExp10, maxExp10) |
| 33 |
fmt.Fprintln(&b, "// pow10Table has 10^q as hi*2^64 + lo times 2^exp2, truncated, for q from minPow10Exp10.") |
| 34 |
fmt.Fprintln(&b, "var pow10Table = [...]pow10Entry{") |
| 35 |
mask := new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 64), big.NewInt(1)) |
| 36 |
for q := minExp10; q <= maxExp10; q++ { |
| 37 |
t, e := significand(q) |
| 38 |
hi := new(big.Int).Rsh(t, 64) |
| 39 |
lo := new(big.Int).And(t, mask) |
| 40 |
fmt.Fprintf(&b, "\t{hi: %#016x, lo: %#016x, exp2: %d}, // 1e%d\n", hi.Uint64(), lo.Uint64(), e, q) |
| 41 |
} |
| 42 |
fmt.Fprintln(&b, "}") |
| 43 |
src, err := format.Source(b.Bytes()) |
| 44 |
if err != nil { |
| 45 |
panic(err) |
| 46 |
} |
| 47 |
if err := os.WriteFile(out, src, 0o644); err != nil { |
| 48 |
panic(err) |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
// significand returns T and E such that T * 2^E <= 10^q < (T+1) * 2^E and 2^127 <= T < 2^128. |
| 53 |
func significand(q int) (*big.Int, int) { |
| 54 |
ten := big.NewInt(10) |
| 55 |
if q >= 0 { |
| 56 |
p := new(big.Int).Exp(ten, big.NewInt(int64(q)), nil) |
| 57 |
n := p.BitLen() |
| 58 |
if n >= 128 { |
| 59 |
return new(big.Int).Rsh(p, uint(n-128)), n - 128 |
| 60 |
} |
| 61 |
return new(big.Int).Lsh(p, uint(128-n)), n - 128 |
| 62 |
} |
| 63 |
// 10^q = 1 / 10^-q: T = floor(2^k / 10^-q) with k such that T has 128 bits, and E = -k. |
| 64 |
d := new(big.Int).Exp(ten, big.NewInt(int64(-q)), nil) |
| 65 |
k := 128 + d.BitLen() |
| 66 |
for { |
| 67 |
t := new(big.Int).Quo(new(big.Int).Lsh(big.NewInt(1), uint(k)), d) |
| 68 |
switch n := t.BitLen(); { |
| 69 |
case n > 128: |
| 70 |
k-- |
| 71 |
case n < 128: |
| 72 |
k++ |
| 73 |
default: |
| 74 |
return t, -k |
| 75 |
} |
| 76 |
} |
| 77 |
} |