Skip to content

Commit

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

// Encoder writes BSON values to an output stream.
Expand Down Expand Up @@ -55,6 +56,11 @@ func (e *Encoder) marshal(v any) error {
e.buf.Write([]byte(v))
e.buf.WriteByte(0)

case time.Time:
var b [8]byte
binary.LittleEndian.PutUint64(b[:], uint64(v.UnixMilli()))
e.buf.Write(b[:])

case int32:
var b [4]byte
binary.LittleEndian.PutUint32(b[:], uint32(v))
Expand Down
25 changes: 25 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"math"
"testing"
"time"
)

func TestEncode(t *testing.T) {
Expand Down Expand Up @@ -92,3 +93,27 @@ func TestEncodeNumbers(t *testing.T) {
wantBytes(t, buf.Bytes(), "713d0ad7a3104540")
buf.Reset()
}

func TestEncodeTime(t *testing.T) {
var err error
var buf bytes.Buffer
enc := NewEncoder(&buf)

var ts time.Time
err = enc.Encode(ts)
mustOk(t, err)
wantBytes(t, buf.Bytes(), "0028d3ed7cc7ffff")
buf.Reset()

ts = time.Unix(0, 0)
err = enc.Encode(ts)
mustOk(t, err)
wantBytes(t, buf.Bytes(), "0000000000000000")
buf.Reset()

ts = time.Date(2023, 8, 17, 10, 20, 30, 0, time.UTC)
err = enc.Encode(ts)
mustOk(t, err)
wantBytes(t, buf.Bytes(), "b0cd02038a010000")
buf.Reset()
}

0 comments on commit 74f64ea

Please sign in to comment.