amuz.es/src/infra/goutils@v0.1.3/io/remover.go (about)

     1  package io
     2  
     3  import (
     4  	"golang.org/x/text/transform"
     5  )
     6  
     7  const (
     8  	linefeed                        = '\n'
     9  	LineFeedRemover linefeedRemover = iota
    10  )
    11  
    12  type linefeedRemover int
    13  
    14  func (linefeedRemover) Reset() {}
    15  func (linefeedRemover) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
    16  	cur, start := 0, 0
    17  	for ; cur < len(src); {
    18  		if src[cur] == linefeed {
    19  			if nDst+1 > len(dst) {
    20  				err = transform.ErrShortDst
    21  				return
    22  			}
    23  			nSrc += cur - start
    24  			nDst += copy(dst[nDst:], src[start:cur])
    25  			cur++
    26  			start = cur
    27  		} else {
    28  			cur++
    29  		}
    30  	}
    31  	if remain := cur - start; remain == 0 {
    32  	} else if nDst+1 > len(dst) {
    33  		err = transform.ErrShortDst
    34  	} else {
    35  		nSrc += remain
    36  		nDst += copy(dst[nDst:], src[start:cur])
    37  	}
    38  	return
    39  }
    40  
    41  type Remover struct {
    42  	Removes []byte
    43  }
    44  
    45  func (r *Remover) Reset() {}
    46  func (r *Remover) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
    47  	cur, start := 0, 0
    48  
    49  	for ; cur < len(src); {
    50  		var (
    51  			curData = src[cur]
    52  			matched = false
    53  		)
    54  		for i := 0; i < len(r.Removes); i++ {
    55  			if matched = r.Removes[i] == curData; matched {
    56  				break
    57  			}
    58  		}
    59  		if matched {
    60  			if nDst+1 > len(dst) {
    61  				err = transform.ErrShortDst
    62  				return
    63  			}
    64  			nSrc += cur - start
    65  			nDst += copy(dst[nDst:], src[start:cur])
    66  			cur++
    67  			start = cur
    68  		} else {
    69  			cur++
    70  		}
    71  	}
    72  	if remain := cur - start; remain == 0 {
    73  	} else if nDst+1 > len(dst) {
    74  		err = transform.ErrShortDst
    75  	} else {
    76  		nSrc += remain
    77  		nDst += copy(dst[nDst:], src[start:cur])
    78  	}
    79  	return
    80  }