Skip to content

Commit

Permalink
ua: decode types that convert to time.Time
Browse files Browse the repository at this point in the history
The codec does not handle types that can be converted to time.Time
correctly since it is too strict in determining what a time.Time type
is. This patch relaxes this by checking if a type can be converted to
time.Time.

Fixes #633
  • Loading branch information
magiconair committed Feb 1, 2023
1 parent 5640a5d commit 624658a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
4 changes: 2 additions & 2 deletions ua/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func isBinaryDecoder(val reflect.Value) bool {
}

func isTime(val reflect.Value) bool {
return val.Type() == timeType
return val.CanConvert(timeType)
}

type BinaryDecoder interface {
Expand All @@ -49,7 +49,7 @@ func decode(b []byte, val reflect.Value, name string) (n int, err error) {
v := val.Interface().(BinaryDecoder)
return v.Decode(b)
case isTime(val):
val.Set(reflect.ValueOf(buf.ReadTime()))
val.Set(reflect.ValueOf(buf.ReadTime()).Convert(val.Type()))
default:
// fmt.Printf("decode: %s is a %s\n", name, val.Kind())
switch val.Kind() {
Expand Down
13 changes: 13 additions & 0 deletions ua/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ type C struct {
B [2]byte
}

type Timestamp time.Time

func TestCodec(t *testing.T) {

tests := []struct {
name string
v interface{}
Expand Down Expand Up @@ -205,6 +208,16 @@ func TestCodec(t *testing.T) {
v: &struct{ V time.Time }{time.Time{}},
b: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
},
{
name: "DateTime as Timestamp",
v: &struct{ V Timestamp }{Timestamp(time.Date(2018, time.August, 10, 23, 0, 0, 0, time.UTC))},
b: []byte{0x00, 0x98, 0x67, 0xdd, 0xfd, 0x30, 0xd4, 0x01},
},
{
name: "DateTimeZero as Timestamp",
v: &struct{ V Timestamp }{Timestamp{}},
b: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
},
{
name: "[]uint32==nil",
v: &struct{ V []uint32 }{},
Expand Down
2 changes: 1 addition & 1 deletion ua/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func encode(val reflect.Value, name string) ([]byte, error) {
return v.Encode()

case isTime(val):
buf.WriteTime(val.Interface().(time.Time))
buf.WriteTime(val.Convert(timeType).Interface().(time.Time))

default:
switch val.Kind() {
Expand Down

0 comments on commit 624658a

Please sign in to comment.