Skip to content

Commit 49ca883

Browse files
Potential fix for code scanning alert no. 8: Incorrect conversion between integer types
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1 parent a61d959 commit 49ca883

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

cmd/status/metrics_battery.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"errors"
66
"fmt"
7+
"math"
78
"os"
89
"path/filepath"
910
"runtime"
@@ -251,9 +252,27 @@ func collectThermal() ThermalStatus {
251252
} else if valUint, err := strconv.ParseUint(valStr, 10, 64); err == nil {
252253
// Strategy 2: Try parsing as an unsigned integer (Two's Complement).
253254
// ioreg often returns negative values as huge uint64 numbers (e.g. 2^64 - 100).
254-
// Casting such a uint64 to int64 correctly restores the negative value.
255-
powerMW = float64(int64(valUint))
255+
// Explicitly handle two's complement rather than relying on an unchecked cast.
256+
var signed int64
257+
if valUint <= math.MaxInt64 {
258+
// Fits in positive int64 range directly.
259+
signed = int64(valUint)
260+
} else {
261+
// Interpret as negative two's complement value.
262+
// For a uint64 v > MaxInt64, the corresponding negative int64 is:
263+
// -(^v + 1) where ^ is bitwise NOT in 64 bits.
264+
negMag := ^valUint + 1
265+
// negMag now holds the magnitude of the negative value as uint64.
266+
if negMag <= math.MaxInt64 {
267+
signed = -int64(negMag)
268+
} else {
269+
// Magnitude too large to represent; skip this parsing strategy.
270+
goto skipUintParse
271+
}
272+
}
273+
powerMW = float64(signed)
256274
parsed = true
275+
skipUintParse:
257276
}
258277

259278
if parsed {

0 commit comments

Comments
 (0)