Line data Source code
1 : // Copyright 2019 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 : // of this source code is governed by a BSD-style license that can be found in 3 : // the LICENSE file. 4 : 5 : package humanize 6 : 7 : import ( 8 : "fmt" 9 : "math" 10 : 11 : "github.com/cockroachdb/redact" 12 : ) 13 : 14 1 : func logn(n, b float64) float64 { 15 1 : return math.Log(n) / math.Log(b) 16 1 : } 17 : 18 1 : func humanate(s uint64, base float64, suffixes []string) string { 19 1 : if s < 10 { 20 1 : return fmt.Sprintf("%d%s", s, suffixes[0]) 21 1 : } 22 1 : e := math.Floor(logn(float64(s), base)) 23 1 : suffix := suffixes[int(e)] 24 1 : val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10 25 1 : f := "%.0f%s" 26 1 : if val < 10 { 27 1 : f = "%.1f%s" 28 1 : } 29 : 30 1 : return fmt.Sprintf(f, val, suffix) 31 : } 32 : 33 : type config struct { 34 : base float64 35 : suffix []string 36 : } 37 : 38 : // Bytes produces human readable representations of byte values in IEC units. 39 : var Bytes = config{1024, []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}} 40 : 41 : // Count produces human readable representations of unitless values in SI units. 42 : var Count = config{1000, []string{"", "K", "M", "G", "T", "P", "E"}} 43 : 44 : // Int64 produces a human readable representation of the value. 45 0 : func (c *config) Int64(s int64) FormattedString { 46 0 : if s < 0 { 47 0 : return FormattedString("-" + humanate(uint64(-s), c.base, c.suffix)) 48 0 : } 49 0 : return FormattedString(humanate(uint64(s), c.base, c.suffix)) 50 : } 51 : 52 : // Uint64 produces a human readable representation of the value. 53 1 : func (c *config) Uint64(s uint64) FormattedString { 54 1 : return FormattedString(humanate(s, c.base, c.suffix)) 55 1 : } 56 : 57 : // FormattedString represents a human readable representation of a value. It 58 : // implements the redact.SafeValue interface to signal that it represents a 59 : // a string that does not need to be redacted. 60 : type FormattedString string 61 : 62 : var _ redact.SafeValue = FormattedString("") 63 : 64 : // SafeValue implements redact.SafeValue. 65 0 : func (fs FormattedString) SafeValue() {} 66 : 67 : // String implements fmt.Stringer. 68 1 : func (fs FormattedString) String() string { return string(fs) }