fix: ByteFmt panic on negative int64 values (#1200)

This commit is contained in:
Copilot authored and GitHub committed 2025-12-28 21:57:40 +08:00
1 parent 3abf6ed933
commit 5515a1c48c
2 files changed
+30 -2

No files matched your search

+14 -1
View File
@@ -5,14 +5,27 @@ import (
"math"
)
const unknownSize = "unknown"
var unitArr = []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
func ByteFmt(size int64) string {
if size == 0 {
return "unknown"
return unknownSize
}
// Handle negative values
if size < 0 {
return unknownSize
}
fs := float64(size)
p := int(math.Log(fs) / math.Log(1024))
// Ensure index is within bounds
if p < 0 {
p = 0
}
if p >= len(unitArr) {
p = len(unitArr) - 1
}
val := fs / math.Pow(1024, float64(p))
_, frac := math.Modf(val)
if frac > 0 {
+16 -1
View File
@@ -14,7 +14,17 @@ func TestByteFmt(t *testing.T) {
{
name: "unknown",
args: args{size: int64(0)},
want: "unknown",
want: unknownSize,
},
{
name: "negative value",
args: args{size: int64(-1)},
want: unknownSize,
},
{
name: "negative min int64",
args: args{size: int64(-9223372036854775808)},
want: unknownSize,
},
{
name: "100B",
@@ -51,6 +61,11 @@ func TestByteFmt(t *testing.T) {
args: args{size: int64(1024 * 1024 * 2)},
want: "2MB",
},
{
name: "large value",
args: args{size: int64(9223372036854775807)}, // max int64
want: "8EB",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {