github.com/zuoyebang/bitalostable@v1.0.1-0.20240229032404-e3b99a834294/internal/humanize/humanize.go (about) 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 func logn(n, b float64) float64 { 15 return math.Log(n) / math.Log(b) 16 } 17 18 func humanate(s uint64, base float64, suffixes []string) string { 19 if s < 10 { 20 return fmt.Sprintf("%d%s", s, suffixes[0]) 21 } 22 e := math.Floor(logn(float64(s), base)) 23 suffix := suffixes[int(e)] 24 val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10 25 f := "%.0f%s" 26 if val < 10 { 27 f = "%.1f%s" 28 } 29 30 return fmt.Sprintf(f, val, suffix) 31 } 32 33 type config struct { 34 base float64 35 suffix []string 36 } 37 38 // IEC produces human readable representations of integer values in IEC units. 39 var IEC = config{1024, []string{" B", " K", " M", " G", " T", " P", " E"}} 40 41 // SI produces human readable representations of integer values in SI units. 42 var SI = config{1000, []string{"", " K", " M", " G", " T", " P", " E"}} 43 44 // Int64 produces a human readable representation of the value. 45 func (c *config) Int64(s int64) FormattedString { 46 if s < 0 { 47 return FormattedString("-" + humanate(uint64(-s), c.base, c.suffix)) 48 } 49 return FormattedString(humanate(uint64(s), c.base, c.suffix)) 50 } 51 52 // Uint64 produces a human readable representation of the value. 53 func (c *config) Uint64(s uint64) FormattedString { 54 return FormattedString(humanate(s, c.base, c.suffix)) 55 } 56 57 // Int64 produces a human readable representation of the value in IEC units 58 // (base 1024). 59 func Int64(s int64) FormattedString { 60 return IEC.Int64(s) 61 } 62 63 // Uint64 produces a human readable representation of the value in IEC units 64 // (base 1024). 65 func Uint64(s uint64) FormattedString { 66 return IEC.Uint64(s) 67 } 68 69 // FormattedString represents a human readable representation of a value. It 70 // implements the redact.SafeValue interface to signal that it represents a 71 // a string that does not need to be redacted. 72 type FormattedString string 73 74 var _ redact.SafeValue = FormattedString("") 75 76 // SafeValue implements redact.SafeValue. 77 func (fs FormattedString) SafeValue() {} 78 79 // String implements fmt.Stringer. 80 func (fs FormattedString) String() string { return string(fs) }