Skip to content

Commit a09cd47

Browse files
committed
Avoid getting "index out of range"
Theoretically there is a case when size/base >= len(_map). I changed the loop's condition expression so there isn't going to be any bad memory access in the following scenario.
1 parent 09dda9d commit a09cd47

File tree

2 files changed

+4
-1
lines changed

2 files changed

+4
-1
lines changed

size.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB",
4141
// using custom format.
4242
func CustomSize(format string, size float64, base float64, _map []string) string {
4343
i := 0
44-
for size >= base {
44+
unitsLimit := len(_map) - 1
45+
for size >= base && i < unitsLimit {
4546
size = size / base
4647
i++
4748
}

size_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ func TestBytesSize(t *testing.T) {
6767
assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB))
6868
assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB))
6969
assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB))
70+
assertEquals(t, "1.049e+06 YiB", BytesSize(KiB*KiB*KiB*KiB*KiB*PiB))
7071
}
7172

7273
func TestHumanSize(t *testing.T) {
@@ -78,6 +79,7 @@ func TestHumanSize(t *testing.T) {
7879
assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB)))
7980
assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB)))
8081
assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB)))
82+
assertEquals(t, "1e+04 YB", HumanSize(float64(10000000000000*PB)))
8183
}
8284

8385
func TestFromHumanSize(t *testing.T) {

0 commit comments

Comments
 (0)