github.com/gopherjs/gopherjs@v1.19.0-beta1.0.20240506212314-27071a8796e4/compiler/natives/src/strconv/atoi.go (about)

     1  //go:build js
     2  // +build js
     3  
     4  package strconv
     5  
     6  import (
     7  	"github.com/gopherjs/gopherjs/js"
     8  )
     9  
    10  const (
    11  	maxInt32 float64 = 1<<31 - 1
    12  	minInt32 float64 = -1 << 31
    13  )
    14  
    15  // Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
    16  func Atoi(s string) (int, error) {
    17  	const fnAtoi = "Atoi"
    18  	if len(s) == 0 {
    19  		return 0, syntaxError(fnAtoi, s)
    20  	}
    21  	// Investigate the bytes of the string
    22  	// Validate each byte is allowed in parsing
    23  	// Number allows some prefixes that Go does not: "0x" "0b", "0o"
    24  	// additionally Number accepts decimals where Go does not "10.2"
    25  	for i := 0; i < len(s); i++ {
    26  		v := s[i]
    27  
    28  		if v < '0' || v > '9' {
    29  			if v != '+' && v != '-' {
    30  				return 0, syntaxError(fnAtoi, s)
    31  			}
    32  		}
    33  	}
    34  	jsValue := js.Global.Call("Number", s, 10)
    35  	if !js.Global.Call("isFinite", jsValue).Bool() {
    36  		return 0, syntaxError(fnAtoi, s)
    37  	}
    38  	// Bounds checking
    39  	floatval := jsValue.Float()
    40  	if floatval > maxInt32 {
    41  		return int(maxInt32), rangeError(fnAtoi, s)
    42  	} else if floatval < minInt32 {
    43  		return int(minInt32), rangeError(fnAtoi, s)
    44  	}
    45  	// Success!
    46  	return jsValue.Int(), nil
    47  }