encoding.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library 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. // The go-ethereum library 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package trie
  17. func CompactEncode(hexSlice []byte) []byte {
  18. terminator := 0
  19. if hexSlice[len(hexSlice)-1] == 16 {
  20. terminator = 1
  21. }
  22. if terminator == 1 {
  23. hexSlice = hexSlice[:len(hexSlice)-1]
  24. }
  25. oddlen := len(hexSlice) % 2
  26. flags := byte(2*terminator + oddlen)
  27. if oddlen != 0 {
  28. hexSlice = append([]byte{flags}, hexSlice...)
  29. } else {
  30. hexSlice = append([]byte{flags, 0}, hexSlice...)
  31. }
  32. l := len(hexSlice) / 2
  33. var buf = make([]byte, l)
  34. for i := 0; i < l; i++ {
  35. buf[i] = 16*hexSlice[2*i] + hexSlice[2*i+1]
  36. }
  37. return buf
  38. }
  39. func CompactDecode(str []byte) []byte {
  40. base := CompactHexDecode(str)
  41. base = base[:len(base)-1]
  42. if base[0] >= 2 {
  43. base = append(base, 16)
  44. }
  45. if base[0]%2 == 1 {
  46. base = base[1:]
  47. } else {
  48. base = base[2:]
  49. }
  50. return base
  51. }
  52. func CompactHexDecode(str []byte) []byte {
  53. l := len(str)*2 + 1
  54. var nibbles = make([]byte, l)
  55. for i, b := range str {
  56. nibbles[i*2] = b / 16
  57. nibbles[i*2+1] = b % 16
  58. }
  59. nibbles[l-1] = 16
  60. return nibbles
  61. }
  62. func DecodeCompact(key []byte) []byte {
  63. l := len(key) / 2
  64. var res = make([]byte, l)
  65. for i := 0; i < l; i++ {
  66. v1, v0 := key[2*i], key[2*i+1]
  67. res[i] = v1*16 + v0
  68. }
  69. return res
  70. }