github.com/go-darwin/sys@v0.0.0-20220510002607-68fd01f054ca/conv.go (about)

     1  // Copyright 2021 The Go Darwin Authors
     2  // SPDX-License-Identifier: BSD-3-Clause
     3  
     4  //go:build amd64 && gc
     5  // +build amd64,gc
     6  
     7  package sys
     8  
     9  // itoa converts val to a decimal string.
    10  func itoa(val int) string {
    11  	if val < 0 {
    12  		return "-" + uitoa(uint(-val))
    13  	}
    14  	return uitoa(uint(val))
    15  }
    16  
    17  // uitoa converts val to a decimal string.
    18  func uitoa(val uint) string {
    19  	if val == 0 { // avoid string allocation
    20  		return "0"
    21  	}
    22  	var buf [20]byte // big enough for 64bit value base 10
    23  	i := len(buf) - 1
    24  	for val >= 10 {
    25  		q := val / 10
    26  		buf[i] = byte('0' + val - q*10)
    27  		i--
    28  		val = q
    29  	}
    30  	// val < 10
    31  	buf[i] = byte('0' + val)
    32  	return string(buf[i:])
    33  }
    34  
    35  const (
    36  	maxUint = ^uint(0)
    37  	maxInt  = int(maxUint >> 1)
    38  )
    39  
    40  // atoi parses an int from a string s.
    41  // The bool result reports whether s is a number
    42  // representable by a value of type int.
    43  func atoi(s string) (int, bool) {
    44  	if s == "" {
    45  		return 0, false
    46  	}
    47  
    48  	neg := false
    49  	if s[0] == '-' {
    50  		neg = true
    51  		s = s[1:]
    52  	}
    53  
    54  	un := uint(0)
    55  	for i := 0; i < len(s); i++ {
    56  		c := s[i]
    57  		if c < '0' || c > '9' {
    58  			return 0, false
    59  		}
    60  		if un > maxUint/10 {
    61  			// overflow
    62  			return 0, false
    63  		}
    64  		un *= 10
    65  		un1 := un + uint(c) - '0'
    66  		if un1 < un {
    67  			// overflow
    68  			return 0, false
    69  		}
    70  		un = un1
    71  	}
    72  
    73  	if !neg && un > uint(maxInt) {
    74  		return 0, false
    75  	}
    76  	if neg && un > uint(maxInt)+1 {
    77  		return 0, false
    78  	}
    79  
    80  	n := int(un)
    81  	if neg {
    82  		n = -n
    83  	}
    84  
    85  	return n, true
    86  }
    87  
    88  // atoi32 is like atoi but for integers
    89  // that fit into an int32.
    90  func atoi32(s string) (int32, bool) {
    91  	if n, ok := atoi(s); n == int(int32(n)) {
    92  		return int32(n), ok
    93  	}
    94  	return 0, false
    95  }