github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/doltcore/table/map_point_reader.go (about)

     1  // Copyright 2020 Dolthub, Inc.
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package table
    16  
    17  import (
    18  	"context"
    19  	"io"
    20  
    21  	"github.com/dolthub/dolt/go/store/types"
    22  )
    23  
    24  type PointReader struct {
    25  	m          types.Map
    26  	emptyTuple types.Tuple
    27  	keys       []types.Tuple
    28  	idx        int
    29  }
    30  
    31  var _ types.MapIterator = &PointReader{}
    32  
    33  // read the map values for a set of map keys
    34  func NewMapPointReader(m types.Map, keys ...types.Tuple) types.MapIterator {
    35  	return &PointReader{
    36  		m:          m,
    37  		emptyTuple: types.EmptyTuple(m.Format()),
    38  		keys:       keys,
    39  	}
    40  }
    41  
    42  // Next implements types.MapIterator.
    43  func (pr *PointReader) Next(ctx context.Context) (k, v types.Value, err error) {
    44  	kt, vt, err := pr.NextTuple(ctx)
    45  
    46  	if err != nil {
    47  		return nil, nil, err
    48  	}
    49  
    50  	if !kt.Empty() {
    51  		k = kt
    52  	}
    53  
    54  	if !vt.Empty() {
    55  		v = vt
    56  	}
    57  
    58  	return k, v, nil
    59  }
    60  
    61  // NextTuple implements types.MapIterator.
    62  func (pr *PointReader) NextTuple(ctx context.Context) (k, v types.Tuple, err error) {
    63  	if pr.idx >= len(pr.keys) {
    64  		return types.Tuple{}, types.Tuple{}, io.EOF
    65  	}
    66  
    67  	k = pr.keys[pr.idx]
    68  	v = pr.emptyTuple
    69  
    70  	var ok bool
    71  	// todo: optimize by implementing MapIterator.Seek()
    72  	v, ok, err = pr.m.MaybeGetTuple(ctx, k)
    73  	pr.idx++
    74  
    75  	if err != nil {
    76  		return types.Tuple{}, types.Tuple{}, err
    77  	} else if !ok {
    78  		return k, pr.emptyTuple, nil
    79  	}
    80  
    81  	return k, v, nil
    82  }