Skip to content

Commit

Permalink
Allow unmarshalling LocalTime to time.Duration
Browse files Browse the repository at this point in the history
  • Loading branch information
Benbebop committed Oct 11, 2024
1 parent af236b6 commit 2ff7476
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions localtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
6 changes: 6 additions & 0 deletions unmarshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
14 changes: 14 additions & 0 deletions unmarshaler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down

0 comments on commit 2ff7476

Please sign in to comment.