github.com/tendermint/tmlibs@v0.9.0/db/util.go (about)

     1  package db
     2  
     3  import (
     4  	"bytes"
     5  )
     6  
     7  func cp(bz []byte) (ret []byte) {
     8  	ret = make([]byte, len(bz))
     9  	copy(ret, bz)
    10  	return ret
    11  }
    12  
    13  // Returns a slice of the same length (big endian)
    14  // except incremented by one.
    15  // Returns nil on overflow (e.g. if bz bytes are all 0xFF)
    16  // CONTRACT: len(bz) > 0
    17  func cpIncr(bz []byte) (ret []byte) {
    18  	if len(bz) == 0 {
    19  		panic("cpIncr expects non-zero bz length")
    20  	}
    21  	ret = cp(bz)
    22  	for i := len(bz) - 1; i >= 0; i-- {
    23  		if ret[i] < byte(0xFF) {
    24  			ret[i]++
    25  			return
    26  		}
    27  		ret[i] = byte(0x00)
    28  		if i == 0 {
    29  			// Overflow
    30  			return nil
    31  		}
    32  	}
    33  	return nil
    34  }
    35  
    36  // Returns a slice of the same length (big endian)
    37  // except decremented by one.
    38  // Returns nil on underflow (e.g. if bz bytes are all 0x00)
    39  // CONTRACT: len(bz) > 0
    40  func cpDecr(bz []byte) (ret []byte) {
    41  	if len(bz) == 0 {
    42  		panic("cpDecr expects non-zero bz length")
    43  	}
    44  	ret = cp(bz)
    45  	for i := len(bz) - 1; i >= 0; i-- {
    46  		if ret[i] > byte(0x00) {
    47  			ret[i]--
    48  			return
    49  		}
    50  		ret[i] = byte(0xFF)
    51  		if i == 0 {
    52  			// Underflow
    53  			return nil
    54  		}
    55  	}
    56  	return nil
    57  }
    58  
    59  // See DB interface documentation for more information.
    60  func IsKeyInDomain(key, start, end []byte, isReverse bool) bool {
    61  	if !isReverse {
    62  		if bytes.Compare(key, start) < 0 {
    63  			return false
    64  		}
    65  		if end != nil && bytes.Compare(end, key) <= 0 {
    66  			return false
    67  		}
    68  		return true
    69  	} else {
    70  		if start != nil && bytes.Compare(start, key) < 0 {
    71  			return false
    72  		}
    73  		if end != nil && bytes.Compare(key, end) <= 0 {
    74  			return false
    75  		}
    76  		return true
    77  	}
    78  }