encoding.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. import (
  18. "bytes"
  19. )
  20. func CompactEncode(hexSlice []byte) []byte {
  21. terminator := 0
  22. if hexSlice[len(hexSlice)-1] == 16 {
  23. terminator = 1
  24. }
  25. if terminator == 1 {
  26. hexSlice = hexSlice[:len(hexSlice)-1]
  27. }
  28. oddlen := len(hexSlice) % 2
  29. flags := byte(2*terminator + oddlen)
  30. if oddlen != 0 {
  31. hexSlice = append([]byte{flags}, hexSlice...)
  32. } else {
  33. hexSlice = append([]byte{flags, 0}, hexSlice...)
  34. }
  35. var buff bytes.Buffer
  36. for i := 0; i < len(hexSlice); i += 2 {
  37. buff.WriteByte(byte(16*hexSlice[i] + hexSlice[i+1]))
  38. }
  39. return buff.Bytes()
  40. }
  41. func CompactDecode(str []byte) []byte {
  42. base := CompactHexDecode(str)
  43. base = base[:len(base)-1]
  44. if base[0] >= 2 {
  45. base = append(base, 16)
  46. }
  47. if base[0]%2 == 1 {
  48. base = base[1:]
  49. } else {
  50. base = base[2:]
  51. }
  52. return base
  53. }
  54. func CompactHexDecode(str []byte) []byte {
  55. var nibbles []byte
  56. for _, b := range str {
  57. nibbles = append(nibbles, b/16)
  58. nibbles = append(nibbles, b%16)
  59. }
  60. nibbles = append(nibbles, 16)
  61. return nibbles
  62. }
  63. // assumes key is odd length
  64. func DecodeCompact(key []byte) []byte {
  65. var res []byte
  66. for i := 0; i < len(key)-1; i += 2 {
  67. v1, v0 := key[i], key[i+1]
  68. res = append(res, v1*16+v0)
  69. }
  70. return res
  71. }