github.com/philpearl/plenc@v0.0.15/plenccodec/float_test.go (about) 1 package plenccodec_test 2 3 import ( 4 "math" 5 "strconv" 6 "testing" 7 "unsafe" 8 9 "github.com/philpearl/plenc" 10 "github.com/philpearl/plenc/plenccodec" 11 ) 12 13 func TestFloat32(t *testing.T) { 14 c := plenccodec.Float32Codec{} 15 tests := []float32{0, 1, -1, 3.14, math.MaxFloat32, math.SmallestNonzeroFloat32} 16 17 for _, test := range tests { 18 t.Run(strconv.FormatFloat(float64(test), 'g', -1, 32), func(t *testing.T) { 19 l := c.Size(unsafe.Pointer(&test), nil) 20 b := make([]byte, 0, l) 21 data := c.Append(b, unsafe.Pointer(&test), nil) 22 var actual float32 23 n, err := c.Read(data, unsafe.Pointer(&actual), c.WireType()) 24 if err != nil { 25 t.Fatal(err) 26 } 27 if n != l { 28 t.Errorf("lengths differ %d %d", l, n) 29 } 30 if actual != test { 31 t.Errorf("values differ. actual %f, expected %f", actual, test) 32 } 33 }) 34 35 t.Run(strconv.FormatFloat(float64(test), 'g', -1, 32)+"_marshal", func(t *testing.T) { 36 data, err := plenc.Marshal(nil, &test) 37 if err != nil { 38 t.Fatal(err) 39 } 40 var out float32 41 if err := plenc.Unmarshal(data, &out); err != nil { 42 t.Fatal(err) 43 } 44 if test != out { 45 t.Errorf("Result incorrect for %f - got %f", test, out) 46 } 47 }) 48 } 49 } 50 51 func TestFloat64(t *testing.T) { 52 c := plenccodec.Float64Codec{} 53 tests := []float64{0, 1, -1, 3.14, math.MaxFloat32, math.SmallestNonzeroFloat32, math.MaxFloat64, math.SmallestNonzeroFloat64} 54 55 for _, test := range tests { 56 t.Run(strconv.FormatFloat(float64(test), 'g', -1, 64), func(t *testing.T) { 57 l := c.Size(unsafe.Pointer(&test), nil) 58 b := make([]byte, 0, l) 59 data := c.Append(b, unsafe.Pointer(&test), nil) 60 var actual float64 61 n, err := c.Read(data, unsafe.Pointer(&actual), c.WireType()) 62 if err != nil { 63 t.Fatal(err) 64 } 65 if n != l { 66 t.Errorf("lengths differ %d %d", l, n) 67 } 68 if actual != test { 69 t.Errorf("values differ. actual %f, expected %f", actual, test) 70 } 71 }) 72 t.Run(strconv.FormatFloat(float64(test), 'g', -1, 64)+"_marshal", func(t *testing.T) { 73 data, err := plenc.Marshal(nil, &test) 74 if err != nil { 75 t.Fatal(err) 76 } 77 var out float64 78 if err := plenc.Unmarshal(data, &out); err != nil { 79 t.Fatal(err) 80 } 81 if test != out { 82 t.Errorf("Result incorrect for %f - got %f", test, out) 83 } 84 }) 85 } 86 }