示例#1
0
func atof64(s string) (f float64, err error) {
	if val, ok := special(s); ok {
		return val, nil
	}

	var d decimal
	if !d.set(s) {
		return 0, syntaxError(fnParseFloat, s)
	}
	if optimize {
		if f, ok := d.atof64(); ok {
			return f, nil
		}

		// Try another fast path.
		ext := new(extFloat)
		if ok := ext.AssignDecimal(&d); ok {
			b, ovf := ext.floatBits()
			f = math.Float64frombits(b)
			if ovf {
				err = rangeError(fnParseFloat, s)
			}
			return f, err
		}
	}
	b, ovf := d.floatBits(&float64info)
	f = math.Float64frombits(b)
	if ovf {
		err = rangeError(fnParseFloat, s)
	}
	return f, err
}
示例#2
0
// DecodeFloatAscending returns the remaining byte slice after decoding and the decoded
// float64 from buf.
func DecodeFloatAscending(buf []byte) ([]byte, float64, error) {
	if PeekType(buf) != Float {
		return buf, 0, util.Errorf("did not find marker")
	}
	switch buf[0] {
	case floatNaN, floatNaNDesc:
		return buf[1:], math.NaN(), nil
	case floatNeg:
		b, u, err := DecodeUint64Ascending(buf[1:])
		if err != nil {
			return b, 0, err
		}
		u = ^u
		return b, math.Float64frombits(u), nil
	case floatZero:
		return buf[1:], 0, nil
	case floatPos:
		b, u, err := DecodeUint64Ascending(buf[1:])
		if err != nil {
			return b, 0, err
		}
		return b, math.Float64frombits(u), nil
	default:
		return nil, 0, util.Errorf("unknown prefix of the encoded byte slice: %q", buf)
	}
}
示例#3
0
func init() {
	// The atof routines return NumErrors wrapping
	// the error and the string.  Convert the table above.
	for i := range atoftests {
		test := &atoftests[i]
		if test.err != nil {
			test.err = &NumError{"ParseFloat", test.in, test.err}
		}
	}

	// Generate random inputs for tests and benchmarks
	rand.Seed(time.Now().UnixNano())
	if testing.Short() {
		atofRandomTests = make([]atofSimpleTest, 100)
	} else {
		atofRandomTests = make([]atofSimpleTest, 10000)
	}
	for i := range atofRandomTests {
		n := uint64(rand.Uint32())<<32 | uint64(rand.Uint32())
		x := math.Float64frombits(n)
		s := FormatFloat(x, 'g', -1, 64)
		atofRandomTests[i] = atofSimpleTest{x, s}
	}

	for i := range benchmarksRandomBits {
		bits := uint64(rand.Uint32())<<32 | uint64(rand.Uint32())
		x := math.Float64frombits(bits)
		benchmarksRandomBits[i] = FormatFloat(x, 'g', -1, 64)
	}

	for i := range benchmarksRandomNormal {
		x := rand.NormFloat64()
		benchmarksRandomNormal[i] = FormatFloat(x, 'g', -1, 64)
	}
}
示例#4
0
func TestCounterAdd(t *testing.T) {
	counter := NewCounter(CounterOpts{
		Name:        "test",
		Help:        "test help",
		ConstLabels: Labels{"a": "1", "b": "2"},
	}).(*counter)
	counter.Inc()
	if expected, got := 1., math.Float64frombits(counter.valBits); expected != got {
		t.Errorf("Expected %f, got %f.", expected, got)
	}
	counter.Add(42)
	if expected, got := 43., math.Float64frombits(counter.valBits); expected != got {
		t.Errorf("Expected %f, got %f.", expected, got)
	}

	if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got {
		t.Errorf("Expected error %q, got %q.", expected, got)
	}

	m := &dto.Metric{}
	counter.Write(m)

	if expected, got := `label:<name:"a" value:"1" > label:<name:"b" value:"2" > counter:<value:43 > `, m.String(); expected != got {
		t.Errorf("expected %q, got %q", expected, got)
	}
}
示例#5
0
func TestFloat64_Random(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping in short mode")
	}
	i := 0
	for i < randomChecks {
		a1 := math.Float64frombits(randomUint64())
		a2 := math.Float64frombits(randomUint64())

		if math.IsNaN(a1) || math.IsNaN(a2) {
			continue
		}
		i++

		r1 := make([]byte, 8)
		PutFloat64(r1, a1)
		v1 := Float64(r1)
		assert.Equal(t, a1, v1)

		r2 := make([]byte, 8)
		PutFloat64(r2, a2)

		switch {
		case a1 < a2:
			assert.Equal(t, -1, bytes.Compare(r1, r2), "%v %v", a1, a2)
		case a1 == a2:
			assert.Equal(t, 0, bytes.Compare(r1, r2), "%v %v", a1, a2)
		case a1 > a2:
			assert.Equal(t, +1, bytes.Compare(r1, r2), "%v %v", a1, a2)
		}
	}
}
示例#6
0
func (smp complexLEF64Sampler) Transform(buf []byte, data accel.DSPSplitComplex) {
	for i := 0; i < len(data.Real); i++ {
		j := i * 16
		data.Real[i] = float32(math.Float64frombits(binary.LittleEndian.Uint64(buf[j : j+8])))
		data.Imag[i] = float32(math.Float64frombits(binary.LittleEndian.Uint64(buf[j+8 : j+16])))
	}
}
示例#7
0
func (p *PlayerPosition) read(rr io.Reader) (err error) {
	var tmp [8]byte
	var tmp0 uint64
	if _, err = rr.Read(tmp[:8]); err != nil {
		return
	}
	tmp0 = (uint64(tmp[7]) << 0) | (uint64(tmp[6]) << 8) | (uint64(tmp[5]) << 16) | (uint64(tmp[4]) << 24) | (uint64(tmp[3]) << 32) | (uint64(tmp[2]) << 40) | (uint64(tmp[1]) << 48) | (uint64(tmp[0]) << 56)
	p.X = math.Float64frombits(tmp0)
	var tmp1 uint64
	if _, err = rr.Read(tmp[:8]); err != nil {
		return
	}
	tmp1 = (uint64(tmp[7]) << 0) | (uint64(tmp[6]) << 8) | (uint64(tmp[5]) << 16) | (uint64(tmp[4]) << 24) | (uint64(tmp[3]) << 32) | (uint64(tmp[2]) << 40) | (uint64(tmp[1]) << 48) | (uint64(tmp[0]) << 56)
	p.Y = math.Float64frombits(tmp1)
	var tmp2 uint64
	if _, err = rr.Read(tmp[:8]); err != nil {
		return
	}
	tmp2 = (uint64(tmp[7]) << 0) | (uint64(tmp[6]) << 8) | (uint64(tmp[5]) << 16) | (uint64(tmp[4]) << 24) | (uint64(tmp[3]) << 32) | (uint64(tmp[2]) << 40) | (uint64(tmp[1]) << 48) | (uint64(tmp[0]) << 56)
	p.Z = math.Float64frombits(tmp2)
	if p.OnGround, err = ReadBool(rr); err != nil {
		return
	}
	return
}
示例#8
0
func (c *Compressor) decode(buf *bytes.Buffer) []float64 {
	head, _ := buf.ReadByte()

	var pred int64
	if (head & 0x80) != 0 {
		pred = c.pred2.Prediction()
	} else {
		pred = c.pred1.Prediction()
	}

	nzb := (head & 0x70) >> 4
	if nzb > 3 {
		nzb++
	}

	dst := make([]byte, 8-nzb)

	// FIXME: errors
	buf.Read(dst)

	diff := c.ToLong(dst)
	actual := pred ^ diff

	c.pred1.Update(actual)
	c.pred2.Update(actual)

	var ret []float64
	ret = append(ret, math.Float64frombits(uint64(actual)))

	if (head & 0x08) != 0 {
		pred = c.pred2.Prediction()
	} else {
		pred = c.pred1.Prediction()
	}

	nzb = head & 0x07
	if nzb > 3 {
		nzb++
	}

	dst = make([]byte, 8-nzb)

	// FIXME: errors
	buf.Read(dst)

	diff = c.ToLong(dst)

	if nzb == 7 && diff == 0 {
		return ret
	}

	actual = pred ^ diff

	c.pred1.Update(actual)
	c.pred2.Update(actual)

	return append(ret, math.Float64frombits(uint64(actual)))
}
示例#9
0
文件: frame.go 项目: betable/tmframe
// Unmarshal overwrites f with the restored value of the TMFRAME found
// in the by []byte data.
func (f *Frame) Unmarshal(by []byte) (rest []byte, err error) {
	// zero it all
	*f = Frame{}

	n := int64(len(by))
	if n < 8 {
		return by, TooShortErr
	}
	prim := binary.LittleEndian.Uint64(by[:8])
	pti := PTI(prim % 8)

	f.Prim = int64(prim)

	switch pti {
	case PtiZero:
		f.V0 = 0.0
		return by[8:], nil
	case PtiOne:
		f.V0 = 1.0
		return by[8:], nil
	case PtiOneFloat64:
		if n < 16 {
			return by, TooShortErr
		}
		f.V0 = math.Float64frombits(binary.LittleEndian.Uint64(by[8:16]))
		return by[16:], nil
	case PtiTwo64:
		if n < 24 {
			return by, TooShortErr
		}
		f.V0 = math.Float64frombits(binary.LittleEndian.Uint64(by[8:16]))
		f.V1 = int64(binary.LittleEndian.Uint64(by[16:24]))
		return by[24:], nil
	case PtiNull:
		return by[8:], nil
	case PtiNA:
		return by[8:], nil
	case PtiNaN:
		// don't actually do this, as it make reflect.DeepEquals not work (of course): f.V0 = MyNaN
		return by[8:], nil
	case PtiUDE:
		ude := binary.LittleEndian.Uint64(by[8:16])
		f.Ude = int64(ude)
		ucount := ude & KeepLow43Bits
		ulen := int64(ucount)
		if n < 16+ulen {
			return by, TooShortErr
		}
		if ulen > 0 {
			f.Data = by[16 : 16+ucount-1] // -1 because the zero terminating byte only goes on the wire
		}
		return by[16+ucount:], nil
	default:
		panic(fmt.Sprintf("unrecog pti: %v", pti))
	}
	// panic("should never get here")
}
示例#10
0
文件: zset.go 项目: scozss/setdb
func readByteSortableFloat(b []byte) float64 {
	if b[0] < 0x80 {
		for i, v := range b[:8] {
			b[i] = v ^ 255
		}
		return math.Float64frombits(binary.BigEndian.Uint64(b))
	}
	return -math.Float64frombits(binary.BigEndian.Uint64(b))
}
示例#11
0
func (d *decoder) value(v reflect.Value) {
	switch v.Kind() {
	case reflect.Array:
		l := v.Len()
		for i := 0; i < l; i++ {
			d.value(v.Index(i))
		}

	case reflect.Struct:
		l := v.NumField()
		for i := 0; i < l; i++ {
			d.value(v.Field(i))
		}

	case reflect.Slice:
		l := v.Len()
		for i := 0; i < l; i++ {
			d.value(v.Index(i))
		}

	case reflect.Int8:
		v.SetInt(int64(d.int8()))
	case reflect.Int16:
		v.SetInt(int64(d.int16()))
	case reflect.Int32:
		v.SetInt(int64(d.int32()))
	case reflect.Int64:
		v.SetInt(d.int64())

	case reflect.Uint8:
		v.SetUint(uint64(d.uint8()))
	case reflect.Uint16:
		v.SetUint(uint64(d.uint16()))
	case reflect.Uint32:
		v.SetUint(uint64(d.uint32()))
	case reflect.Uint64:
		v.SetUint(d.uint64())

	case reflect.Float32:
		v.SetFloat(float64(math.Float32frombits(d.uint32())))
	case reflect.Float64:
		v.SetFloat(math.Float64frombits(d.uint64()))

	case reflect.Complex64:
		v.SetComplex(complex(
			float64(math.Float32frombits(d.uint32())),
			float64(math.Float32frombits(d.uint32())),
		))
	case reflect.Complex128:
		v.SetComplex(complex(
			math.Float64frombits(d.uint64()),
			math.Float64frombits(d.uint64()),
		))
	}
}
示例#12
0
文件: data.go 项目: OctoTail/Emperor
func ReqSET2(msg []byte, pId uint16) error {
	// TODO: check len(msg)
	switch msg[0] {
	case 0: //Unit
		unitId := binary.BigEndian.Uint32(msg[1:5])
		unit, ok := Units[unitId]
		if !ok {
			return errors.New("No such Unit")
		}
		unit.Lock()
		defer unit.Unlock()
		if unit.Owner.A != pId {
			return errors.New("Do not own Unit")
		}
		switch msg[5] { //Switch attributes
		case 0: //X,Y
			if pId != 0 {
				return errors.New("Can't change Unit.X/Y")
			}
			x := math.Float64frombits(binary.BigEndian.Uint64(msg[6:14]))
			y := math.Float64frombits(binary.BigEndian.Uint64(msg[14:22]))
			unit.X.Update(x)
			unit.Y.Update(y)

		case 1: //Vx,Vy
			vx := math.Float64frombits(binary.BigEndian.Uint64(msg[6:14]))
			vy := math.Float64frombits(binary.BigEndian.Uint64(msg[14:22]))
			if math.Sqrt(vx*vx+vy*vy) > unit.MaxSpeed.A {
				return errors.New("Desired speed > Unit.MaxSpeed")
			}
			deltafov(unitId, 5, vx, vy)
			unit.Vx.Update(vx)
			unit.Vy.Update(vy)
			updateFn := func(id ...interface{}) {
				unit := Units[id[0].(uint32)]
				unit.Lock()
				defer unit.Unlock()
				//TODO: Check for confilcts
				unit.X.Update(unit.X.A + unit.Vx.A)
				unit.Y.Update(unit.Y.A + unit.Vy.A)
			}
			Timers[timersI] = &Timer{fn: updateFn,
				args:   []interface{}{unitId},
				Delta:  1.0,
				id:     timersI,
				inform: unit.Vx.inform}
			Timers[timersI].Go()
			//unit.MvTimer.Update(timersI)
			timersI++

		}
	}
	return nil
}
示例#13
0
文件: req.go 项目: OctoTail/Emperor
func main() {
	AES_KEY := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
	PID := []byte{0, 1}

	ServerAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:8888")
	LocalAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	Conn, _ := net.DialUDP("udp", LocalAddr, ServerAddr)
	defer Conn.Close()

	go func() {
		for {
			p := make([]byte, 2048)
			n, _ := Conn.Read(p)

			msg, err := encryption.Decrypt(p[:n], AES_KEY)
			if err != nil {
				fmt.Printf("%s\n", err)
				return
			}
			switch msg[0] {
			case 0:
				fmt.Printf("Unit[")
				id := binary.BigEndian.Uint32(msg[1:5])
				fmt.Printf("%d].%d := %x\n", id, msg[5], msg[6:])
			case 1:
				fmt.Printf("Timer[")
				id := binary.BigEndian.Uint32(msg[1:5])
				start := math.Float64frombits(binary.BigEndian.Uint64(msg[5:13]))
				delta := math.Float64frombits(binary.BigEndian.Uint64(msg[13:21]))
				fmt.Printf("%d] := %f->%f\n", id, start, delta)
				break
			default:
				fmt.Printf("%d[", msg[0])
				id := binary.BigEndian.Uint32(msg[1:5])
				fmt.Printf("%d].%d := %x\n", id, msg[5], msg[6:])
			}
		}
	}()

	for {
		input := make([]byte, 0)
		for {
			var x byte
			_, err := fmt.Scanf("%x", &x)
			if err != nil {
				break
			}
			input = append(input, x)
		}
		buf := encryption.Encrypt(input, AES_KEY)
		buf = append(PID, buf...)
		Conn.Write(buf)
	}
}
示例#14
0
func complex128Decoder(dec *decoder, v reflect.Value) error {
	bs := dec.buf[:8]
	if err := readAtLeast(dec, bs, 8); err != nil {
		return err
	}
	f1 := math.Float64frombits(dec.order.Uint64(bs))
	if err := readAtLeast(dec, bs, 8); err != nil {
		return err
	}
	v.SetComplex(complex(f1, math.Float64frombits(dec.order.Uint64(bs))))
	return nil
}
示例#15
0
func parseComplexArray(buf []byte, offset, end int) (interface{}, int, error) {
	length := end - offset
	cArr := make([]complex128, 0, length/16)
	for ; offset < end; offset += 16 {
		bitsReal := binary.LittleEndian.Uint64(buf[offset : offset+8])
		bitsImag := binary.LittleEndian.Uint64(buf[offset+8 : offset+16])
		cArr = append(cArr, complex(math.Float64frombits(bitsReal), math.Float64frombits(bitsImag)))
	}
	if len(cArr) == 1 {
		return cArr[0], offset, nil
	}
	return cArr, offset, nil
}
示例#16
0
func complex128Decoder(dec *decoder, p unsafe.Pointer) error {
	bs := dec.buf[:8]
	if err := readAtLeast(dec, bs, 8); err != nil {
		return err
	}
	f1 := math.Float64frombits(dec.order.Uint64(bs))
	if err := readAtLeast(dec, bs, 8); err != nil {
		return err
	}
	v := (*complex128)(p)
	*v = complex(f1, math.Float64frombits(dec.order.Uint64(bs)))
	return nil
}
示例#17
0
func (p *Parser) ReadFloat64(value *float64) *Parser {
	bufFloat64 := make([]byte, 8)
	if bufFloat64 = p.buffer.Next(8); len(bufFloat64) < 8 {
		p.err = errors.New("Not enough bytes in buffer")
		return p
	}

	if p.Endian() == BigEndian {
		(*value) = math.Float64frombits(binary.BigEndian.Uint64(bufFloat64))
	} else {
		(*value) = math.Float64frombits(binary.LittleEndian.Uint64(bufFloat64))
	}

	return p
}
示例#18
0
文件: io.go 项目: rawlingsj/gofabric8
// UnmarshalBinary decodes the binary form into the receiver.
// It panics if the receiver is a non-zero Dense matrix.
//
// See MarshalBinary for the on-disk layout.
//
// Limited checks on the validity of the binary input are performed:
//  - matrix.ErrShape is returned if the number of rows or columns is negative,
//  - an error is returned if the resulting Dense matrix is too
//  big for the current architecture (e.g. a 16GB matrix written by a
//  64b application and read back from a 32b application.)
// UnmarshalBinary does not limit the size of the unmarshaled matrix, and so
// it should not be used on untrusted data.
func (m *Dense) UnmarshalBinary(data []byte) error {
	if !m.isZero() {
		panic("mat64: unmarshal into non-zero matrix")
	}

	if len(data) < 2*sizeInt64 {
		return errTooSmall
	}

	p := 0
	rows := int64(binary.LittleEndian.Uint64(data[p : p+sizeInt64]))
	p += sizeInt64
	cols := int64(binary.LittleEndian.Uint64(data[p : p+sizeInt64]))
	p += sizeInt64
	if rows < 0 || cols < 0 {
		return errBadSize
	}

	size := rows * cols
	if int(size) < 0 || size > maxLen {
		return errTooBig
	}

	if len(data) != int(size)*sizeFloat64+2*sizeInt64 {
		return errBadBuffer
	}

	m.reuseAs(int(rows), int(cols))
	for i := range m.mat.Data {
		m.mat.Data[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[p : p+sizeFloat64]))
		p += sizeFloat64
	}

	return nil
}
示例#19
0
func word64_Set(p word64, o *Buffer, x uint64) {
	t := p.v.Type().Elem()
	switch t {
	case int64Type:
		if len(o.int64s) == 0 {
			o.int64s = make([]int64, uint64PoolSize)
		}
		o.int64s[0] = int64(x)
		p.v.Set(reflect.ValueOf(&o.int64s[0]))
		o.int64s = o.int64s[1:]
		return
	case uint64Type:
		if len(o.uint64s) == 0 {
			o.uint64s = make([]uint64, uint64PoolSize)
		}
		o.uint64s[0] = x
		p.v.Set(reflect.ValueOf(&o.uint64s[0]))
		o.uint64s = o.uint64s[1:]
		return
	case float64Type:
		if len(o.float64s) == 0 {
			o.float64s = make([]float64, uint64PoolSize)
		}
		o.float64s[0] = math.Float64frombits(x)
		p.v.Set(reflect.ValueOf(&o.float64s[0]))
		o.float64s = o.float64s[1:]
		return
	}
	panic("unreachable")
}
示例#20
0
// turn uint64 op into float64 op
func fop(f func(x, y uint64) uint64) func(x, y float64) float64 {
	return func(x, y float64) float64 {
		bx := math.Float64bits(x)
		by := math.Float64bits(y)
		return math.Float64frombits(f(bx, by))
	}
}
示例#21
0
func decode(b []byte, t uint16) driver.Value {
	switch t {
	case typeBool:
		if len(b) >= 1 && b[0] != 0 {
			return true
		}
		return false
	case typeBlob:
		return b
	case typeVarchar, typeText, typeAscii:
		return b
	case typeInt:
		return int64(int32(binary.BigEndian.Uint32(b)))
	case typeBigInt:
		return int64(binary.BigEndian.Uint64(b))
	case typeFloat:
		return float64(math.Float32frombits(binary.BigEndian.Uint32(b)))
	case typeDouble:
		return math.Float64frombits(binary.BigEndian.Uint64(b))
	case typeTimestamp:
		t := int64(binary.BigEndian.Uint64(b))
		sec := t / 1000
		nsec := (t - sec*1000) * 1000000
		return time.Unix(sec, nsec)
	case typeUUID, typeTimeUUID:
		return uuid.FromBytes(b)
	default:
		panic("unsupported type")
	}
	return b
}
示例#22
0
// deserializeVertex deserializes a dvid.GraphVertex (compression turned off for now)
func (db *GraphKeyValueDB) deserializeVertex(vertexdata []byte) (dvid.GraphVertex, error) {
	// create vertex to be returned
	vert := dvid.GraphVertex{GraphElement: &dvid.GraphElement{}}

	// if vertexdata is empty return an error
	if vertexdata == nil || len(vertexdata) == 0 {
		return vert, fmt.Errorf("Vertex data empty")
	}

	// boilerplate deserialization from DVID
	data, _, err := dvid.DeserializeData(vertexdata, true)
	if err != nil {
		return vert, err
	}

	// load data from vertex (vertex id, vertex weight, num vertices,
	// vertex array, num properties, property array

	// load vertex id
	start := 0
	vert.Id = dvid.VertexID(binary.LittleEndian.Uint64(data[start:]))
	start += 8

	// load vertex weight
	floatbits := binary.LittleEndian.Uint64(data[start:])
	vert.Weight = math.Float64frombits(floatbits)
	start += 8

	// number of vertices
	count := binary.LittleEndian.Uint64(data[start:])
	start += 8

	vert.Vertices = make([]dvid.VertexID, count, count)
	// load vertices
	for i := uint64(0); i < count; i++ {
		vert.Vertices[i] = dvid.VertexID(binary.LittleEndian.Uint64(data[start:]))
		start += 8
	}

	// number of properties
	vert.Properties = make(dvid.ElementProperties)
	count = binary.LittleEndian.Uint64(data[start:])
	start += 8

	// create property strings
	for i := uint64(0); i < count; i++ {
		propertyname := string("")
		// null separated strings
		for data[start] != byte(0) {
			propertyname += string(data[start])
			start += 1
		}
		vert.Properties[propertyname] = struct{}{}

		// increment beyond null
		start += 1
	}

	return vert, nil
}
示例#23
0
文件: read_bytes.go 项目: kgrz/msgp
// ReadFloat64Bytes tries to read a float64
// from 'b' and return the value and the remaining bytes.
// Possible errors:
// - ErrShortBytes (too few bytes)
// - TypeError{} (not a float64)
func ReadFloat64Bytes(b []byte) (f float64, o []byte, err error) {
	if len(b) < 9 {
		if len(b) >= 5 && b[0] == mfloat32 {
			var tf float32
			tf, o, err = ReadFloat32Bytes(b)
			f = float64(tf)
			return
		}
		err = ErrShortBytes
		return
	}

	if b[0] != mfloat64 {
		if b[0] == mfloat32 {
			var tf float32
			tf, o, err = ReadFloat32Bytes(b)
			f = float64(tf)
			return
		}
		err = badPrefix(Float64Type, b[0])
		return
	}

	f = math.Float64frombits(getMuint64(b))
	o = b[9:]
	return
}
示例#24
0
// ReadFloat64 reads a float64 from the reader.
// (If the value on the wire is encoded as a float32,
// it will be up-cast to a float64.)
func (m *Reader) ReadFloat64() (f float64, err error) {
	var p []byte
	p, err = m.r.Peek(9)
	if err != nil {
		// we'll allow a coversion from float32 to float64,
		// since we don't lose any precision
		if err == io.EOF && len(p) > 0 && p[0] == mfloat32 {
			ef, err := m.ReadFloat32()
			return float64(ef), err
		}
		return
	}
	if p[0] != mfloat64 {
		// see above
		if p[0] == mfloat32 {
			ef, err := m.ReadFloat32()
			return float64(ef), err
		}
		err = badPrefix(Float64Type, p[0])
		return
	}
	f = math.Float64frombits(getMuint64(p))
	_, err = m.r.Skip(9)
	return
}
示例#25
0
// sampleValueAtIndex implements chunkIterator.
func (it *deltaEncodedChunkIterator) sampleValueAtIndex(idx int) clientmodel.SampleValue {
	offset := deltaHeaderBytes + idx*int(it.tBytes+it.vBytes) + int(it.tBytes)

	if it.isInt {
		switch it.vBytes {
		case d0:
			return it.baseV
		case d1:
			return it.baseV + clientmodel.SampleValue(int8(it.c[offset]))
		case d2:
			return it.baseV + clientmodel.SampleValue(int16(binary.LittleEndian.Uint16(it.c[offset:])))
		case d4:
			return it.baseV + clientmodel.SampleValue(int32(binary.LittleEndian.Uint32(it.c[offset:])))
		// No d8 for ints.
		default:
			panic("Invalid number of bytes for integer delta")
		}
	} else {
		switch it.vBytes {
		case d4:
			return it.baseV + clientmodel.SampleValue(math.Float32frombits(binary.LittleEndian.Uint32(it.c[offset:])))
		case d8:
			// Take absolute value for d8.
			return clientmodel.SampleValue(math.Float64frombits(binary.LittleEndian.Uint64(it.c[offset:])))
		default:
			panic("Invalid number of bytes for floating point delta")
		}
	}
}
示例#26
0
文件: value.go 项目: mschoch/otto
func init() {
	__NaN__ = math.NaN()
	__PositiveInfinity__ = math.Inf(+1)
	__NegativeInfinity__ = math.Inf(-1)
	__PositiveZero__ = 0
	__NegativeZero__ = math.Float64frombits(0 | (1 << 63))
}
示例#27
0
文件: simple.go 项目: MG-RAST/Shock
func (d *simpleDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
	switch d.bd {
	case simpleVdFloat32:
		f = float64(math.Float32frombits(d.r.readUint32()))
	case simpleVdFloat64:
		f = math.Float64frombits(d.r.readUint64())
	default:
		if d.bd >= simpleVdPosInt1 && d.bd <= simpleVdNegInt8 {
			_, i, _ := d.decIntAny()
			f = float64(i)
		} else {
			decErr("Float only valid from float32/64: Invalid descriptor: %v", d.bd)
		}
	}
	// check overflow (logic adapted from std pkg reflect/value.go OverflowFloat()
	if chkOverflow32 {
		f2 := f
		if f2 < 0 {
			f2 = -f
		}
		if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 {
			decErr("Overflow float32 value: %v", f2)
		}
	}
	return
}
示例#28
0
func readFixedType(ti *typeInfo, r *tdsBuffer) (res interface{}) {
	r.ReadFull(ti.Buffer)
	buf := ti.Buffer
	switch ti.TypeId {
	case typeNull:
		return nil
	case typeInt1:
		return int64(buf[0])
	case typeBit:
		return buf[0] != 0
	case typeInt2:
		return int64(int16(binary.LittleEndian.Uint16(buf)))
	case typeInt4:
		return int64(int32(binary.LittleEndian.Uint32(buf)))
	case typeDateTim4:
		return decodeDateTim4(buf)
	case typeFlt4:
		return math.Float32frombits(binary.LittleEndian.Uint32(buf))
	case typeMoney4:
		return decodeMoney4(buf)
	case typeMoney:
		return decodeMoney(buf)
	case typeDateTime:
		return decodeDateTime(buf)
	case typeFlt8:
		return math.Float64frombits(binary.LittleEndian.Uint64(buf))
	case typeInt8:
		return int64(binary.LittleEndian.Uint64(buf))
	default:
		badStreamPanicf("Invalid typeid")
	}
	panic("shoulnd't get here")
}
示例#29
0
文件: gauges.go 项目: Netflix/rend
func getAllGauges() ([]IntMetric, []FloatMetric) {
	numIDs := int(atomic.LoadUint32(curIntGaugeID))
	retint := make([]IntMetric, numIDs)

	for i := 0; i < numIDs; i++ {
		retint[i] = IntMetric{
			Name: intgnames[i],
			Val:  atomic.LoadUint64(&intgauges[i]),
			Tgs:  intgtags[i],
		}
	}

	numIDs = int(atomic.LoadUint32(curFloatGaugeID))
	retfloat := make([]FloatMetric, numIDs)

	for i := 0; i < numIDs; i++ {
		// The int64 bit pattern of the float value needs to be converted back
		// into a float64 here. This is a literal reinterpretation of the same
		// exact bits.
		intval := atomic.LoadUint64(&floatgauges[i])

		retfloat[i] = FloatMetric{
			Name: floatgnames[i],
			Val:  math.Float64frombits(intval),
			Tgs:  floatgtags[i],
		}
	}

	return retint, retfloat
}
示例#30
0
文件: io.go 项目: rawlingsj/gofabric8
// UnmarshalBinary decodes the binary form into the receiver.
// It panics if the receiver is a non-zero Vector.
//
// See MarshalBinary for the on-disk layout.
//
// Limited checks on the validity of the binary input are performed:
//  - matrix.ErrShape is returned if the number of rows is negative,
//  - an error is returned if the resulting Vector is too
//  big for the current architecture (e.g. a 16GB vector written by a
//  64b application and read back from a 32b application.)
// UnmarshalBinary does not limit the size of the unmarshaled vector, and so
// it should not be used on untrusted data.
func (v *Vector) UnmarshalBinary(data []byte) error {
	if !v.isZero() {
		panic("mat64: unmarshal into non-zero vector")
	}

	p := 0
	n := int64(binary.LittleEndian.Uint64(data[p : p+sizeInt64]))
	p += sizeInt64
	if n < 0 {
		return errBadSize
	}
	if n > maxLen {
		return errTooBig
	}
	if len(data) != int(n)*sizeFloat64+sizeInt64 {
		return errBadBuffer
	}

	v.reuseAs(int(n))
	for i := range v.mat.Data {
		v.mat.Data[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[p : p+sizeFloat64]))
		p += sizeFloat64
	}

	return nil
}