textlinescanner.go 709 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package iox
  2. import (
  3. "bufio"
  4. "io"
  5. "strings"
  6. )
  7. type TextLineScanner struct {
  8. reader *bufio.Reader
  9. hasNext bool
  10. line string
  11. err error
  12. }
  13. func NewTextLineScanner(reader io.Reader) *TextLineScanner {
  14. return &TextLineScanner{
  15. reader: bufio.NewReader(reader),
  16. hasNext: true,
  17. }
  18. }
  19. func (scanner *TextLineScanner) Scan() bool {
  20. if !scanner.hasNext {
  21. return false
  22. }
  23. line, err := scanner.reader.ReadString('\n')
  24. scanner.line = strings.TrimRight(line, "\n")
  25. if err == io.EOF {
  26. scanner.hasNext = false
  27. return true
  28. } else if err != nil {
  29. scanner.err = err
  30. return false
  31. }
  32. return true
  33. }
  34. func (scanner *TextLineScanner) Line() (string, error) {
  35. return scanner.line, scanner.err
  36. }