badguardhome/internal/aghtime/duration.go
Eugene Burkov e064e0f277 Pull request: 1992 configurable timeouts
Merge in DNS/adguard-home from 1992-conf-timeouts to master

Updates #1992.

Squashed commit of the following:

commit 1050c54fb407bec0617728690763b0392b3440b0
Merge: 05f71c3e 59544160
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Fri Aug 27 20:04:25 2021 +0300

    Merge branch 'master' into 1992-conf-timeouts

commit 05f71c3e5397909d943e69d49a247bf4f67619b0
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Fri Aug 27 20:03:06 2021 +0300

    home: use const

commit d0861792b42e6d066aa3ffdb3937e29477235ee0
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Fri Aug 27 19:16:26 2021 +0300

    home: fix default timeout

commit ba26fcdcf66366350c89d5a82c4da91ade45838f
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Fri Aug 27 16:50:33 2021 +0300

    all: mk ping timeout configurable
2021-08-27 20:16:07 +03:00

69 lines
1.8 KiB
Go

// Package aghtime defines some types for convenient work with time values.
package aghtime
import (
"time"
"github.com/AdguardTeam/golibs/errors"
)
// Duration is a wrapper for time.Duration providing functionality for encoding.
type Duration struct {
// time.Duration is embedded here to avoid implementing all the methods.
time.Duration
}
// String implements the fmt.Stringer interface for Duration. It wraps
// time.Duration.String method and additionally cuts off non-leading zero values
// of minutes and seconds. Some values which are differ between the
// implementations:
//
// Duration: "1m", time.Duration: "1m0s"
// Duration: "1h", time.Duration: "1h0m0s"
// Duration: "1h1m", time.Duration: "1h1m0s"
//
func (d Duration) String() (str string) {
str = d.Duration.String()
const (
tailMin = len(`0s`)
tailMinSec = len(`0m0s`)
secsInHour = time.Hour / time.Second
minsInHour = time.Hour / time.Minute
)
switch rounded := d.Duration / time.Second; {
case
rounded == 0,
rounded*time.Second != d.Duration,
rounded%60 != 0:
// Return the uncutted value if it's either equal to zero or has
// fractions of a second or even whole seconds in it.
return str
case (rounded%secsInHour)/minsInHour != 0:
return str[:len(str)-tailMin]
default:
return str[:len(str)-tailMinSec]
}
}
// MarshalText implements the encoding.TextMarshaler interface for Duration.
func (d Duration) MarshalText() (text []byte, err error) {
return []byte(d.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface for
// *Duration.
//
// TODO(e.burkov): Make it able to parse larger units like days.
func (d *Duration) UnmarshalText(b []byte) (err error) {
defer func() { err = errors.Annotate(err, "unmarshalling duration: %w") }()
d.Duration, err = time.ParseDuration(string(b))
return err
}