github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/chain/trie/encoding.go (about)

     1  package trie
     2  
     3  func hexToCompact(hex []byte) []byte {
     4  	terminator := byte(0)
     5  	if hasTerm(hex) {
     6  		terminator = 1
     7  		hex = hex[:len(hex)-1]
     8  	}
     9  	buf := make([]byte, len(hex)/2+1)
    10  	buf[0] = terminator << 5
    11  	if len(hex)&1 == 1 {
    12  		buf[0] |= 1 << 4
    13  		buf[0] |= hex[0]
    14  		hex = hex[1:]
    15  	}
    16  	decodeNibbles(hex, buf[1:])
    17  	return buf
    18  }
    19  
    20  func compactToHex(compact []byte) []byte {
    21  	if len(compact) == 0 {
    22  		return compact
    23  	}
    24  	base := keybytesToHex(compact)
    25  
    26  	if base[0] < 2 {
    27  		base = base[:len(base)-1]
    28  	}
    29  
    30  	chop := 2 - base[0]&1
    31  	return base[chop:]
    32  }
    33  
    34  func keybytesToHex(str []byte) []byte {
    35  	l := len(str)*2 + 1
    36  	var nibbles = make([]byte, l)
    37  	for i, b := range str {
    38  		nibbles[i*2] = b / 16
    39  		nibbles[i*2+1] = b % 16
    40  	}
    41  	nibbles[l-1] = 16
    42  	return nibbles
    43  }
    44  
    45  func hexToKeybytes(hex []byte) []byte {
    46  	if hasTerm(hex) {
    47  		hex = hex[:len(hex)-1]
    48  	}
    49  	if len(hex)&1 != 0 {
    50  		panic("can't convert hex key of odd length")
    51  	}
    52  	key := make([]byte, len(hex)/2)
    53  	decodeNibbles(hex, key)
    54  	return key
    55  }
    56  
    57  func decodeNibbles(nibbles []byte, bytes []byte) {
    58  	for bi, ni := 0, 0; ni < len(nibbles); bi, ni = bi+1, ni+2 {
    59  		bytes[bi] = nibbles[ni]<<4 | nibbles[ni+1]
    60  	}
    61  }
    62  
    63  func prefixLen(a, b []byte) int {
    64  	var i, length = 0, len(a)
    65  	if len(b) < length {
    66  		length = len(b)
    67  	}
    68  	for ; i < length; i++ {
    69  		if a[i] != b[i] {
    70  			break
    71  		}
    72  	}
    73  	return i
    74  }
    75  
    76  func hasTerm(s []byte) bool {
    77  	return len(s) > 0 && s[len(s)-1] == 16
    78  }