github.com/asifdxtreme/cli@v6.1.3-0.20150123051144-9ead8700b4ae+incompatible/cf/formatters/bytes.go (about)

     1  package formatters
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"regexp"
     7  	"strconv"
     8  	"strings"
     9  
    10  	. "github.com/cloudfoundry/cli/cf/i18n"
    11  )
    12  
    13  const (
    14  	BYTE     = 1.0
    15  	KILOBYTE = 1024 * BYTE
    16  	MEGABYTE = 1024 * KILOBYTE
    17  	GIGABYTE = 1024 * MEGABYTE
    18  	TERABYTE = 1024 * GIGABYTE
    19  )
    20  
    21  func ByteSize(bytes int64) string {
    22  	unit := ""
    23  	value := float32(bytes)
    24  
    25  	switch {
    26  	case bytes >= TERABYTE:
    27  		unit = "T"
    28  		value = value / TERABYTE
    29  	case bytes >= GIGABYTE:
    30  		unit = "G"
    31  		value = value / GIGABYTE
    32  	case bytes >= MEGABYTE:
    33  		unit = "M"
    34  		value = value / MEGABYTE
    35  	case bytes >= KILOBYTE:
    36  		unit = "K"
    37  		value = value / KILOBYTE
    38  	case bytes == 0:
    39  		return "0"
    40  	}
    41  
    42  	stringValue := fmt.Sprintf("%.1f", value)
    43  	stringValue = strings.TrimSuffix(stringValue, ".0")
    44  	return fmt.Sprintf("%s%s", stringValue, unit)
    45  }
    46  
    47  func ToMegabytes(s string) (int64, error) {
    48  	parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s))
    49  	if len(parts) < 3 {
    50  		return 0, invalidByteQuantityError()
    51  	}
    52  
    53  	value, err := strconv.ParseInt(parts[1], 10, 0)
    54  	if err != nil {
    55  		return 0, invalidByteQuantityError()
    56  	}
    57  
    58  	var bytes int64
    59  	unit := strings.ToUpper(parts[2])
    60  	switch unit {
    61  	case "T":
    62  		bytes = value * TERABYTE
    63  	case "G":
    64  		bytes = value * GIGABYTE
    65  	case "M":
    66  		bytes = value * MEGABYTE
    67  	case "K":
    68  		bytes = value * KILOBYTE
    69  	}
    70  
    71  	return bytes / MEGABYTE, nil
    72  }
    73  
    74  var (
    75  	bytesPattern *regexp.Regexp = regexp.MustCompile(`(?i)^(-?\d+)([KMGT])B?$`)
    76  )
    77  
    78  func invalidByteQuantityError() error {
    79  	return errors.New(T("Byte quantity must be an integer with a unit of measurement like M, MB, G, or GB"))
    80  }