Skip to content

Commit 41a9946

Browse files
committed
format: start using go/token.File.Lines
While here, the slices package as well, both added in Go 1.21.
1 parent 5aa7546 commit 41a9946

File tree

1 file changed

+8
-19
lines changed

1 file changed

+8
-19
lines changed

format/format.go

+8-19
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"os"
1616
"reflect"
1717
"regexp"
18+
"slices"
1819
"sort"
1920
"strconv"
2021
"strings"
@@ -226,26 +227,14 @@ func (f *fumpter) inlineComment(pos token.Pos) *ast.Comment {
226227
func (f *fumpter) addNewline(at token.Pos) {
227228
offset := f.Offset(at)
228229

229-
// TODO: replace with the new Lines method once we require Go 1.21 or later
230-
field := reflect.ValueOf(f.file).Elem().FieldByName("lines")
231-
n := field.Len()
232-
lines := make([]int, 0, n+1)
233-
for i := 0; i < n; i++ {
234-
cur := int(field.Index(i).Int())
235-
if offset == cur {
236-
// This newline already exists; do nothing. Duplicate
237-
// newlines can't exist.
238-
return
239-
}
240-
if offset >= 0 && offset < cur {
241-
lines = append(lines, offset)
242-
offset = -1
243-
}
244-
lines = append(lines, cur)
245-
}
246-
if offset >= 0 {
247-
lines = append(lines, offset)
230+
lines := f.file.Lines()
231+
i, exists := slices.BinarySearch(lines, offset)
232+
if exists {
233+
// This newline already exists; do nothing. Duplicate
234+
// newlines can't exist.
235+
return
248236
}
237+
lines = slices.Insert(lines, i, offset)
249238
if !f.file.SetLines(lines) {
250239
panic(fmt.Sprintf("could not set lines to %v", lines))
251240
}

0 commit comments

Comments
 (0)