forked from vmihailenco/msgpack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
59 lines (51 loc) · 1.07 KB
/
time.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package msgpack
import (
"fmt"
"reflect"
"time"
)
var (
timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
)
func init() {
Register(timeType, encodeTimeValue, decodeTimeValue)
}
func (e *Encoder) EncodeTime(tm time.Time) error {
if err := e.w.WriteByte(0x92); err != nil {
return err
}
if err := e.EncodeInt64(tm.Unix()); err != nil {
return err
}
return e.EncodeInt(tm.Nanosecond())
}
func (d *Decoder) DecodeTime() (time.Time, error) {
b, err := d.r.ReadByte()
if err != nil {
return time.Time{}, err
}
if b != 0x92 {
return time.Time{}, fmt.Errorf("msgpack: invalid code %x decoding time", b)
}
sec, err := d.DecodeInt64()
if err != nil {
return time.Time{}, err
}
nsec, err := d.DecodeInt64()
if err != nil {
return time.Time{}, err
}
return time.Unix(sec, nsec), nil
}
func encodeTimeValue(e *Encoder, v reflect.Value) error {
tm := v.Interface().(time.Time)
return e.EncodeTime(tm)
}
func decodeTimeValue(d *Decoder, v reflect.Value) error {
tm, err := d.DecodeTime()
if err != nil {
return err
}
v.Set(reflect.ValueOf(tm))
return nil
}