github.com/Cloud-Foundations/Dominator@v0.3.4/lib/format/format.go (about) 1 package format 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 // Duration is similar to the time.Duration.String method from the standard 9 // library but is more readable and shows only 3 digits of precision when 10 // duration is less than 1 minute. 11 func Duration(duration time.Duration) string { 12 if ns := duration.Nanoseconds(); ns < 1000 { 13 return fmt.Sprintf("%dns", ns) 14 } else if us := float64(duration) / float64(time.Microsecond); us < 1000 { 15 return fmt.Sprintf("%.3gµs", us) 16 } else if ms := float64(duration) / float64(time.Millisecond); ms < 1000 { 17 return fmt.Sprintf("%.3gms", ms) 18 } else if s := float64(duration) / float64(time.Second); s < 60 { 19 return fmt.Sprintf("%.3gs", s) 20 } else { 21 duration -= duration % time.Second 22 day := time.Hour * 24 23 if duration < day { 24 return duration.String() 25 } 26 week := day * 7 27 if duration < week { 28 days := duration / day 29 duration %= day 30 return fmt.Sprintf("%dd%s", days, duration) 31 } 32 year := day*365 + day>>2 33 if duration < year { 34 weeks := duration / week 35 duration %= week 36 days := duration / day 37 duration %= day 38 return fmt.Sprintf("%dw%dd%s", weeks, days, duration) 39 } 40 years := duration / year 41 duration %= year 42 weeks := duration / week 43 duration %= week 44 days := duration / day 45 duration %= day 46 return fmt.Sprintf("%dy%dw%dd%s", years, weeks, days, duration) 47 } 48 } 49 50 // FormatBytes returns a string with the number of bytes specified converted 51 // into a human-friendly format with a binary multiplier (i.e. GiB). 52 func FormatBytes(bytes uint64) string { 53 shift, multiplier := GetMiltiplier(bytes) 54 return fmt.Sprintf("%d %sB", bytes>>shift, multiplier) 55 } 56 57 // GetMiltiplier will return the preferred base-2 multiplier (i.e. Ki, Mi, Gi) 58 // and right shift number for the specified vlaue. 59 func GetMiltiplier(value uint64) (uint, string) { 60 if value>>40 > 100 || (value>>40 >= 1 && value&(1<<40-1) == 0) { 61 return 40, "Ti" 62 } else if value>>30 > 100 || (value>>30 >= 1 && value&(1<<30-1) == 0) { 63 return 30, "Gi" 64 } else if value>>20 > 100 || (value>>20 >= 1 && value&(1<<20-1) == 0) { 65 return 20, "Mi" 66 } else if value>>10 > 100 || (value>>10 >= 1 && value&(1<<10-1) == 0) { 67 return 10, "Ki" 68 } else { 69 return 0, "" 70 } 71 }