72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package human
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func Size(size int64) string {
|
|
if size < 0 {
|
|
return "-" + Size(-size)
|
|
}
|
|
|
|
if size < 1024 {
|
|
return "0 B"
|
|
}
|
|
|
|
units := []string{"KB", "MB", "GB", "TB", "PB", "EB"}
|
|
div := int64(1024)
|
|
exp := 0
|
|
|
|
for i := 1; i < len(units); i++ {
|
|
nextDiv := div * 1024
|
|
if size < nextDiv {
|
|
break
|
|
}
|
|
div = nextDiv
|
|
exp = i
|
|
}
|
|
|
|
value := float64(size) / float64(div)
|
|
if value == float64(int64(value)) {
|
|
return fmt.Sprintf("%.0f %s", value, units[exp])
|
|
}
|
|
return fmt.Sprintf("%.2f %s", value, units[exp])
|
|
}
|
|
|
|
func Duration(d time.Duration) string {
|
|
if d < 0 {
|
|
return "-" + Duration(-d)
|
|
}
|
|
|
|
totalSeconds := int64(d.Seconds())
|
|
days := totalSeconds / 86400
|
|
hours := (totalSeconds % 86400) / 3600
|
|
minutes := (totalSeconds % 3600) / 60
|
|
seconds := totalSeconds % 60
|
|
nanos := d.Nanoseconds() % int64(time.Second)
|
|
|
|
var parts []string
|
|
if days > 0 {
|
|
parts = append(parts, fmt.Sprintf("%dd", days))
|
|
}
|
|
if hours > 0 {
|
|
parts = append(parts, fmt.Sprintf("%dh", hours))
|
|
}
|
|
if minutes > 0 {
|
|
parts = append(parts, fmt.Sprintf("%dm", minutes))
|
|
}
|
|
|
|
if nanos > 0 {
|
|
secWithNanos := float64(seconds) + float64(nanos)/1e9
|
|
parts = append(parts, fmt.Sprintf("%.2fs", secWithNanos))
|
|
} else if seconds > 0 {
|
|
parts = append(parts, fmt.Sprintf("%ds", seconds))
|
|
} else if len(parts) == 0 {
|
|
return "0s"
|
|
}
|
|
|
|
return strings.Join(parts, " ")
|
|
}
|