Documentation
¶
Overview ¶
Package duration provides an extended duration type with days support and multiple encoding formats.
This package wraps time.Duration and extends it with:
- Days notation in parsing and formatting (e.g., "5d23h15m13s")
- Multiple encoding support (JSON, YAML, TOML, CBOR, text)
- Viper configuration integration
- Arithmetic operations and helper functions
- Truncation and rounding to various time units
- PID controller-based range generation
The package is limited to time.Duration's range (±290 years). For larger durations, use the big sub-package.
Example usage:
import "github.com/nabbar/golib/duration"
// Parse duration with days
d, _ := duration.Parse("5d23h15m13s")
fmt.Println(d.String()) // Output: 5d23h15m13s
// Create durations
timeout := duration.Days(2) + duration.Hours(3)
// Convert to time.Duration
std := timeout.Time()
// Use in JSON
type Config struct {
Timeout duration.Duration `json:"timeout"`
}
Index ¶
- Variables
- func ViperDecoderHook() libmap.DecodeHookFuncType
- type Duration
- func Days(i int64) Duration
- func Hours(i int64) Duration
- func Minutes(i int64) Duration
- func Parse(s string) (Duration, error)
- func ParseByte(p []byte) (Duration, error)
- func ParseDuration(d time.Duration) Duration
- func ParseFloat64(f float64) Duration
- func ParseUint32(i uint32) Duration
- func Seconds(i int64) Duration
- func (d Duration) Days() int64
- func (d Duration) Float64() float64
- func (d Duration) MarshalCBOR() ([]byte, error)
- func (d Duration) MarshalJSON() ([]byte, error)
- func (d Duration) MarshalTOML() ([]byte, error)
- func (d Duration) MarshalText() ([]byte, error)
- func (d Duration) MarshalYAML() (interface{}, error)
- func (d Duration) RangeCtxFrom(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) RangeCtxTo(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) RangeDefFrom(dur Duration) []Duration
- func (d Duration) RangeDefTo(dur Duration) []Duration
- func (d Duration) RangeFrom(dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) RangeTo(dur Duration, rateP, rateI, rateD float64) []Duration
- func (d Duration) String() string
- func (d Duration) Time() time.Duration
- func (d Duration) TruncateDays() Duration
- func (d Duration) TruncateHours() Duration
- func (d Duration) TruncateMicroseconds() Duration
- func (d Duration) TruncateMilliseconds() Duration
- func (d Duration) TruncateMinutes() Duration
- func (d Duration) TruncateSeconds() Duration
- func (d *Duration) UnmarshalCBOR(bytes []byte) error
- func (d *Duration) UnmarshalJSON(bytes []byte) error
- func (d *Duration) UnmarshalTOML(i interface{}) error
- func (d *Duration) UnmarshalText(bytes []byte) error
- func (d *Duration) UnmarshalYAML(value *yaml.Node) error
Constants ¶
This section is empty.
Variables ¶
var ( DefaultRateProportional float64 = 0.1 DefaultRateIntegral float64 = 0.01 DefaultRateDerivative float64 = 0.05 )
Functions ¶
func ViperDecoderHook ¶
func ViperDecoderHook() libmap.DecodeHookFuncType
ViperDecoderHook is a libmap.DecodeHookFuncType that is used to decode strings into libdur.Duration values. It takes a reflect.Type, a reflect.Type, and an interface{} as parameters, and returns an interface{} and an error. If the data type is not a string, it returns the data as is and a nil error. If the target type is not a libdur.Duration, it returns the data as is and a nil error. Otherwise, it formats/decodes/parses the data and returns the new value.
Types ¶
type Duration ¶
func Days ¶
Days returns a Duration representing i days.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.
The duration is calculated by multiplying i by 24 hours (1 day).
func Hours ¶
Hours returns a Duration representing i hours.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.
func Minutes ¶
Minutes returns a Duration representing i minutes.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.
func Parse ¶
Parse parses a string representing a duration and returns a Duration object. It will return an error if the string is invalid.
The string must be in the format "XhYmZs" where X, Y, and Z are integers representing the number of hours, minutes, and seconds respectively. The letters "h", "m", and "s" are optional and can be omitted.
For example, "2h" represents 2 hours, "3m" represents 3 minutes, and "4s" represents 4 seconds.
The function is case insensitive.
func ParseByte ¶
ParseByte parses a byte array representing a duration and returns a Duration object. It will return an error if the byte array is invalid.
The byte array must be in the format "XhYmZs" where X, Y, and Z are integers representing the number of hours, minutes, and seconds respectively. The letters "h", "m", and "s" are optional and can be omitted.
For example, "2h" represents 2 hours, "3m" represents 3 minutes, and "4s" represents 4 seconds.
The function is case insensitive.
func ParseDuration ¶
ParseDuration returns a Duration representing d time.Duration.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
The function is a no-op and simply returns the input time.Duration as a Duration. It can be used to convert a time.Duration to a Duration without modifying the underlying time.Duration.
Example:
d := 5*time.Hour dd := ParseDuration(d) fmt.Println(dd) // 5h0m0s
func ParseFloat64 ¶ added in v1.17.0
ParseFloat64 returns a Duration representing f seconds.
If f is larger than math.MaxInt64, ParseFloat64 returns a Duration representing math.MaxInt64 seconds. If f is smaller than -math.MaxInt64, ParseFloat64 returns a Duration representing -math.MaxInt64 seconds.
Otherwise, ParseFloat64 returns a Duration representing the closest integer to f seconds. The returned Duration is a new Duration and does not modify the underlying float64.
func ParseUint32 ¶ added in v1.19.0
func Seconds ¶
Seconds returns a Duration representing i seconds.
The returned Duration is a new Duration and does not modify the underlying time.Duration.
The function panics if i is larger than math.MaxInt64 or smaller than -math.MaxInt64.
func (Duration) Days ¶
Days returns the number of days in the duration. The number of days is calculated by dividing the total number of hours by 24 and rounding down to the nearest integer. If the total number of hours is greater than the maximum value of int64, the maximum value of int64 is returned.
func (Duration) Float64 ¶ added in v1.17.0
Float64 returns the underlying int64 value of the duration as a float64.
This can be useful when working with libraries or functions that expect a float64 value, as it allows for easy conversion between the duration package and the required type.
Example:
d := libdur.ParseDuration("1h30m") f := d.Float64() fmt.Println(f) // Output: 5400.0
func (Duration) MarshalCBOR ¶
MarshalCBOR returns the CBOR encoding of the duration.
The CBOR encoding is simply the CBOR encoding of the string representation of the duration.
Example:
d := duration.MustParse("1h2m3s") b, err := d.MarshalCBOR()
if err != nil {
panic(err)
}
fmt.Println(string(b)) // Output: CBOR encoding of "1h2m3s"
func (Duration) MarshalJSON ¶
MarshalJSON returns the JSON encoding of the duration.
The JSON encoding is simply the string representation of the duration wrapped in double quotes.
Example:
d := duration.MustParse("1h2m3s") b, err := d.MarshalJSON()
if err != nil {
panic(err)
}
fmt.Println(string(b)) // Output: "1h2m3s"
func (Duration) MarshalTOML ¶
func (Duration) MarshalText ¶
MarshalText returns the text encoding of the duration.
The text encoding is simply the string representation of the duration.
Example:
d := duration.MustParse("1h2m3s") b, err := d.MarshalText()
if err != nil {
panic(err)
}
fmt.Println(string(b)) // Output: "1h2m3s"
func (Duration) MarshalYAML ¶
MarshalYAML returns the YAML encoding of the duration.
The YAML encoding is simply the string representation of the duration.
Example:
d := duration.MustParse("1h2m3s") y, err := d.MarshalYAML()
if err != nil {
panic(err)
}
fmt.Println(y) // Output: "1h2m3s"
func (Duration) RangeCtxFrom ¶ added in v1.19.0
func (d Duration) RangeCtxFrom(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration
RangeCtxFrom generates a list of durations from dur to d, spaced according to the given PID controller parameters.
The first element of the list is the end duration (dur), and the last element is the start duration (d). If the list has less than 3 elements, the start and end durations are added to the list.
If the first element of the list is greater than the end duration, the end duration is added to the beginning of the list.
If the last element of the list is less than the start duration, the start duration is added to the end of the list.
The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate
The context is used to cancel the range generation if the context is canceled before the range is fully generated. If the context is canceled before the range is fully generated, the function will return an empty list.
func (Duration) RangeCtxTo ¶ added in v1.19.0
func (d Duration) RangeCtxTo(ctx context.Context, dur Duration, rateP, rateI, rateD float64) []Duration
RangeCtxTo generates a list of durations from d to dur, spaced according to the given PID controller parameters.
The first element of the list is the start duration (d), and the last element is the end duration (dur). If the list has less than 3 elements, the start and end durations are added to the list.
If the first element of the list is greater than the start duration, the start duration is added to the beginning of the list.
If the last element of the list is less than the end duration, the end duration is added to the end of the list.
The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate
The context is used to cancel the range generation if the context is canceled before the range is fully generated.
func (Duration) RangeDefFrom ¶ added in v1.17.0
RangeDefFrom generates a list of durations from dur to d, spaced according to the default PID controller parameters.
The first element of the list is the end duration (dur), and the last element is the start duration (d). If the list has less than 3 elements, the start and end durations are added to the list.
If the first element of the list is greater than the end duration, the end duration is added to the beginning of the list.
If the last element of the list is less than the start duration, the start duration is added to the end of the list.
func (Duration) RangeDefTo ¶ added in v1.17.0
RangeDefTo generates a list of durations from d to dur, spaced according to the default PID controller parameters.
The first element of the list is the start duration (d), and the last element is the end duration (dur). If the list has less than 3 elements, the start and end durations are added to the list.
If the first element of the list is greater than the start duration, the start duration is added to the beginning of the list.
If the last element of the list is less than the end duration, the end duration is added to the end of the list.
func (Duration) RangeFrom ¶ added in v1.17.0
RangeFrom generates a list of durations from dur to d, spaced according to the given PID controller parameters.
The first element of the list is the end duration (dur), and the last element is the start duration (d). If the list has less than 3 elements, the start and end durations are added to the list.
If the first element of the list is greater than the end duration, the end duration is added to the beginning of the list.
If the last element of the list is less than the start duration, the start duration is added to the end of the list.
The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate
The context is used to cancel the range generation if the context is canceled before the range is fully generated. If the context is canceled before the range is fully generated, the function will return an empty list.
func (Duration) RangeTo ¶ added in v1.17.0
RangeTo generates a list of durations from d to dur, spaced according to the given PID controller parameters.
The first element of the list is the start duration (d), and the last element is the end duration (dur). If the list has less than 3 elements, the start and end durations are added to the list.
If the first element of the list is greater than the start duration, the start duration is added to the beginning of the list.
If the last element of the list is less than the end duration, the end duration is added to the end of the list.
The PID controller parameters are: - rateP: the proportional rate - rateI: the integral rate - rateD: the derivative rate
If the context is canceled before the range is fully generated, the function will return an empty list.
func (Duration) String ¶
String returns a string representation of the duration. The string is in the format "NdNhNmNs" where N is a number. The days are omitted if n is 0 or negative. The hours, minutes, and seconds are omitted if they are 0.
Example:
d := libdur.ParseDuration("1d2h3m4s") fmt.Println(d.String()) // Output: 1d2h3m4s
func (Duration) Time ¶
Time returns a time.Duration representation of the duration. It is a simple wrapper around the conversion of the underlying int64 value to a time.Duration.
Time is useful when working with the time package, as it allows for easy conversion between the duration package and the time package.
Example:
d := libdur.ParseDuration("1h30m") td := d.Time() fmt.Println(td) // Output: 1h30m0s
func (Duration) TruncateDays ¶ added in v1.15.3
TruncateDays returns the result of rounding d toward zero to a multiple of a day. If d is an exact multiple of a day, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a day. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a day, it rounds up to the next multiple of a day. For example, TruncateDays(ParseDuration("1.5d")) returns ParseDuration("2d").
func (Duration) TruncateHours ¶ added in v1.15.3
TruncateHours returns the result of rounding d toward zero to a multiple of an hour. If d is an exact multiple of an hour, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of an hour. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of an hour, it rounds up to the next multiple of an hour. For example, TruncateHours(ParseDuration("1.5h")) returns ParseDuration("2h").
func (Duration) TruncateMicroseconds ¶ added in v1.15.3
TruncateMicroseconds returns the result of rounding d toward zero to a multiple of a microsecond. If d is an exact multiple of a microsecond, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a microsecond. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a microsecond, it rounds up to the next multiple of a microsecond). For example, TruncateMicroseconds(ParseDuration("1.5µs")) returns ParseDuration("2µs").
func (Duration) TruncateMilliseconds ¶ added in v1.15.3
TruncateMilliseconds returns the result of rounding d toward zero to a multiple of a millisecond. If d is an exact multiple of a millisecond, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a millisecond. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a millisecond, it rounds up to the next multiple of a millisecond. For example, TruncateMilliseconds(ParseDuration("1.5ms")) returns ParseDuration("2ms").
func (Duration) TruncateMinutes ¶ added in v1.15.3
TruncateMinutes returns the result of rounding d toward zero to a multiple of a minute. If d is an exact multiple of a minute, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a minute. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a minute, it rounds up to the next multiple of a minute. For example, TruncateMinutes(ParseDuration("1.5m")) returns ParseDuration("2m").
func (Duration) TruncateSeconds ¶ added in v1.15.3
TruncateSeconds returns the result of rounding d toward zero to a multiple of a second. If d is an exact multiple of a second, it returns d unchanged. Otherwise, it returns the duration d rounded to the nearest multiple of a second. The rounding mode is to round half even up (i.e. if d is halfway between two multiples of a second, it rounds up to the next multiple of a second. For example, TruncateSeconds(ParseDuration("1.5s")) returns ParseDuration("2s").
func (*Duration) UnmarshalCBOR ¶
UnmarshalCBOR parses the CBOR-encoded duration and stores the result in the receiver.
The CBOR encoding is expected to be the CBOR encoding of the string representation of the duration.
Example:
d := &duration.Duration{} b := []byte{CBOR encoding of "1h2m3s"}
if err := d.UnmarshalCBOR(b); err != nil {
panic(err)
}
fmt.Println(d.String()) // Output: "1h2m3s"
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON parses the JSON-encoded duration and stores the result in the receiver.
The JSON encoding is expected to be a string representation of the duration wrapped in double quotes.
Example:
b := []byte(`"1h2m3s"`) d := &duration.Duration{}
if err := d.UnmarshalJSON(b); err != nil {
panic(err)
}
fmt.Println(d.String()) // Output: "1h2m3s"
func (*Duration) UnmarshalTOML ¶
func (*Duration) UnmarshalText ¶
UnmarshalText parses the text-encoded duration and stores the result in the receiver.
The text encoding is expected to be a string representation of the duration.
Example:
d := &duration.Duration{} b := []byte("1h2m3s")
if err := d.UnmarshalText(b); err != nil {
panic(err)
}
fmt.Println(d.String()) // Output: "1h2m3s"
func (*Duration) UnmarshalYAML ¶
UnmarshalYAML parses the YAML-encoded duration and stores the result in the receiver.
The YAML encoding is expected to be a string representation of the duration.
Example:
y := &yaml.Node{Value: "1h2m3s"} d := &duration.Duration{}
if err := d.UnmarshalYAML(y); err != nil {
panic(err)
}
fmt.Println(d.String()) // Output: "1h2m3s"