~sircmpwn/go-bare

88a9d80d592ab5f0280e7a428813420a1aa25281 — Drew DeVault 3 months ago e668818
reader, writer: error on NaN
3 files changed, 25 insertions(+), 2 deletions(-)

M reader.go
M writer.go
M writer_test.go
M reader.go => reader.go +10 -2
@@ 110,12 110,20 @@ func (r *Reader) ReadI64() (int64, error) {

func (r *Reader) ReadF32() (float32, error) {
	u, err := r.ReadU32()
	return math.Float32frombits(u), err
	f := math.Float32frombits(u)
	if math.IsNaN(float64(f)) {
		return 0.0, fmt.Errorf("NaN is not permitted in BARE floats")
	}
	return f, err
}

func (r *Reader) ReadF64() (float64, error) {
	u, err := r.ReadU64()
	return math.Float64frombits(u), err
	f := math.Float64frombits(u)
	if math.IsNaN(f) {
		return 0.0, fmt.Errorf("NaN is not permitted in BARE floats")
	}
	return f, err
}

func (r *Reader) ReadBool() (bool, error) {

M writer.go => writer.go +8 -0
@@ 2,7 2,9 @@ package bare

import (
	"encoding/binary"
	"fmt"
	"io"
	"math"
)

// A Writer for BARE primitive types.


@@ 62,10 64,16 @@ func (w *Writer) WriteI64(i int64) error {
}

func (w *Writer) WriteF32(f float32) error {
	if math.IsNaN(float64(f)) {
		return fmt.Errorf("NaN is not permitted in BARE floats")
	}
	return binary.Write(w.base, binary.LittleEndian, f)
}

func (w *Writer) WriteF64(f float64) error {
	if math.IsNaN(f) {
		return fmt.Errorf("NaN is not permitted in BARE floats")
	}
	return binary.Write(w.base, binary.LittleEndian, f)
}


M writer_test.go => writer_test.go +7 -0
@@ 2,6 2,7 @@ package bare

import (
	"bytes"
	"math"
	"testing"

	"github.com/stretchr/testify/assert"


@@ 99,6 100,9 @@ func TestWriteF32(t *testing.T) {
	err := w.WriteF32(float32(1337.42))
	assert.Nil(t, err)
	assert.Equal(t, []byte{0x71, 0x2D, 0xA7, 0x44}, b.Bytes())

	err = w.WriteF32(float32(math.NaN()))
	assert.NotNil(t, err)
}

func TestWriteF64(t *testing.T) {


@@ 107,6 111,9 @@ func TestWriteF64(t *testing.T) {
	err := w.WriteF64(float64(133713371337.42424242))
	assert.Nil(t, err)
	assert.Equal(t, []byte{0x9B, 0x6C, 0xC9, 0x20, 0xF0, 0x21, 0x3F, 0x42}, b.Bytes())

	err = w.WriteF64(math.NaN())
	assert.NotNil(t, err)
}

func TestWriteBool(t *testing.T) {