From fa0fbde2369553ebdc538bf761db8ab274f1bce4 Mon Sep 17 00:00:00 2001 From: Paul Z Date: Tue, 14 Dec 2021 15:42:09 +0100 Subject: [PATCH] substring: don't fail if start, end out of bounds --- strings.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/strings.go b/strings.go index e0ae628c..fd46ecd4 100644 --- a/strings.go +++ b/strings.go @@ -224,13 +224,21 @@ func splitn(sep string, n int, orig string) map[string]string { // // If start is >= 0 and end < 0 or end bigger than s length, this calls string[start:] // +// If start >= len(s) this returns an empty string +// // Otherwise, this calls string[start, end]. func substring(start, end int, s string) string { - if start < 0 { - return s[:end] + if start >= len(s) { + return "" + } + if start < 0 { + start = 0 + } + if end > len(s) { + end = len(s) } - if end < 0 || end > len(s) { - return s[start:] + if start > end { + end = start } return s[start:end] }