aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/test/testhelpers/remove_lines.go
blob: 214a2627a87a8b95979650bb10bffc655f821f47 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package testhelpers

import (
	"fmt"
	"sort"
	"strings"
)

func RemoveLines(str string, lines ...int) (string, error) {
	if len(lines) == 0 {
		return str, nil
	}

	sort.Ints(lines)

	var b strings.Builder
	b.Grow(len(str))

	var count int
	var start int
	var lineID int
	for i, s := range str {
		if s != '\n' {
			continue
		}

		if lines[lineID] != count {
			b.WriteString(str[start:i])
			b.WriteString("\n")
		} else {
			lineID++
			if len(lines) <= lineID {
				b.WriteString(str[i+1:])
				break
			}
		}

		count++
		start = i + 1
	}

	if len(lines) > lineID {
		return str, fmt.Errorf("not all lines were removed: processed line ids before %d for lines %d", lineID, lines)
	}

	return b.String(), nil
}