diff --git a/encode.go b/encode.go index 7925941..afc35ed 100644 --- a/encode.go +++ b/encode.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "fmt" "io" + "math" ) // Encoder writes BSON values to an output stream. @@ -64,6 +65,11 @@ func (e *Encoder) marshal(v any) error { binary.LittleEndian.PutUint64(b[:], uint64(v)) e.buf.Write(b[:]) + case float64: + var b [8]byte + binary.LittleEndian.PutUint64(b[:], math.Float64bits(float64(v))) + e.buf.Write(b[:]) + case bool: var b [1]byte if v { diff --git a/encode_test.go b/encode_test.go index 587bd9c..e0c2538 100644 --- a/encode_test.go +++ b/encode_test.go @@ -2,6 +2,7 @@ package bson import ( "bytes" + "math" "testing" ) @@ -56,3 +57,38 @@ func TestEncodeString(t *testing.T) { wantBytes(t, buf.Bytes(), "0100000000") buf.Reset() } + +func TestEncodeNumbers(t *testing.T) { + var buf bytes.Buffer + enc := NewEncoder(&buf) + + err := enc.Encode(float64(3.14159)) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "6e861bf0f9210940") + buf.Reset() + + err = enc.Encode(float64(0)) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "0000000000000000") + buf.Reset() + + err = enc.Encode(math.NaN()) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "010000000000f87f") + buf.Reset() + + err = enc.Encode(math.Inf(+1)) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "000000000000f07f") + buf.Reset() + + err = enc.Encode(math.Inf(-1)) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "000000000000f0ff") + buf.Reset() + + err = enc.Encode(42.13) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "713d0ad7a3104540") + buf.Reset() +}