-
Notifications
You must be signed in to change notification settings - Fork 62
/
parse.go
72 lines (61 loc) · 2.08 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (c) 2021-2022 Trim21 <trim21.me@gmail.com>
//
// SPDX-License-Identifier: AGPL-3.0-only
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>
package duration
import (
"errors"
"fmt"
"regexp"
"strconv"
"time"
"github.com/bangumi/server/internal/errgo"
)
// ErrOverFlow is the error when int components too big like `1:61:00`.
var ErrOverFlow = errors.New(
"overflow: components like minutes or seconds is bigger than it should be",
)
var extraPattern = regexp.MustCompile(`^(\d+(:))?(\d+):(\d+)$`)
// Parse a string like "01:31:41" and go default Duration.String() to time.Duration.
func Parse(s string) (time.Duration, error) {
g := extraPattern.FindStringSubmatch(s)
if g == nil {
d, err := time.ParseDuration(s)
return d, errgo.Wrap(err, "time.ParseDuration")
}
var hour int
var err error
if g[1] != "" {
hour, err = strconv.Atoi(g[1][:len(g[1])-1])
if err != nil {
return 0, errgo.Wrap(err, "parse time component as int")
}
}
minute, err := strconv.Atoi(g[3])
if err != nil {
return 0, errgo.Wrap(err, "parse time component as int")
} else if minute >= 60 {
return 0, errgo.Msg(ErrOverFlow,
fmt.Sprintf("overflow: minutes %d is bigger than 60", minute))
}
second, err := strconv.Atoi(g[4])
if err != nil {
return 0, errgo.Wrap(err, "parse time component as int")
} else if second >= 60 {
return 0, errgo.Msg(ErrOverFlow,
fmt.Sprintf("overflow: second %d is bigger than 60", second))
}
return time.Hour*time.Duration(hour) +
time.Minute*time.Duration(minute) + time.Second*time.Duration(second), nil
}