File: duration.go

package info (click to toggle)
golang-github-linode-linodego 1.55.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,112 kB
  • sloc: makefile: 96; sh: 52; python: 24
file content (64 lines) | stat: -rw-r--r-- 1,173 bytes parent folder | download | duplicates (2)
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
package duration

import (
	"encoding/json"
	"fmt"
	"log"
	"strconv"
	"strings"
)

func UnmarshalTimeRemaining(m json.RawMessage) *int {
	jsonBytes, err := m.MarshalJSON()
	if err != nil {
		panic(jsonBytes)
	}

	if len(jsonBytes) == 4 && string(jsonBytes) == "null" {
		return nil
	}

	var timeStr string
	if err := json.Unmarshal(jsonBytes, &timeStr); err == nil && len(timeStr) > 0 {
		dur, err := durationToSeconds(timeStr)
		if err != nil {
			panic(err)
		}

		return &dur
	}

	var intPtr int
	if err := json.Unmarshal(jsonBytes, &intPtr); err == nil {
		return &intPtr
	}

	log.Println("[WARN] Unexpected unmarshalTimeRemaining value: ", jsonBytes)

	return nil
}

// durationToSeconds takes a hh:mm:ss string and returns the number of seconds.
func durationToSeconds(s string) (int, error) {
	multipliers := [3]int{60 * 60, 60, 1}
	segs := strings.Split(s, ":")

	if len(segs) > len(multipliers) {
		return 0, fmt.Errorf("too many ':' separators in time duration: %s", s)
	}

	var d int

	l := len(segs)

	for i := range l {
		m, err := strconv.Atoi(segs[i])
		if err != nil {
			return 0, err
		}

		d += m * multipliers[i+len(multipliers)-l]
	}

	return d, nil
}