remove: countlines from textreader

This commit is contained in:
Inanc Gumus
2019-08-08 17:19:46 +03:00
parent 43d25a4180
commit 5d5c656413
2 changed files with 24 additions and 33 deletions

View File

@ -9,30 +9,20 @@ package main
import ( import (
"bufio" "bufio"
"bytes"
"fmt" "fmt"
"io" "io"
"os"
"strings" "strings"
) )
func textReader(r io.Reader) inputFn { func textReader(r io.Reader) inputFn {
return func() ([]result, error) { return func() ([]result, error) {
// first: count the lines, so the parseText can create return parseText(bufio.NewScanner(r))
// enough buffer.
var buf bytes.Buffer
lines, err := countLines(io.TeeReader(r, &buf))
if err != nil {
return nil, err
}
return parseText(bufio.NewScanner(&buf), lines)
} }
} }
// TODO: custom error type for line information // TODO: custom error type for line information
func parseText(in *bufio.Scanner, nlines int) ([]result, error) { func parseText(in *bufio.Scanner) ([]result, error) {
res := make([]result, 0, nlines) var res []result
for l := 1; in.Scan(); l++ { for l := 1; in.Scan(); l++ {
fields := strings.Fields(in.Text()) fields := strings.Fields(in.Text())
@ -46,23 +36,3 @@ func parseText(in *bufio.Scanner, nlines int) ([]result, error) {
return res, in.Err() return res, in.Err()
} }
func countLines(r io.Reader) (int, error) {
var (
lines int
buf = make([]byte, os.Getpagesize()) // read via 16 KB blocks
)
for {
n, err := r.Read(buf)
lines += bytes.Count(buf[:n], []byte{'\n'})
if err == io.EOF {
return lines, nil
}
if err != nil {
return lines, err
}
}
}

View File

@ -13,6 +13,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"os"
) )
// this could be made faster. // this could be made faster.
@ -106,3 +107,23 @@ func atoi(input []byte) (int, error) {
} }
return val, nil return val, nil
} }
func countLines(r io.Reader) (int, error) {
var (
lines int
buf = make([]byte, os.Getpagesize()) // read via 16 KB blocks
)
for {
n, err := r.Read(buf)
lines += bytes.Count(buf[:n], []byte{'\n'})
if err == io.EOF {
return lines, nil
}
if err != nil {
return lines, err
}
}
}