textlinescanner.go 940 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package iox
  2. import (
  3. "bufio"
  4. "io"
  5. "strings"
  6. )
  7. // A TextLineScanner is a scanner that can scan lines from given reader.
  8. type TextLineScanner struct {
  9. reader *bufio.Reader
  10. hasNext bool
  11. line string
  12. err error
  13. }
  14. // NewTextLineScanner returns a TextLineScanner with given reader.
  15. func NewTextLineScanner(reader io.Reader) *TextLineScanner {
  16. return &TextLineScanner{
  17. reader: bufio.NewReader(reader),
  18. hasNext: true,
  19. }
  20. }
  21. // Scan checks if scanner has more lines to read.
  22. func (scanner *TextLineScanner) Scan() bool {
  23. if !scanner.hasNext {
  24. return false
  25. }
  26. line, err := scanner.reader.ReadString('\n')
  27. scanner.line = strings.TrimRight(line, "\n")
  28. if err == io.EOF {
  29. scanner.hasNext = false
  30. return true
  31. } else if err != nil {
  32. scanner.err = err
  33. return false
  34. }
  35. return true
  36. }
  37. // Line returns the next available line.
  38. func (scanner *TextLineScanner) Line() (string, error) {
  39. return scanner.line, scanner.err
  40. }