mirror of
https://github.com/golang/go.git
synced 2025-12-08 06:10:04 +00:00
Use unsigned int in itoa to avoid relying on the behaviour of
signed integer overflow when negating the most negative integer. R=rsc DELTA=11 (0 added, 7 deleted, 4 changed) OCL=16105 CL=16120
This commit is contained in:
parent
e4a61c6524
commit
489b5001e2
1 changed files with 4 additions and 11 deletions
|
|
@ -168,30 +168,23 @@ export func itoa(i int) string {
|
|||
}
|
||||
|
||||
neg := false; // negative
|
||||
bigneg := false; // largest negative number
|
||||
u := uint(i);
|
||||
if i < 0 {
|
||||
neg = true;
|
||||
i = -i;
|
||||
if i < 0 {
|
||||
bigneg = true; // is largest negative int
|
||||
i-- // now positive
|
||||
}
|
||||
u = -u;
|
||||
}
|
||||
|
||||
// Assemble decimal in reverse order.
|
||||
var b [32]byte;
|
||||
bp := len(b);
|
||||
for ; i > 0; i /= 10 {
|
||||
for ; u > 0; u /= 10 {
|
||||
bp--;
|
||||
b[bp] = byte(i%10) + '0'
|
||||
b[bp] = byte(u%10) + '0'
|
||||
}
|
||||
if neg { // add sign
|
||||
bp--;
|
||||
b[bp] = '-'
|
||||
}
|
||||
if bigneg { // account for i-- above
|
||||
b[len(b)-1]++
|
||||
}
|
||||
|
||||
// BUG return string(b[bp:len(b)])
|
||||
return string((&b)[bp:len(b)])
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue