github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/internal/humanize/humanize.go (about)

     1  // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package humanize
    16  
    17  import (
    18  	"fmt"
    19  	"math"
    20  
    21  	"github.com/cockroachdb/redact"
    22  )
    23  
    24  func logn(n, b float64) float64 {
    25  	return math.Log(n) / math.Log(b)
    26  }
    27  
    28  func humanate(s uint64, base float64, suffixes []string) string {
    29  	if s < 10 {
    30  		return fmt.Sprintf("%d%s", s, suffixes[0])
    31  	}
    32  	e := math.Floor(logn(float64(s), base))
    33  	suffix := suffixes[int(e)]
    34  	val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
    35  	f := "%.0f%s"
    36  	if val < 10 {
    37  		f = "%.1f%s"
    38  	}
    39  
    40  	return fmt.Sprintf(f, val, suffix)
    41  }
    42  
    43  type config struct {
    44  	base   float64
    45  	suffix []string
    46  }
    47  
    48  var IEC = config{1024, []string{" B", " K", " M", " G", " T", " P", " E"}}
    49  
    50  var SI = config{1000, []string{"", " K", " M", " G", " T", " P", " E"}}
    51  
    52  func (c *config) Int64(s int64) FormattedString {
    53  	if s < 0 {
    54  		return FormattedString("-" + humanate(uint64(-s), c.base, c.suffix))
    55  	}
    56  	return FormattedString(humanate(uint64(s), c.base, c.suffix))
    57  }
    58  
    59  func (c *config) Uint64(s uint64) FormattedString {
    60  	return FormattedString(humanate(s, c.base, c.suffix))
    61  }
    62  
    63  func Int64(s int64) FormattedString {
    64  	return IEC.Int64(s)
    65  }
    66  
    67  func Uint64(s uint64) FormattedString {
    68  	return IEC.Uint64(s)
    69  }
    70  
    71  type FormattedString string
    72  
    73  var _ redact.SafeValue = FormattedString("")
    74  
    75  func (fs FormattedString) SafeValue() {}
    76  
    77  func (fs FormattedString) String() string { return string(fs) }