diff --git a/byteseq.go b/byteseq.go index 583caab..99ce831 100644 --- a/byteseq.go +++ b/byteseq.go @@ -92,35 +92,20 @@ func TrimRight[S byteSeq](s S, cutset byte) S { // This is an optimized version that's faster than strings/bytes.TrimSpace for ASCII strings. // It removes the following ASCII whitespace characters: space, tab, newline, carriage return, vertical tab, and form feed. func TrimSpace[S byteSeq](s S) S { - length := len(s) + i, j := 0, len(s)-1 - // Fast path for empty input - if length == 0 { + // fast path for empty string + if j < 0 { return s } - // Find first non-whitespace character - start := 0 - for start < length && whitespaceTable[s[start]] { - start++ - } - - // If all whitespace, return empty with zero capacity to match bytes.TrimSpace behavior - if start == length { - return s[length:length] + // Find first non-whitespace from start + for ; i <= j && whitespaceTable[s[i]]; i++ { //nolint:revive // we want to check for multiple whitespace chars } - // Find last non-whitespace character - end := length - 1 - for end > start && whitespaceTable[s[end]] { - end-- + // Find first non-whitespace from end + for ; i < j && whitespaceTable[s[j]]; j-- { //nolint:revive // we want to check for multiple whitespace chars } - // If no trimming needed, return original (no allocation) - if start == 0 && end == length-1 { - return s - } - - // Return trimmed substring/subslice - return s[start : end+1] + return s[i : j+1] }