Skip to content

Commit f4993c5

Browse files
authored
Merge pull request #3 from smoya/feature/timeDuration
Encoding/Decoding time.Duration to/from int64
2 parents 546e6f1 + dee495f commit f4993c5

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

bson/decode.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -601,7 +601,12 @@ func (d *decoder) readElemTo(out reflect.Value, kind byte) (good bool) {
601601
case 0x11: // Mongo-specific timestamp
602602
in = MongoTimestamp(d.readInt64())
603603
case 0x12: // Int64
604-
in = d.readInt64()
604+
switch out.Type() {
605+
case typeTimeDuration:
606+
in = time.Duration(time.Duration(d.readInt64()) * time.Millisecond)
607+
default:
608+
in = d.readInt64()
609+
}
605610
case 0x13: // Decimal128
606611
in = Decimal128{
607612
l: uint64(d.readInt64()),

bson/encode.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ var (
5555
typeTime = reflect.TypeOf(time.Time{})
5656
typeString = reflect.TypeOf("")
5757
typeJSONNumber = reflect.TypeOf(json.Number(""))
58+
typeTimeDuration = reflect.TypeOf(time.Duration(0))
5859
)
5960

6061
const itoaCacheSize = 32
@@ -326,7 +327,11 @@ func (e *encoder) addElem(name string, v reflect.Value, minSize bool) {
326327
} else {
327328
e.addElemName(0xFF, name)
328329
}
330+
case typeTimeDuration:
331+
// Stored as int64
332+
e.addElemName(0x12, name)
329333

334+
e.addInt64(int64(v.Int()/1e6))
330335
default:
331336
i := v.Int()
332337
if (minSize || v.Type().Kind() != reflect.Int64) && i >= math.MinInt32 && i <= math.MaxInt32 {

0 commit comments

Comments
 (0)