github.com/sdibtacm/sandbox@v0.0.0-20200320120712-60470cf803dc/units/helper/str_to_byte.go (about)

     1  package helper
     2  
     3  import "fmt"
     4  
     5  // from C++ std library
     6  
     7  func StrToBytes(str string) uint64 {
     8  	res := uint64(1)
     9  	pos := len(str) - 1
    10  	if pos > 0 && (str[pos] == 'b' || str[pos] == 'B') {
    11  		pos--
    12  	}
    13  	if pos > 0 {
    14  		switch str[pos] {
    15  		case 'p':
    16  			fallthrough
    17  		case 'P':
    18  			res *= 1024
    19  			fallthrough
    20  		case 't':
    21  			fallthrough
    22  		case 'T':
    23  			res *= 1024
    24  			fallthrough
    25  		case 'g':
    26  			fallthrough
    27  		case 'G':
    28  			res *= 1024
    29  			fallthrough
    30  		case 'm':
    31  			fallthrough
    32  		case 'M':
    33  			res *= 1024
    34  			fallthrough
    35  		case 'k':
    36  			fallthrough
    37  		case 'K':
    38  			res *= 1024
    39  		}
    40  	}
    41  	if res == 1 {
    42  		// read as long long
    43  		res = toUint64(str)
    44  	} else {
    45  		// read as double so that the user can use things like 0.5mb
    46  		res *= uint64(toFloat64(str))
    47  	}
    48  	return res
    49  }
    50  
    51  func toUint64(str string) uint64 {
    52  	var res uint64
    53  	_, err := fmt.Sscanf(str, "%d", &res)
    54  	if err != nil {
    55  		return 0
    56  	}
    57  	return res
    58  }
    59  
    60  func toFloat64(str string) float64 {
    61  	var res float64
    62  	_, err := fmt.Sscanf(str, "%g", &res)
    63  	if err != nil {
    64  		return 0
    65  	}
    66  	return res
    67  }
    68  
    69  func BytesToStr() {
    70  
    71  }