package jsonnum

import (
	
	
)

//go:generate go run ../cmd/pow10table pow10_table.go

// pow10Entry is 10^q as a truncated 128-bit significand: ( hi*2^64 + lo ) * 2^exp2 <= 10^q, less than the
// next significand times 2^exp2.
type pow10Entry struct {
	hi, lo uint64
	exp2   int
}

// mulPow10 returns the float64 nearest to w * 10^q, rounded to even, and true; or false when that is not decided
// by the table, which the caller then leaves to strconv.
//
// The significand T of 10^q is truncated, so the exact product w * 10^q is in [w*T, w*T + w) times 2^exp2. Both
// ends are rounded to 53 bits: when they give the same float64, it is the one of every value between them, so it
// is the float64 of w * 10^q. Only a product very near a half-way point between two float64 values gives two,
// which is rare.
func mulPow10( uint64,  int) (float64, bool) {
	if  == 0 {
		return 0, true
	}
	if  < minPow10Exp10 ||  > maxPow10Exp10 {
		return 0, false
	}
	 := &pow10Table[-minPow10Exp10]
	// the lower end: w * T, a number of 192 bits in p2, p1, p0.
	,  := bits.Mul64(, .lo)
	,  := bits.Mul64(, .hi)
	 := 
	,  := bits.Add64(, , 0)
	 :=  + 
	// the upper end: w * T + w.
	,  := bits.Add64(, , 0)
	,  := bits.Add64(, 0, )
	 :=  + 
	, ,  := round192(, , )
	if ! {
		return 0, false
	}
	, ,  := round192(, , )
	if ! ||  !=  ||  !=  {
		return 0, false
	}
	// the value is m * 2^( e + exp2 ), and m has 53 bits.
	 :=  + .exp2
	// a normal float64 is m * 2^exp with 53-bit m and exp from -1074 to 971.
	if  < -1074 ||  > 971 {
		return 0, false
	}
	return math.Ldexp(float64(), ), true
}

// round192 rounds the 192-bit number x2*2^128 + x1*2^64 + x0, whose top word is not zero, to 53 bits, to even:
// it returns m and e such that the rounded number is m * 2^e with 2^52 <= m < 2^53.
func round192(, ,  uint64) (uint64, int, bool) {
	if  == 0 {
		return 0, 0, false
	}
	 := bits.LeadingZeros64()
	// the top 64 bits of the number, and whether a bit below them is set.
	 := <<uint() | >>uint(64-)
	if  == 0 {
		 = 
	}
	 := <<uint() | 
	 :=  != 0 || &(1<<10-1) != 0
	 :=  >> 11
	 := >>10&1 != 0
	if  && ( || &1 != 0) {
		++
		if  == 1<<53 {
			 >>= 1
			return , 11 + 128 -  + 1, true
		}
	}
	return , 11 + 128 - , true
}