Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,21 @@ import (
"strings"
"time"
_ "time/tzdata" // load fallback timezone data for use in docker images.
"unicode"
)

const (
Day = 24 * time.Hour
Week = 7 * Day
)

func isPartOfNumber(c byte) bool {
return ('0' <= c && c <= '9') || c == '.' || c == '-'
}

func isSpaceOrTab(c byte) bool {
return c == ' ' || c == '\t'
}

// Parse parses a duration string with "d" for days (24 hours)
// and "w" for weeks (7 days) in addition to what stdlib [time.ParseDuration] supports.
func Parse(s string) (time.Duration, error) {
Expand All @@ -36,12 +43,12 @@ func Parse(s string) (time.Duration, error) {
hasDecimal := false
for s != "" {
// consume spaces and tabs between parts
for len(s) > 0 && (s[0] == ' ' || s[0] == '\t') {
for len(s) > 0 && isSpaceOrTab(s[0]) {
s = s[1:]
}
// find number part
i := 0
for i < len(s) && (('0' <= s[i] && s[i] <= '9') || s[i] == '.' || s[i] == '-') {
for i < len(s) && isPartOfNumber(s[i]) {
if s[i] == '.' {
hasDecimal = true
}
Expand All @@ -55,7 +62,7 @@ func Parse(s string) (time.Duration, error) {

// find unit
j := 0
for j < len(s) && unicode.IsLetter(rune(s[j])) {
for j < len(s) && !isPartOfNumber(s[j]) && !isSpaceOrTab(s[j]) {
j++
}
if j == 0 {
Expand Down Expand Up @@ -91,7 +98,9 @@ func Parse(s string) (time.Duration, error) {
default:
return 0, errors.New("unknown unit " + unit + " in duration " + orig)
}
smallestUnit = min(smallestUnit, mult)
if mult < smallestUnit {
smallestUnit = mult
}
if v < 0 {
return 0, errors.New("unexpected negative sign in middle of duration " + orig)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module fortio.org/duration

go 1.21
go 1.20
Loading