cloudflare/pint

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.13.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

internal/output/humanize.go

59lines · 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 mc := int64(math.Mod(float64(d.Microseconds()), 1000))
18
19 chunks := []struct {
20 singularName string
21 amount int64
22 }{
23 {"w", weeks},
24 {"d", days},
25 {"h", hours},
26 {"m", minutes},
27 {"s", seconds},
28 {"ms", ms},
29 {"µs", mc},
30 }
31
32 parts := []string{}
33
34 for _, chunk := range chunks {
35 if chunk.amount > 0 {
36 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.singularName))
37 }
38 }
39
40 if len(parts) == 0 {
41 return "0"
42 }
43
44 return strings.Join(parts, "")
45}
46
47func HumanizeBytes(b int) string {
48 const unit = 1024
49 if b < unit {
50 return fmt.Sprintf("%dB", b)
51 }
52 div, exp := int64(unit), 0
53 for n := b / unit; n >= unit; n /= unit {
54 div *= unit
55 exp++
56 }
57 return fmt.Sprintf("%.1f%ciB",
58 float64(b)/float64(div), "KMGTPE"[exp])
59}
60