Skip to content

Commit 64dcb40

Browse files
committed
fix(helper): Fix the bug that may cause out-of-bounds access when parsing formatted strings
1 parent 951745f commit 64dcb40

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

helper.go

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,11 @@ func format2layout(format string) string {
105105
} else {
106106
switch format[i] {
107107
case '\\': // raw output, no parse
108-
buffer = append(buffer, format[i+1])
109-
i++
108+
// Ensure we don't go out of bounds
109+
if i+1 < len(format) {
110+
buffer = append(buffer, format[i+1])
111+
i++
112+
}
110113
continue
111114
default:
112115
buffer = append(buffer, format[i])
@@ -116,8 +119,9 @@ func format2layout(format string) string {
116119

117120
result := string(buffer)
118121

119-
// Cache the result for common formats
120-
if len(format) <= 50 { // Only cache short formats to avoid memory bloat
122+
// Cache the result for common formats to improve performance
123+
// Only cache reasonably short formats to avoid memory bloat
124+
if len(format) <= 50 {
121125
layoutCache.Store(format, result)
122126
}
123127

@@ -168,13 +172,17 @@ func parseDuration(duration string) (dur Duration, err error) {
168172
}
169173

170174
// Cache the successful result for common durations
171-
if len(duration) <= 10 { // Only cache short durations to avoid memory bloat
175+
// Only cache reasonably short durations to avoid memory bloat
176+
if len(duration) <= 20 {
172177
durationCache.Store(duration, dur)
173178
}
174179
return
175180
}
176181

177182
// gets absolute value.
178183
func getAbsValue(value int64) int64 {
184+
// Use bit manipulation for better performance
185+
// For positive numbers: value ^ 0 - 0 = value
186+
// For negative numbers: value ^ -1 - (-1) = ^value + 1 = -value
179187
return (value ^ (value >> 63)) - (value >> 63)
180188
}

0 commit comments

Comments
 (0)