cloudflare/pint

Public

mirrored from https://github.com/cloudflare/pintAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.75.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

internal/output/humanize.go

57lines · modecode

1package output
2
3import (
4 "fmt"
5 "math"
6 "strings"
7 "time"
8)
9
10func HumanizeDuration(d time.Duration) string {
11 weeks := int64(d.Hours() / (7 * 24))
12 days := int64(math.Mod(d.Hours(), 7*24) / 24)
13 hours := int64(math.Mod(d.Hours(), 24))
14 minutes := int64(math.Mod(d.Minutes(), 60))
15 seconds := int64(math.Mod(d.Seconds(), 60))
16 ms := int64(math.Mod(float64(d.Milliseconds()), 1000))
17
18 chunks := []struct {
19 singularName string
20 amount int64
21 }{
22 {"w", weeks},
23 {"d", days},
24 {"h", hours},
25 {"m", minutes},
26 {"s", seconds},
27 {"ms", ms},
28 }
29
30 parts := []string{}
31
32 for _, chunk := range chunks {
33 if chunk.amount > 0 {
34 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.singularName))
35 }
36 }
37
38 if len(parts) == 0 {
39 return "0"
40 }
41
42 return strings.Join(parts, "")
43}
44
45func HumanizeBytes(b int) string {
46 const unit = 1024
47 if b < unit {
48 return fmt.Sprintf("%dB", b)
49 }
50 div, exp := int64(unit), 0
51 for n := b / unit; n >= unit; n /= unit {
52 div *= unit
53 exp++
54 }
55 return fmt.Sprintf("%.1f%ciB",
56 float64(b)/float64(div), "KMGTPE"[exp])
57}