Skip to content

Commit

Permalink
Encoding/Decoding time.Duration to/from int64
Browse files Browse the repository at this point in the history
  • Loading branch information
smoya committed Dec 16, 2016
1 parent 9a2573d commit dee495f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 6 additions & 1 deletion bson/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
5 changes: 5 additions & 0 deletions bson/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit dee495f

Please sign in to comment.