Skip to content

Commit

Permalink
feat(scw): add NewDurationFromTimeDuration (#1910)
Browse files Browse the repository at this point in the history
  • Loading branch information
Codelax authored Nov 3, 2023
1 parent c78681e commit e3f574f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
9 changes: 9 additions & 0 deletions scw/custom_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,15 @@ func (d *Duration) UnmarshalJSON(b []byte) error {
return nil
}

func NewDurationFromTimeDuration(t time.Duration) *Duration {
duration := Duration{
Seconds: int64(t.Seconds()),
}
duration.Nanos = int32(t.Nanoseconds() - (time.Duration(duration.Seconds) * time.Second).Nanoseconds())

return &duration
}

// splitFloatString splits a float represented in a string, and returns its units (left-coma part) and nanos (right-coma part).
// E.g.:
// "3" ==> units = 3 | nanos = 0
Expand Down
55 changes: 55 additions & 0 deletions scw/custom_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,61 @@ func TestDuration_ToTimeDuration(t *testing.T) {
}
}

func TestDuration_FromTimeDuration(t *testing.T) {
cases := []struct {
name string
duration time.Duration
want *Duration
}{
{
name: "zero duration",
want: &Duration{Seconds: 0, Nanos: 0},
duration: time.Duration(0),
},
{
name: "seconds only",
want: &Duration{Seconds: 10, Nanos: 0},
duration: time.Duration(10) * time.Second,
},
{
name: "nanoseconds only",
want: &Duration{Seconds: 0, Nanos: 500},
duration: time.Duration(500),
},
{
name: "seconds and nanoseconds",
want: &Duration{Seconds: 10, Nanos: 500},
duration: time.Duration(10)*time.Second + time.Duration(500),
},
{
name: "negative seconds",
want: &Duration{Seconds: -10, Nanos: 0},
duration: time.Duration(-10) * time.Second,
},
{
name: "negative nanoseconds",
want: &Duration{Seconds: 0, Nanos: -500},
duration: time.Duration(-500),
},
{
name: "negative seconds and nanoseconds",
want: &Duration{Seconds: -10, Nanos: -500},
duration: time.Duration(-10)*time.Second + time.Duration(-500),
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := NewDurationFromTimeDuration(c.duration)
if got == nil {
t.Errorf("got nil, want %v", c.want)
} else if got.Seconds != c.want.Seconds && got.Nanos != c.want.Nanos {
t.Errorf("got %v, want %v", *got, c.want)
}
})
}
}

func TestJSONObject_UnmarshalJSON(t *testing.T) {
cases := []struct {
name string
Expand Down

0 comments on commit e3f574f

Please sign in to comment.