From 8da641adb8781167c2d6b5de6f03e7ca79cc3bd8 Mon Sep 17 00:00:00 2001 From: Charlie Tonneslan Date: Fri, 29 May 2026 07:55:06 -0400 Subject: [PATCH] util: don't drop trailing b/B when the input is a single-digit byte count parseSizeInBytes only stripped the trailing 'b'/'B' inside the "lastChar > 1" branch, so "1B" or "1b" fell through to cast.ToInt with the unit still attached and returned 0. Hoisted the strip out of that branch so single-digit byte sizes parse like the rest. Test cases for "1b" and "1B" added; the existing cases still pass. Signed-off-by: Charlie Tonneslan --- util.go | 33 ++++++++++++++++----------------- viper_test.go | 2 ++ 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/util.go b/util.go index d08ed4621..614f308e1 100644 --- a/util.go +++ b/util.go @@ -153,25 +153,24 @@ func parseSizeInBytes(sizeStr string) uint { lastChar := len(sizeStr) - 1 multiplier := uint(1) - if lastChar > 0 { - if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' { - if lastChar > 1 { - switch unicode.ToLower(rune(sizeStr[lastChar-1])) { - case 'k': - multiplier = 1 << 10 - sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) - case 'm': - multiplier = 1 << 20 - sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) - case 'g': - multiplier = 1 << 30 - sizeStr = strings.TrimSpace(sizeStr[:lastChar-1]) - default: - multiplier = 1 - sizeStr = strings.TrimSpace(sizeStr[:lastChar]) - } + if lastChar > 0 && (sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B') { + sizeStr = sizeStr[:lastChar] + lastChar-- + + if lastChar >= 0 { + switch unicode.ToLower(rune(sizeStr[lastChar])) { + case 'k': + multiplier = 1 << 10 + sizeStr = sizeStr[:lastChar] + case 'm': + multiplier = 1 << 20 + sizeStr = sizeStr[:lastChar] + case 'g': + multiplier = 1 << 30 + sizeStr = sizeStr[:lastChar] } } + sizeStr = strings.TrimSpace(sizeStr) } size := max(cast.ToInt(sizeStr), 0) diff --git a/viper_test.go b/viper_test.go index 8b0232aee..180b703da 100644 --- a/viper_test.go +++ b/viper_test.go @@ -1437,6 +1437,8 @@ func TestSizeInBytes(t *testing.T) { "b": 0, "12 bytes": 0, "200000000000gb": 0, + "1b": 1, + "1B": 1, "12 b": 12, "43 MB": 43 * (1 << 20), "10mb": 10 * (1 << 20),