github.com/KEINOS/go-countline@v1.1.0/cl/_alt/alt1.go (about)

     1  //nolint:revive,stylecheck
     2  package _alt
     3  
     4  import (
     5  	"io"
     6  
     7  	"github.com/pkg/errors"
     8  	"golang.org/x/text/transform"
     9  )
    10  
    11  // ----------------------------------------------------------------------------
    12  //  CountLinesAlt1
    13  // ----------------------------------------------------------------------------
    14  
    15  // CountLinesAlt1 uses a Transformer to count the number of lines in a file.
    16  func CountLinesAlt1(inputReader io.Reader) (int, error) {
    17  	if inputReader == nil {
    18  		return 0, errors.New("given reader is nil")
    19  	}
    20  
    21  	bufReader := new(LineCounterAlt1)
    22  	transformer := transform.NewReader(inputReader, bufReader)
    23  
    24  	_, err := io.ReadAll(transformer)
    25  	if err != nil {
    26  		return 0, errors.Wrap(err, "failed to read the file")
    27  	}
    28  
    29  	count := bufReader.Count
    30  	if bufReader.HasFragments {
    31  		count++
    32  	}
    33  
    34  	return count, nil
    35  }
    36  
    37  type LineCounterAlt1 struct {
    38  	LenRead      int
    39  	Count        int
    40  	HasFragments bool
    41  }
    42  
    43  // Transform is the implementation of the Transformer interface.
    44  //
    45  //nolint:nonamedreturns // named returns are used for clarity to match the interface
    46  func (lc *LineCounterAlt1) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
    47  	readBytes := 0
    48  
    49  	for _, value := range src {
    50  		readBytes++
    51  
    52  		if value == '\n' {
    53  			lc.Count++
    54  			lc.HasFragments = false
    55  
    56  			continue
    57  		}
    58  
    59  		lc.HasFragments = true
    60  	}
    61  
    62  	lc.LenRead += readBytes
    63  
    64  	return readBytes, readBytes, nil
    65  }
    66  
    67  func (lc *LineCounterAlt1) Reset() {
    68  	lc.LenRead = 0
    69  	lc.Count = 0
    70  	lc.HasFragments = false
    71  }