This commit is contained in:
r4
2022-09-20 00:54:22 +02:00
commit 4195b20e65
33 changed files with 6397 additions and 0 deletions

57
util/strings.go Normal file
View File

@@ -0,0 +1,57 @@
package util
import (
"strings"
)
func CapitalizeFirst(s string) string {
if len(s) == 0 {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}
// A StringTabulator aligns columns similarly to the tabulator
// character (but 100% rigorously).
type StringTabulator [][]string
func (t *StringTabulator) WriteRow(cols ...string) {
*t = append(*t, cols)
}
func (t *StringTabulator) String() string {
if t == nil {
return ""
}
// Find which row has the most columns.
longestRow := 0
for _, row := range *t {
if len(row) > longestRow {
longestRow = len(row)
}
}
// For each column, find the field with the longest string.
longestField := make([]int, longestRow)
for _, row := range *t {
for i, col := range row {
if len(col) > longestField[i] {
longestField[i] = len(col)
}
}
}
// Add each line tabulated.
var res strings.Builder
for _, row := range *t {
for i, col := range row {
res.WriteString(col)
res.WriteString(strings.Repeat(" ", longestField[i]-len(col)))
}
res.WriteString("\n")
}
// Return the result.
return res.String()
}

41
util/time.go Normal file
View File

@@ -0,0 +1,41 @@
package util
import (
"errors"
"fmt"
"strconv"
"strings"
)
// Convert a duration specifier to seconds (e.g. 64 (seconds), 1:04, 0:1:04 etc.)
func ParseDurationSeconds(s string) (int, error) {
var secs int
sp := strings.Split(s, ":")
if len(sp) < 1 || len(sp) > 3 {
return 0, errors.New("invalid duration format")
}
magnitude := 1
for i := len(sp) - 1; i >= 0; i-- {
n, err := strconv.Atoi(sp[i])
if n < 0 || err != nil {
return 0, errors.New("invalid duration")
}
secs += n * magnitude
magnitude *= 60
}
return secs, nil
}
func FormatDurationSeconds(s int) string {
var h, m int
h = s / 3600
s -= h * 3600
m = s / 60
s -= m * 60
var hs string
if h > 0 {
hs = fmt.Sprintf("%02d:", h)
}
return fmt.Sprintf("%s%02d:%02d", hs, m, s)
}