github.com/core-coin/go-core/v2@v2.1.9/common/size.go (about)

     1  // Copyright 2014 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-core library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-core library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package common
    18  
    19  import (
    20  	"fmt"
    21  )
    22  
    23  // StorageSize is a wrapper around a float value that supports user friendly
    24  // formatting.
    25  type StorageSize float64
    26  
    27  // String implements the stringer interface.
    28  func (s StorageSize) String() string {
    29  	if s > 1099511627776 {
    30  		return fmt.Sprintf("%.2f TiB", s/1099511627776)
    31  	} else if s > 1073741824 {
    32  		return fmt.Sprintf("%.2f GiB", s/1073741824)
    33  	} else if s > 1048576 {
    34  		return fmt.Sprintf("%.2f MiB", s/1048576)
    35  	} else if s > 1024 {
    36  		return fmt.Sprintf("%.2f KiB", s/1024)
    37  	} else {
    38  		return fmt.Sprintf("%.2f B", s)
    39  	}
    40  }
    41  
    42  // TerminalString implements log.TerminalStringer, formatting a string for console
    43  // output during logging.
    44  func (s StorageSize) TerminalString() string {
    45  	if s > 1099511627776 {
    46  		return fmt.Sprintf("%.2fTiB", s/1099511627776)
    47  	} else if s > 1073741824 {
    48  		return fmt.Sprintf("%.2fGiB", s/1073741824)
    49  	} else if s > 1048576 {
    50  		return fmt.Sprintf("%.2fMiB", s/1048576)
    51  	} else if s > 1024 {
    52  		return fmt.Sprintf("%.2fKiB", s/1024)
    53  	} else {
    54  		return fmt.Sprintf("%.2fB", s)
    55  	}
    56  }