github.com/karalabe/go-ethereum@v0.8.5/trie/encoding.go (about) 1 package trie 2 3 import ( 4 "bytes" 5 "encoding/hex" 6 "strings" 7 ) 8 9 func CompactEncode(hexSlice []byte) string { 10 terminator := 0 11 if hexSlice[len(hexSlice)-1] == 16 { 12 terminator = 1 13 } 14 15 if terminator == 1 { 16 hexSlice = hexSlice[:len(hexSlice)-1] 17 } 18 19 oddlen := len(hexSlice) % 2 20 flags := byte(2*terminator + oddlen) 21 if oddlen != 0 { 22 hexSlice = append([]byte{flags}, hexSlice...) 23 } else { 24 hexSlice = append([]byte{flags, 0}, hexSlice...) 25 } 26 27 var buff bytes.Buffer 28 for i := 0; i < len(hexSlice); i += 2 { 29 buff.WriteByte(byte(16*hexSlice[i] + hexSlice[i+1])) 30 } 31 32 return buff.String() 33 } 34 35 func CompactDecode(str string) []byte { 36 base := CompactHexDecode(str) 37 base = base[:len(base)-1] 38 if base[0] >= 2 { 39 base = append(base, 16) 40 } 41 if base[0]%2 == 1 { 42 base = base[1:] 43 } else { 44 base = base[2:] 45 } 46 47 return base 48 } 49 50 func CompactHexDecode(str string) []byte { 51 base := "0123456789abcdef" 52 var hexSlice []byte 53 54 enc := hex.EncodeToString([]byte(str)) 55 for _, v := range enc { 56 hexSlice = append(hexSlice, byte(strings.IndexByte(base, byte(v)))) 57 } 58 hexSlice = append(hexSlice, 16) 59 60 return hexSlice 61 } 62 63 func DecodeCompact(key []byte) string { 64 const base = "0123456789abcdef" 65 var str string 66 67 for _, v := range key { 68 if v < 16 { 69 str += string(base[v]) 70 } 71 } 72 73 res, _ := hex.DecodeString(str) 74 75 return string(res) 76 }