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 4c61aff
Show file tree
Hide file tree
Showing 2 changed files with 14 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
8 changes: 8 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,13 @@ func (e *encoder) addElem(name string, v reflect.Value, minSize bool) {
} else {
e.addElemName(0xFF, name)
}
case typeTimeDuration:
//panic("STOP!!!")
// Stored as int64
e.addElemName(0x12, name)

//s.Unix()*1000 + int64(s.Nanosecond()/1e6)
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 Expand Up @@ -434,6 +441,7 @@ func (e *encoder) addElem(name string, v reflect.Value, minSize bool) {
}

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

0 comments on commit 4c61aff

Please sign in to comment.