encoding.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package trie
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "strings"
  21. )
  22. func CompactEncode(hexSlice []byte) string {
  23. terminator := 0
  24. if hexSlice[len(hexSlice)-1] == 16 {
  25. terminator = 1
  26. }
  27. if terminator == 1 {
  28. hexSlice = hexSlice[:len(hexSlice)-1]
  29. }
  30. oddlen := len(hexSlice) % 2
  31. flags := byte(2*terminator + oddlen)
  32. if oddlen != 0 {
  33. hexSlice = append([]byte{flags}, hexSlice...)
  34. } else {
  35. hexSlice = append([]byte{flags, 0}, hexSlice...)
  36. }
  37. var buff bytes.Buffer
  38. for i := 0; i < len(hexSlice); i += 2 {
  39. buff.WriteByte(byte(16*hexSlice[i] + hexSlice[i+1]))
  40. }
  41. return buff.String()
  42. }
  43. func CompactDecode(str string) []byte {
  44. base := CompactHexDecode(str)
  45. base = base[:len(base)-1]
  46. if base[0] >= 2 {
  47. base = append(base, 16)
  48. }
  49. if base[0]%2 == 1 {
  50. base = base[1:]
  51. } else {
  52. base = base[2:]
  53. }
  54. return base
  55. }
  56. func CompactHexDecode(str string) []byte {
  57. base := "0123456789abcdef"
  58. var hexSlice []byte
  59. enc := hex.EncodeToString([]byte(str))
  60. for _, v := range enc {
  61. hexSlice = append(hexSlice, byte(strings.IndexByte(base, byte(v))))
  62. }
  63. hexSlice = append(hexSlice, 16)
  64. return hexSlice
  65. }
  66. func DecodeCompact(key []byte) string {
  67. const base = "0123456789abcdef"
  68. var str string
  69. for _, v := range key {
  70. if v < 16 {
  71. str += string(base[v])
  72. }
  73. }
  74. res, _ := hex.DecodeString(str)
  75. return string(res)
  76. }