github.com/nutsdb/nutsdb@v1.0.4/iterator.go (about) 1 // Copyright 2023 The nutsdb Author. 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 // 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 nutsdb 16 17 import ( 18 "github.com/tidwall/btree" 19 ) 20 21 type Iterator struct { 22 tx *Tx 23 options IteratorOptions 24 iter btree.IterG[*Item] 25 } 26 27 type IteratorOptions struct { 28 Reverse bool 29 } 30 31 func NewIterator(tx *Tx, bucket string, options IteratorOptions) *Iterator { 32 b, err := tx.db.bm.GetBucket(DataStructureBTree, bucket) 33 if err != nil { 34 return nil 35 } 36 iterator := &Iterator{ 37 tx: tx, 38 options: options, 39 iter: tx.db.Index.bTree.getWithDefault(b.Id).btree.Iter(), 40 } 41 42 if options.Reverse { 43 iterator.iter.Last() 44 } else { 45 iterator.iter.First() 46 } 47 48 return iterator 49 } 50 51 func (it *Iterator) Rewind() bool { 52 if it.options.Reverse { 53 return it.iter.Last() 54 } else { 55 return it.iter.First() 56 } 57 } 58 59 func (it *Iterator) Seek(key []byte) bool { 60 return it.iter.Seek(&Item{key: key}) 61 } 62 63 func (it *Iterator) Next() bool { 64 if it.options.Reverse { 65 return it.iter.Prev() 66 } else { 67 return it.iter.Next() 68 } 69 } 70 71 func (it *Iterator) Valid() bool { 72 return it.iter.Item() != nil 73 } 74 75 func (it *Iterator) Key() []byte { 76 return it.iter.Item().key 77 } 78 79 func (it *Iterator) Value() ([]byte, error) { 80 return it.tx.db.getValueByRecord(it.iter.Item().record) 81 }