OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package cmpbin |
| 6 |
| 7 import ( |
| 8 "encoding/binary" |
| 9 "io" |
| 10 "math" |
| 11 ) |
| 12 |
| 13 // WriteFloat64 writes a memcmp-sortable float to buf. It returns the number |
| 14 // of bytes written (8, unless an error occurs), and any write error |
| 15 // encountered. |
| 16 func WriteFloat64(buf io.Writer, v float64) (n int, err error) { |
| 17 bits := math.Float64bits(v) |
| 18 bits = bits ^ (-(bits >> 63) | (1 << 63)) |
| 19 data := make([]byte, 8) |
| 20 binary.BigEndian.PutUint64(data, bits) |
| 21 return buf.Write(data) |
| 22 } |
| 23 |
| 24 // ReadFloat64 reads a memcmp-sortable float from buf (as written by |
| 25 // WriteFloat64). It also returns the number of bytes read (8, unless an error |
| 26 // occurs), and any read error encountered. |
| 27 func ReadFloat64(buf io.Reader) (ret float64, n int, err error) { |
| 28 // byte-ordered floats http://stereopsis.com/radix.html |
| 29 data := make([]byte, 8) |
| 30 if n, err = buf.Read(data); err != nil { |
| 31 return |
| 32 } |
| 33 bits := binary.BigEndian.Uint64(data) |
| 34 ret = math.Float64frombits(bits ^ (((bits >> 63) - 1) | (1 << 63))) |
| 35 return |
| 36 } |
OLD | NEW |