Skip to content

Commit 01a2b69

Browse files
committed
fix(isutf8): Fix token too long error
1 parent 97cde61 commit 01a2b69

File tree

1 file changed

+25
-19
lines changed

1 file changed

+25
-19
lines changed

cmd/isutf8/cmd.go

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bufio"
55
"errors"
66
"fmt"
7+
"io"
78
"os"
89
"unicode/utf8"
910

@@ -67,27 +68,32 @@ func checkFile(cmd *cobra.Command, path string) error {
6768
_ = f.Close()
6869
}()
6970

70-
scanner := bufio.NewScanner(f)
71-
var line, offset int64
72-
for scanner.Scan() {
73-
line++
74-
b := scanner.Bytes()
71+
buf := bufio.NewReader(f)
72+
line := int64(1)
73+
var i, offset int64
74+
for {
75+
r, size, err := buf.ReadRune()
76+
if err != nil {
77+
if errors.Is(err, io.EOF) {
78+
return nil
79+
}
80+
return err
81+
}
7582

76-
for i := 0; i < len(b); {
77-
if r, width := utf8.DecodeRune(b[i:]); width != 0 {
78-
if r == utf8.RuneError {
79-
if _, err := fmt.Fprintf(cmd.OutOrStdout(),
80-
"%s: line %d, char %d, byte %d\n",
81-
path, line, i, offset,
82-
); err != nil {
83-
return err
84-
}
85-
return fmt.Errorf("%s: %w", path, errNotUTF8)
86-
}
87-
i += width
88-
offset++
83+
switch r {
84+
case '\n':
85+
line++
86+
case utf8.RuneError:
87+
if _, err := fmt.Fprintf(cmd.OutOrStdout(),
88+
"%s: line %d, char %d, byte %d\n",
89+
path, line, i, offset,
90+
); err != nil {
91+
return err
8992
}
93+
return fmt.Errorf("%s: %w", path, errNotUTF8)
9094
}
95+
96+
i += int64(size)
97+
offset++
9198
}
92-
return scanner.Err()
9399
}

0 commit comments

Comments
 (0)