github.com/lingyao2333/mo-zero@v1.4.1/core/iox/textlinescanner.go (about)

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