github.com/grailbio/base@v0.0.11/data/size.go (about)

     1  // Copyright 2017 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package data provides functionality for measuring and displaying
     6  // data quantities.
     7  package data
     8  
     9  import "fmt"
    10  
    11  // A Size represents a data quantity in number of bytes.
    12  type Size int64
    13  
    14  // Common data quantities.
    15  const (
    16  	B Size = 1 << (10 * iota)
    17  	KiB
    18  	MiB
    19  	GiB
    20  	TiB
    21  	PiB
    22  	EiB
    23  )
    24  
    25  // Bytes returns the size as an integer byte count.
    26  func (s Size) Bytes() int64 {
    27  	return int64(s)
    28  }
    29  
    30  // Count returns the number of us in s.
    31  func (s Size) Count(u Size) float64 {
    32  	return float64(s) / float64(u)
    33  }
    34  
    35  // String returns a string representation of the data quantity b,
    36  // picking the largest appropriate unit.
    37  func (s Size) String() string {
    38  	abs := s
    39  	if abs < 0 {
    40  		abs = -abs
    41  	}
    42  	switch {
    43  	case abs >= EiB:
    44  		return fmt.Sprintf("%.1fEiB", s.Count(EiB))
    45  	case abs >= PiB:
    46  		return fmt.Sprintf("%.1fPiB", s.Count(PiB))
    47  	case abs >= TiB:
    48  		return fmt.Sprintf("%.1fTiB", s.Count(TiB))
    49  	case abs >= GiB:
    50  		return fmt.Sprintf("%.1fGiB", s.Count(GiB))
    51  	case abs >= MiB:
    52  		return fmt.Sprintf("%.1fMiB", s.Count(MiB))
    53  	case abs >= KiB:
    54  		return fmt.Sprintf("%.1fKiB", s.Count(KiB))
    55  	}
    56  	return fmt.Sprintf("%dB", s)
    57  }