github.com/amazechain/amc@v0.1.3/modules/ethdb/kv_util.go (about)

     1  // Copyright 2023 The AmazeChain Authors
     2  // This file is part of the AmazeChain library.
     3  //
     4  // The AmazeChain library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The AmazeChain library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package ethdb
    18  
    19  import (
    20  	"bytes"
    21  
    22  	"github.com/ledgerwatch/erigon-lib/kv"
    23  )
    24  
    25  func Walk(c kv.Cursor, startkey []byte, fixedbits int, walker func(k, v []byte) (bool, error)) error {
    26  	fixedbytes, mask := Bytesmask(fixedbits)
    27  	k, v, err := c.Seek(startkey)
    28  	if err != nil {
    29  		return err
    30  	}
    31  	for k != nil && len(k) >= fixedbytes && (fixedbits == 0 || bytes.Equal(k[:fixedbytes-1], startkey[:fixedbytes-1]) && (k[fixedbytes-1]&mask) == (startkey[fixedbytes-1]&mask)) {
    32  		goOn, err := walker(k, v)
    33  		if err != nil {
    34  			return err
    35  		}
    36  		if !goOn {
    37  			break
    38  		}
    39  		k, v, err = c.Next()
    40  		if err != nil {
    41  			return err
    42  		}
    43  	}
    44  	return nil
    45  }
    46  
    47  func Bytesmask(fixedbits int) (fixedbytes int, mask byte) {
    48  	fixedbytes = (fixedbits + 7) / 8
    49  	shiftbits := fixedbits & 7
    50  	mask = byte(0xff)
    51  	if shiftbits != 0 {
    52  		mask = 0xff << (8 - shiftbits)
    53  	}
    54  	return fixedbytes, mask
    55  }