Last active
January 7, 2025 15:43
-
-
Save djale1k/a328bbb96e26ec304d320f60e8c5e87a to your computer and use it in GitHub Desktop.
Count file lines fast in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func LineCounter(r io.Reader) (int, error) { | |
buf := make([]byte, 32*1024) | |
count := 0 | |
lineSep := []byte{'\n'} | |
for { | |
c, err := r.Read(buf) | |
count += bytes.Count(buf[:c], lineSep) | |
switch { | |
case err == io.EOF: | |
return count, nil | |
case err != nil: | |
return count, err | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment