From dee495f093e2defa15806a5c45cd6cc37fea7e0f Mon Sep 17 00:00:00 2001 From: Sergio Moya Date: Fri, 16 Dec 2016 13:35:55 +0100 Subject: [PATCH] Encoding/Decoding time.Duration to/from int64 --- bson/decode.go | 7 ++++++- bson/encode.go | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/bson/decode.go b/bson/decode.go index 7c2d8416a..cf564385f 100644 --- a/bson/decode.go +++ b/bson/decode.go @@ -538,7 +538,12 @@ func (d *decoder) readElemTo(out reflect.Value, kind byte) (good bool) { case 0x11: // Mongo-specific timestamp in = MongoTimestamp(d.readInt64()) case 0x12: // Int64 - in = d.readInt64() + switch out.Type() { + case typeTimeDuration: + in = time.Duration(time.Duration(d.readInt64()) * time.Millisecond) + default: + in = d.readInt64() + } case 0x13: // Decimal128 in = Decimal128{ l: uint64(d.readInt64()), diff --git a/bson/encode.go b/bson/encode.go index add39e865..08f60df0b 100644 --- a/bson/encode.go +++ b/bson/encode.go @@ -54,6 +54,7 @@ var ( typeTime = reflect.TypeOf(time.Time{}) typeString = reflect.TypeOf("") typeJSONNumber = reflect.TypeOf(json.Number("")) + typeTimeDuration = reflect.TypeOf(time.Duration(0)) ) const itoaCacheSize = 32 @@ -325,7 +326,11 @@ func (e *encoder) addElem(name string, v reflect.Value, minSize bool) { } else { e.addElemName(0xFF, name) } + case typeTimeDuration: + // Stored as int64 + e.addElemName(0x12, name) + e.addInt64(int64(v.Int()/1e6)) default: i := v.Int() if (minSize || v.Type().Kind() != reflect.Int64) && i >= math.MinInt32 && i <= math.MaxInt32 {