github.com/uber/kraken@v0.1.4/utils/memsize/memsize.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, Inc.
     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  package memsize
    15  
    16  import (
    17  	"fmt"
    18  )
    19  
    20  // Defines number of bits in each bit unit.
    21  const (
    22  	bit uint64 = 1 << (10 * iota)
    23  	Kbit
    24  	Mbit
    25  	Gbit
    26  	Tbit
    27  )
    28  
    29  // Defines number of bytes in each byte unit.
    30  const (
    31  	B uint64 = 1 << (10 * iota)
    32  	KB
    33  	MB
    34  	GB
    35  	TB
    36  )
    37  
    38  type unit struct {
    39  	val uint64
    40  	str string
    41  }
    42  
    43  func format(units []unit, n uint64) (string, bool) {
    44  	for _, u := range units {
    45  		if n >= u.val {
    46  			f := float64(n) / float64(u.val)
    47  			return fmt.Sprintf("%.2f%s", f, u.str), true
    48  		}
    49  	}
    50  	return "", false
    51  }
    52  
    53  // Format returns a human readable representation for the given number of bytes.
    54  func Format(bytes uint64) string {
    55  	units := []unit{
    56  		{TB, "TB"},
    57  		{GB, "GB"},
    58  		{MB, "MB"},
    59  		{KB, "KB"},
    60  		{B, "B"},
    61  	}
    62  	s, ok := format(units, bytes)
    63  	if !ok {
    64  		s = "0B"
    65  	}
    66  	return s
    67  }
    68  
    69  // BitFormat returns a human readable representation for the given number of bits.
    70  func BitFormat(bits uint64) string {
    71  	units := []unit{
    72  		{Tbit, "Tbit"},
    73  		{Gbit, "Gbit"},
    74  		{Mbit, "Mbit"},
    75  		{Kbit, "Kbit"},
    76  		{1, "bit"},
    77  	}
    78  	s, ok := format(units, bits)
    79  	if !ok {
    80  		s = "0bit"
    81  	}
    82  	return s
    83  }