github.com/neohugo/neohugo@v0.123.8/common/hugio/hasBytesWriter.go (about)

     1  // Copyright 2024 The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package hugio
    15  
    16  import (
    17  	"bytes"
    18  )
    19  
    20  // HasBytesWriter is a writer that will set Match to true if the given pattern
    21  // is found in the stream.
    22  type HasBytesWriter struct {
    23  	Match   bool
    24  	Pattern []byte
    25  
    26  	i    int
    27  	done bool
    28  	buff []byte
    29  }
    30  
    31  func (h *HasBytesWriter) Write(p []byte) (n int, err error) {
    32  	if h.done {
    33  		return len(p), nil
    34  	}
    35  
    36  	if len(h.buff) == 0 {
    37  		h.buff = make([]byte, len(h.Pattern)*2)
    38  	}
    39  
    40  	for i := range p {
    41  		h.buff[h.i] = p[i]
    42  		h.i++
    43  		if h.i == len(h.buff) {
    44  			// Shift left.
    45  			copy(h.buff, h.buff[len(h.buff)/2:])
    46  			h.i = len(h.buff) / 2
    47  		}
    48  
    49  		if bytes.Contains(h.buff, h.Pattern) {
    50  			h.Match = true
    51  			h.done = true
    52  			return len(p), nil
    53  		}
    54  	}
    55  
    56  	return len(p), nil
    57  }