Skip to content

Commit

Permalink
Add double (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Aug 15, 2023
1 parent a53b7f5 commit 14c138a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
6 changes: 6 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/binary"
"fmt"
"io"
"math"
)

// Encoder writes BSON values to an output stream.
Expand Down Expand Up @@ -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 {
Expand Down
36 changes: 36 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bson

import (
"bytes"
"math"
"testing"
)

Expand Down Expand Up @@ -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()
}

0 comments on commit 14c138a

Please sign in to comment.