diff options
Diffstat (limited to 'internal/service/time.go')
-rw-r--r-- | internal/service/time.go | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/internal/service/time.go b/internal/service/time.go new file mode 100644 index 0000000..b275b82 --- /dev/null +++ b/internal/service/time.go @@ -0,0 +1,59 @@ +package service + +import ( + "math/rand" + "time" +) + +type Duration struct { + time.Duration +} + +func DurationRef(v time.Duration) *Duration { + return &Duration{v} +} + +func (s Duration) MarshalText() ([]byte, error) { + return []byte(s.Duration.String()), nil +} + +func (s *Duration) Max(args ...*Duration) Duration { + m := s + + for _, o := range args { + if m.Duration < o.Duration { + v := o + m = v + } + } + + return *m +} + +func (s *Duration) Min(args ...*Duration) Duration { + m := s + + for _, o := range args { + if m.Duration > o.Duration { + v := o + m = v + } + } + + return *m +} + +func (s *Duration) UnmarshalText(text []byte) error { + v, err := time.ParseDuration(string(text)) + if err != nil { + return err + } + *s = Duration{v} + + return nil +} + +func RandomDuration(from Duration, until Duration) Duration { + period := until.Duration - from.Duration + return Duration{from.Duration + time.Duration(rand.Intn(int(period)))} +} |