encoding.go 1.3 KB

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