1// package utils provides simple transformation functions which do not fit anywhere else in particular.
2package utils
3
4import (
5	"fmt"
6	"strings"
7)
8
9// FloatTimeString formats length in seconds as H:mm:ss.
10func FloatTimeString(msecs float64) string {
11	return TimeString(int(msecs / 1000))
12}
13
14// TimeString formats length in seconds as H:mm:ss.
15func TimeString(secs int) string {
16	if secs < 0 {
17		return `--:--`
18	}
19	hours := int(secs / 3600)
20	secs = secs % 3600
21	minutes := int(secs / 60)
22	secs = secs % 60
23	if hours > 0 {
24		return fmt.Sprintf("%d:%02d:%02d", hours, minutes, secs)
25	}
26	return fmt.Sprintf("%02d:%02d", minutes, secs)
27}
28
29// TimeRunes acts as TimeString, but returns a slice of runes.
30func TimeRunes(secs int) []rune {
31	return []rune(TimeString(secs))
32}
33
34// ReverseRunes returns a new, reversed rune slice.
35func ReverseRunes(src []rune) []rune {
36	dest := make([]rune, len(src))
37	for i, j := 0, len(src)-1; i <= j; i, j = i+1, j-1 {
38		dest[i], dest[j] = src[j], src[i]
39	}
40	return dest
41}
42
43// TokenFilter returns a subset of tokens that match the specified prefix.
44func TokenFilter(match string, tokens []string) []string {
45	dest := make([]string, 0, len(tokens))
46	for _, tok := range tokens {
47		if strings.HasPrefix(tok, match) {
48			dest = append(dest, tok)
49		}
50	}
51	return dest
52}
53
54// HumanFormatBool works as strconv.FormatBool, but returns "yes" or "no".
55func HumanFormatBool(b bool) string {
56	if b {
57		return "yes"
58	}
59	return "no"
60}
61
62// Min returns the minimum of a and b.
63func Min(a, b int) int {
64	if a < b {
65		return a
66	}
67	return b
68}
69
70// Max returns the maximum of a and b.
71func Max(a, b int) int {
72	if a > b {
73		return a
74	}
75	return b
76}
77