github.com/cockroachdb/pebble@v0.0.0-20231214172447-ab4952c5f87b/internal/keyspan/transformer.go (about)

     1  // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
     2  // of this source code is governed by a BSD-style license that can be found in
     3  // the LICENSE file.
     4  
     5  package keyspan
     6  
     7  import "github.com/cockroachdb/pebble/internal/base"
     8  
     9  // Transformer defines a transformation to be applied to a Span.
    10  type Transformer interface {
    11  	// Transform takes a Span as input and writes the transformed Span to the
    12  	// provided output *Span pointer. The output Span's Keys slice may be reused
    13  	// by Transform to reduce allocations.
    14  	Transform(cmp base.Compare, in Span, out *Span) error
    15  }
    16  
    17  // The TransformerFunc type is an adapter to allow the use of ordinary functions
    18  // as Transformers. If f is a function with the appropriate signature,
    19  // TransformerFunc(f) is a Transformer that calls f.
    20  type TransformerFunc func(base.Compare, Span, *Span) error
    21  
    22  // Transform calls f(cmp, in, out).
    23  func (tf TransformerFunc) Transform(cmp base.Compare, in Span, out *Span) error {
    24  	return tf(cmp, in, out)
    25  }
    26  
    27  var noopTransform Transformer = TransformerFunc(func(_ base.Compare, s Span, dst *Span) error {
    28  	dst.Start, dst.End = s.Start, s.End
    29  	dst.Keys = append(dst.Keys[:0], s.Keys...)
    30  	return nil
    31  })
    32  
    33  // VisibleTransform filters keys that are invisible at the provided snapshot
    34  // sequence number.
    35  func VisibleTransform(snapshot uint64) Transformer {
    36  	return TransformerFunc(func(_ base.Compare, s Span, dst *Span) error {
    37  		dst.Start, dst.End = s.Start, s.End
    38  		dst.Keys = dst.Keys[:0]
    39  		for _, k := range s.Keys {
    40  			// NB: The InternalKeySeqNumMax value is used for the batch snapshot
    41  			// because a batch's visible span keys are filtered when they're
    42  			// fragmented. There's no requirement to enforce visibility at
    43  			// iteration time.
    44  			if base.Visible(k.SeqNum(), snapshot, base.InternalKeySeqNumMax) {
    45  				dst.Keys = append(dst.Keys, k)
    46  			}
    47  		}
    48  		return nil
    49  	})
    50  }