Skip to content

Commit 4c61aff

Browse files
committed
Encoding/Decoding time.Duration to/from int64
1 parent 9a2573d commit 4c61aff

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

bson/decode.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -538,7 +538,12 @@ func (d *decoder) readElemTo(out reflect.Value, kind byte) (good bool) {
538538
case 0x11: // Mongo-specific timestamp
539539
in = MongoTimestamp(d.readInt64())
540540
case 0x12: // Int64
541-
in = d.readInt64()
541+
switch out.Type() {
542+
case typeTimeDuration:
543+
in = time.Duration(time.Duration(d.readInt64()) * time.Millisecond)
544+
default:
545+
in = d.readInt64()
546+
}
542547
case 0x13: // Decimal128
543548
in = Decimal128{
544549
l: uint64(d.readInt64()),

bson/encode.go

+8
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ var (
5454
typeTime = reflect.TypeOf(time.Time{})
5555
typeString = reflect.TypeOf("")
5656
typeJSONNumber = reflect.TypeOf(json.Number(""))
57+
typeTimeDuration = reflect.TypeOf(time.Duration(0))
5758
)
5859

5960
const itoaCacheSize = 32
@@ -325,7 +326,13 @@ func (e *encoder) addElem(name string, v reflect.Value, minSize bool) {
325326
} else {
326327
e.addElemName(0xFF, name)
327328
}
329+
case typeTimeDuration:
330+
//panic("STOP!!!")
331+
// Stored as int64
332+
e.addElemName(0x12, name)
328333

334+
//s.Unix()*1000 + int64(s.Nanosecond()/1e6)
335+
e.addInt64(int64(v.Int()/1e6))
329336
default:
330337
i := v.Int()
331338
if (minSize || v.Type().Kind() != reflect.Int64) && i >= math.MinInt32 && i <= math.MaxInt32 {
@@ -434,6 +441,7 @@ func (e *encoder) addElem(name string, v reflect.Value, minSize bool) {
434441
}
435442

436443
case time.Time:
444+
//panic("TIME!")
437445
// MongoDB handles timestamps as milliseconds.
438446
e.addElemName(0x09, name)
439447
e.addInt64(s.Unix()*1000 + int64(s.Nanosecond()/1e6))

0 commit comments

Comments
 (0)