github.com/cockroachdb/pebble@v0.0.0-20231214172447-ab4952c5f87b/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 // 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 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 // 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 func (fs FormattedString) SafeValue() {} 66 67 // String implements fmt.Stringer. 68 func (fs FormattedString) String() string { return string(fs) }