mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-26 16:55:15 +00:00
types: add simple duration type for parsing [0-9]+[wd]
This commit is contained in:
parent
e0daf9904e
commit
4388bc209b
47
pkg/types/duration.go
Normal file
47
pkg/types/duration.go
Normal file
|
@ -0,0 +1,47 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var simpleDurationRegExp = regexp.MustCompile("^(\\d+)[hdw]$")
|
||||
|
||||
var ErrNotSimpleDuration = errors.New("the given input is not simple duration format")
|
||||
|
||||
type SimpleDuration struct {
|
||||
Num int64
|
||||
Unit string
|
||||
Duration Duration
|
||||
}
|
||||
|
||||
func ParseSimpleDuration(s string) (*SimpleDuration, error) {
|
||||
if !simpleDurationRegExp.MatchString(s) {
|
||||
return nil, errors.Wrapf(ErrNotSimpleDuration, "input %q is not a simple duration", s)
|
||||
}
|
||||
|
||||
matches := simpleDurationRegExp.FindStringSubmatch(s)
|
||||
numStr := matches[1]
|
||||
unit := matches[2]
|
||||
num, err := strconv.ParseInt(numStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch unit {
|
||||
case "d":
|
||||
d := Duration(time.Duration(num) * 24 * time.Hour)
|
||||
return &SimpleDuration{num, unit, d}, nil
|
||||
case "w":
|
||||
d := Duration(time.Duration(num) * 7 * 24 * time.Hour)
|
||||
return &SimpleDuration{num, unit, d}, nil
|
||||
case "h":
|
||||
d := Duration(time.Duration(num) * time.Hour)
|
||||
return &SimpleDuration{num, unit, d}, nil
|
||||
}
|
||||
|
||||
return nil, errors.Wrapf(ErrNotSimpleDuration, "input %q is not a simple duration", s)
|
||||
}
|
|
@ -26,6 +26,12 @@ func (d *Duration) UnmarshalJSON(data []byte) error {
|
|||
|
||||
switch t := o.(type) {
|
||||
case string:
|
||||
sd, err := ParseSimpleDuration(t)
|
||||
if err == nil {
|
||||
*d = sd.Duration
|
||||
return nil
|
||||
}
|
||||
|
||||
dd, err := time.ParseDuration(t)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
Loading…
Reference in New Issue
Block a user