@@ -15,6 +15,7 @@ import (
15
15
"os"
16
16
"reflect"
17
17
"regexp"
18
+ "slices"
18
19
"sort"
19
20
"strconv"
20
21
"strings"
@@ -226,26 +227,14 @@ func (f *fumpter) inlineComment(pos token.Pos) *ast.Comment {
226
227
func (f * fumpter ) addNewline (at token.Pos ) {
227
228
offset := f .Offset (at )
228
229
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
248
236
}
237
+ lines = slices .Insert (lines , i , offset )
249
238
if ! f .file .SetLines (lines ) {
250
239
panic (fmt .Sprintf ("could not set lines to %v" , lines ))
251
240
}
0 commit comments