go-zero/core/iox/textlinescanner.go

47 lines
940 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package iox
import (
"bufio"
"io"
"strings"
)
2021-02-19 18:40:26 +08:00
// A TextLineScanner is a scanner that can scan lines from given reader.
2020-07-26 17:09:05 +08:00
type TextLineScanner struct {
reader *bufio.Reader
hasNext bool
line string
err error
}
2021-02-19 18:40:26 +08:00
// NewTextLineScanner returns a TextLineScanner with given reader.
2020-07-26 17:09:05 +08:00
func NewTextLineScanner(reader io.Reader) *TextLineScanner {
return &TextLineScanner{
reader: bufio.NewReader(reader),
hasNext: true,
}
}
2021-02-19 18:40:26 +08:00
// Scan checks if scanner has more lines to read.
2020-07-26 17:09:05 +08:00
func (scanner *TextLineScanner) Scan() bool {
if !scanner.hasNext {
return false
}
line, err := scanner.reader.ReadString('\n')
scanner.line = strings.TrimRight(line, "\n")
if err == io.EOF {
scanner.hasNext = false
return true
} else if err != nil {
scanner.err = err
return false
}
return true
}
2021-02-19 18:40:26 +08:00
// Line returns the next available line.
2020-07-26 17:09:05 +08:00
func (scanner *TextLineScanner) Line() (string, error) {
return scanner.line, scanner.err
}