github.com/searKing/golang/go@v1.2.74/container/stream/op/match/sink.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package match
     6  
     7  import (
     8  	"github.com/searKing/golang/go/container/stream/op/terminal"
     9  	"github.com/searKing/golang/go/util/function/predicate"
    10  	"github.com/searKing/golang/go/util/object"
    11  )
    12  
    13  /**
    14   * Boolean specific terminal sink to avoid the boxing costs when returning
    15   * results.  Subclasses implement the shape-specific functionality.
    16   *
    17   * @param <T> The output type of the stream pipeline
    18   */
    19  type booleanTerminalSink struct {
    20  	terminal.TODOSink
    21  	stop  bool
    22  	value bool
    23  }
    24  
    25  func (sink *booleanTerminalSink) AcceptMatchKind(matchKind Kind) {
    26  	sink.value = !matchKind.ShortCircuitResult
    27  }
    28  
    29  func (sink *booleanTerminalSink) GetAndClearState() bool {
    30  	return sink.value
    31  }
    32  
    33  func (sink *booleanTerminalSink) CancellationRequested() bool {
    34  	return sink.stop
    35  }
    36  
    37  type MatchSink struct {
    38  	booleanTerminalSink
    39  
    40  	matchKind Kind
    41  	predicate predicate.Predicater
    42  }
    43  
    44  func NewMatchSink(matchKind Kind, predicate predicate.Predicater) *MatchSink {
    45  	object.RequireNonNil(predicate)
    46  	sink := &MatchSink{
    47  		matchKind: matchKind,
    48  		predicate: predicate,
    49  	}
    50  	sink.AcceptMatchKind(matchKind)
    51  	sink.SetDerived(sink)
    52  	return sink
    53  }
    54  
    55  func (sink *MatchSink) Accept(value interface{}) {
    56  	if !sink.stop && sink.predicate.Test(value) == sink.matchKind.StopOnPredicateMatches {
    57  		sink.stop = true
    58  		sink.value = sink.matchKind.ShortCircuitResult
    59  	}
    60  }