collapseNewlines replaces runs of 3 or more consecutive newlines with exactly 2, preserving single blank lines (paragraph breaks) while eliminating scroll-padding attacks. Trailing whitespace on each line is stripped first so that whitespace-only lines become empty and collapse naturally.
(s string)
| 135 | // each line is stripped first so that whitespace-only lines become |
| 136 | // empty and collapse naturally. |
| 137 | func collapseNewlines(s string) string { |
| 138 | // Step 1: Trim trailing whitespace from each line, preserving |
| 139 | // leading whitespace for indentation. |
| 140 | lines := strings.Split(s, "\n") |
| 141 | for i, line := range lines { |
| 142 | lines[i] = strings.TrimRightFunc(line, unicode.IsSpace) |
| 143 | } |
| 144 | s = strings.Join(lines, "\n") |
| 145 | |
| 146 | // Step 2: Collapse runs of 3+ consecutive newlines down to 2. |
| 147 | var b strings.Builder |
| 148 | b.Grow(len(s)) |
| 149 | consecutiveNewlines := 0 |
| 150 | for _, r := range s { |
| 151 | if r == '\n' { |
| 152 | consecutiveNewlines++ |
| 153 | if consecutiveNewlines <= 2 { |
| 154 | _, _ = b.WriteRune(r) |
| 155 | } |
| 156 | continue |
| 157 | } |
| 158 | consecutiveNewlines = 0 |
| 159 | _, _ = b.WriteRune(r) |
| 160 | } |
| 161 | return b.String() |
| 162 | } |
no test coverage detected