From 2ff7476b4ac47e76c64bf9667434f06e680643b5 Mon Sep 17 00:00:00 2001 From: Benbebop Date: Thu, 10 Oct 2024 20:54:33 -0600 Subject: [PATCH] Allow unmarshalling LocalTime to time.Duration --- localtime.go | 5 +++++ types.go | 1 + unmarshaler.go | 6 ++++++ unmarshaler_test.go | 14 ++++++++++++++ 4 files changed, 26 insertions(+) diff --git a/localtime.go b/localtime.go index a856bfdb..1090f054 100644 --- a/localtime.go +++ b/localtime.go @@ -50,6 +50,11 @@ type LocalTime struct { Precision int // Number of digits to display for Nanosecond. } +// AsDuration converts d into a duration +func (d LocalTime) AsDuration() time.Duration { + return time.Duration(d.Hour)*time.Hour + time.Duration(d.Minute)*time.Minute + time.Duration(d.Second)*time.Second + time.Duration(d.Nanosecond)*time.Nanosecond +} + // String returns RFC 3339 representation of d. // If d.Nanosecond and d.Precision are zero, the time won't have a nanosecond // component. If d.Nanosecond > 0 but d.Precision = 0, then the minimum number diff --git a/types.go b/types.go index 3c6b8fe5..2c946878 100644 --- a/types.go +++ b/types.go @@ -7,6 +7,7 @@ import ( ) var timeType = reflect.TypeOf((*time.Time)(nil)).Elem() +var durationType = reflect.TypeOf((*time.Duration)(nil)).Elem() var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() var mapStringInterfaceType = reflect.TypeOf(map[string]interface{}(nil)) diff --git a/unmarshaler.go b/unmarshaler.go index c3df8bee..2266c421 100644 --- a/unmarshaler.go +++ b/unmarshaler.go @@ -852,6 +852,12 @@ func (d *decoder) unmarshalLocalTime(value *unstable.Node, v reflect.Value) erro return unstable.NewParserError(rest, "extra characters at the end of a local time") } + if v.Type() == durationType { + cast := lt.AsDuration() + v.Set(reflect.ValueOf(cast)) + return nil + } + v.Set(reflect.ValueOf(lt)) return nil } diff --git a/unmarshaler_test.go b/unmarshaler_test.go index 3cbd81d1..be35bf5a 100644 --- a/unmarshaler_test.go +++ b/unmarshaler_test.go @@ -603,6 +603,20 @@ foo = "bar"`, } }, }, + { + desc: "local-time into duration", + input: `a = 12:08:05.666666666`, + gen: func() test { + var v map[string]time.Duration + + return test{ + target: &v, + expected: &map[string]time.Duration{ + "a": 12*time.Hour + 8*time.Minute + 5*time.Second + 666666666*time.Nanosecond, //toml.LocalTime{Hour: 12, Minute: 8, Second: 5, Nanosecond: 666666666, Precision: 9}, + }, + } + }, + }, { desc: "local-time missing digit", input: `a = 12:08:0`,