github.com/apcera/util@v0.0.0-20180322191801-7a50bc84ee48/str/str.go (about)

     1  // Copyright 2012 Apcera Inc. All rights reserved.
     2  
     3  // Miscellaneous utilities formatting, coloring terminal output, and similar.
     4  package str
     5  
     6  import (
     7  	"strconv"
     8  )
     9  
    10  func FormatInt(i int) string {
    11  	if i >= 0 {
    12  		return fmtImpl(uint64(i), false)
    13  	}
    14  	return fmtImpl(uint64(-i), true)
    15  }
    16  
    17  func FormatIntv(v interface{}) string {
    18  	var i uint64
    19  	var neg bool
    20  
    21  	switch v.(type) {
    22  	case int:
    23  		in := v.(int)
    24  		if in < 0 {
    25  			i = uint64(-in)
    26  			neg = true
    27  		} else {
    28  			i = uint64(in)
    29  		}
    30  	case int8:
    31  		i8 := v.(int8)
    32  		if i8 < 0 {
    33  			i = uint64(-i8)
    34  			neg = true
    35  		} else {
    36  			i = uint64(i8)
    37  		}
    38  	case int16:
    39  		i16 := v.(int16)
    40  		if i16 < 0 {
    41  			i = uint64(-i16)
    42  			neg = true
    43  		} else {
    44  			i = uint64(i16)
    45  		}
    46  	case int32:
    47  		i32 := v.(int64)
    48  		if i32 < 0 {
    49  			i = uint64(-i32)
    50  			neg = true
    51  		} else {
    52  			i = uint64(i32)
    53  		}
    54  	case int64:
    55  		i64 := v.(int64)
    56  		if i64 < 0 {
    57  			i = uint64(-i64)
    58  			neg = true
    59  		} else {
    60  			i = uint64(i64)
    61  		}
    62  	case uint:
    63  		i = uint64(v.(uint))
    64  	case uint8:
    65  		i = uint64(v.(uint8))
    66  	case uint16:
    67  		i = uint64(v.(uint16))
    68  	case uint32:
    69  		i = uint64(v.(uint32))
    70  	case uint64:
    71  		i = v.(uint64)
    72  	default:
    73  		return "<invalid value in FormatIntv>"
    74  	}
    75  
    76  	return fmtImpl(i, neg)
    77  }
    78  
    79  func fmtImpl(i uint64, negative bool) string {
    80  	s := strconv.FormatUint(i, 10)
    81  	ex := 0
    82  	if negative == true {
    83  		ex = 1
    84  	}
    85  	n := len(s)
    86  	// "g" is number of commas to insert, total output len is ex+g+len(s)
    87  	g := (n - 1) / 3
    88  	if g == 0 {
    89  		if negative {
    90  			return "-" + s
    91  		}
    92  		return s
    93  	}
    94  	buffer := make([]byte, 0, ex+g+len(s))
    95  	if negative == true {
    96  		buffer = append(buffer, '-')
    97  	}
    98  	// set "n" to length of head before first ","
    99  	if n = n - g*3; n > 0 {
   100  		buffer = append(buffer, s[:n]...)
   101  	}
   102  	for i := 0; i < g; i++ {
   103  		buffer = append(buffer, byte(','))
   104  		buffer = append(buffer, s[n:n+3]...)
   105  		n += 3
   106  	}
   107  	return string(buffer)
   108  }