Source file src/internal/runtime/strconv/atoi.go

     1  // Copyright 2025 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package strconv
     6  
     7  import (
     8  	"internal/runtime/math"
     9  )
    10  
    11  // Atoi64 parses an int64 from a string s.
    12  // The bool result reports whether s is a number
    13  // representable by a value of type int64.
    14  func Atoi64(s string) (int64, bool) {
    15  	if s == "" {
    16  		return 0, false
    17  	}
    18  
    19  	neg := false
    20  	if s[0] == '-' {
    21  		neg = true
    22  		s = s[1:]
    23  	}
    24  
    25  	un := uint64(0)
    26  	for i := 0; i < len(s); i++ {
    27  		c := s[i]
    28  		if c < '0' || c > '9' {
    29  			return 0, false
    30  		}
    31  		if un > math.MaxUint64/10 {
    32  			// overflow
    33  			return 0, false
    34  		}
    35  		un *= 10
    36  		un1 := un + uint64(c) - '0'
    37  		if un1 < un {
    38  			// overflow
    39  			return 0, false
    40  		}
    41  		un = un1
    42  	}
    43  
    44  	if !neg && un > uint64(math.MaxInt64) {
    45  		return 0, false
    46  	}
    47  	if neg && un > uint64(math.MaxInt64)+1 {
    48  		return 0, false
    49  	}
    50  
    51  	n := int64(un)
    52  	if neg {
    53  		n = -n
    54  	}
    55  
    56  	return n, true
    57  }
    58  
    59  // Atoi is like Atoi64 but for integers
    60  // that fit into an int.
    61  func Atoi(s string) (int, bool) {
    62  	if n, ok := Atoi64(s); n == int64(int(n)) {
    63  		return int(n), ok
    64  	}
    65  	return 0, false
    66  }
    67  
    68  // Atoi32 is like Atoi but for integers
    69  // that fit into an int32.
    70  func Atoi32(s string) (int32, bool) {
    71  	if n, ok := Atoi64(s); n == int64(int32(n)) {
    72  		return int32(n), ok
    73  	}
    74  	return 0, false
    75  }
    76  
    77  

View as plain text