From 18305200d2c5caf0f97a057347500b9050909401 Mon Sep 17 00:00:00 2001 From: SapirBaruch Date: Sun, 21 Jun 2026 05:30:48 +0300 Subject: [PATCH] fix(stringx): return empty string from FirstN when n is negative (#5620) --- core/stringx/strings.go | 4 ++++ core/stringx/strings_test.go | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/core/stringx/strings.go b/core/stringx/strings.go index dadf2c52c..e1afe9424 100644 --- a/core/stringx/strings.go +++ b/core/stringx/strings.go @@ -34,6 +34,10 @@ func Filter(s string, remove func(r rune) bool) string { // FirstN returns first n runes from s. func FirstN(s string, n int, ellipsis ...string) string { + if n < 0 { + return "" + } + var i int for j := range s { diff --git a/core/stringx/strings_test.go b/core/stringx/strings_test.go index 0adcaf3ab..aa84db9dd 100644 --- a/core/stringx/strings_test.go +++ b/core/stringx/strings_test.go @@ -190,6 +190,18 @@ func TestFirstN(t *testing.T) { n: 10, expect: "我是中国人", }, + { + name: "negative n returns empty string", + input: "hello world", + n: -1, + expect: "", + }, + { + name: "negative n with utf8 returns empty string", + input: "我是中国人", + n: -5, + expect: "", + }, } for _, test := range tests {