github.com/ledgerwatch/erigon-lib@v1.0.0/kv/iter/helpers.go (about) 1 /* 2 Copyright 2021 Erigon contributors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package iter 18 19 import ( 20 "fmt" 21 "testing" 22 23 "github.com/stretchr/testify/require" 24 ) 25 26 func ToArr[T any](s Unary[T]) (res []T, err error) { 27 for s.HasNext() { 28 k, err := s.Next() 29 if err != nil { 30 return res, err 31 } 32 res = append(res, k) 33 } 34 return res, nil 35 } 36 37 func ToDualArray[K, V any](s Dual[K, V]) (keys []K, values []V, err error) { 38 for s.HasNext() { 39 k, v, err := s.Next() 40 if err != nil { 41 return keys, values, err 42 } 43 keys = append(keys, k) 44 values = append(values, v) 45 } 46 return keys, values, nil 47 } 48 49 func ExpectEqualU64(tb testing.TB, s1, s2 Unary[uint64]) { 50 tb.Helper() 51 ExpectEqual[uint64](tb, s1, s2) 52 } 53 func ExpectEqual[V comparable](tb testing.TB, s1, s2 Unary[V]) { 54 tb.Helper() 55 for s1.HasNext() && s2.HasNext() { 56 k1, e1 := s1.Next() 57 k2, e2 := s2.Next() 58 require.Equal(tb, e1 == nil, e2 == nil) 59 require.Equal(tb, k1, k2) 60 } 61 62 has1 := s1.HasNext() 63 has2 := s2.HasNext() 64 var label string 65 if has1 { 66 v1, _ := s1.Next() 67 label = fmt.Sprintf("v1: %v", v1) 68 } 69 if has2 { 70 v2, _ := s2.Next() 71 label += fmt.Sprintf(" v2: %v", v2) 72 } 73 require.False(tb, has1, label) 74 require.False(tb, has2, label) 75 } 76 77 // PairsWithErrorIter - return N, keys and then error 78 type PairsWithErrorIter struct { 79 errorAt, i int 80 } 81 82 func PairsWithError(errorAt int) *PairsWithErrorIter { 83 return &PairsWithErrorIter{errorAt: errorAt} 84 } 85 func (m *PairsWithErrorIter) HasNext() bool { return true } 86 func (m *PairsWithErrorIter) Next() ([]byte, []byte, error) { 87 if m.i >= m.errorAt { 88 return nil, nil, fmt.Errorf("expected error at iteration: %d", m.errorAt) 89 } 90 m.i++ 91 return []byte(fmt.Sprintf("%x", m.i)), []byte(fmt.Sprintf("%x", m.i)), nil 92 } 93 94 func Count[T any](s Unary[T]) (cnt int, err error) { 95 for s.HasNext() { 96 _, err := s.Next() 97 if err != nil { 98 return cnt, err 99 } 100 cnt++ 101 } 102 return cnt, err 103 } 104 105 func CountDual[K, V any](s Dual[K, V]) (cnt int, err error) { 106 for s.HasNext() { 107 _, _, err := s.Next() 108 if err != nil { 109 return cnt, err 110 } 111 cnt++ 112 } 113 return cnt, err 114 }