node_enc.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2022 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. "github.com/ethereum/go-ethereum/rlp"
  19. )
  20. func nodeToBytes(n node) []byte {
  21. w := rlp.NewEncoderBuffer(nil)
  22. n.encode(w)
  23. result := w.ToBytes()
  24. w.Flush()
  25. return result
  26. }
  27. func (n *fullNode) encode(w rlp.EncoderBuffer) {
  28. offset := w.List()
  29. for _, c := range n.Children {
  30. if c != nil {
  31. c.encode(w)
  32. } else {
  33. w.Write(rlp.EmptyString)
  34. }
  35. }
  36. w.ListEnd(offset)
  37. }
  38. func (n *shortNode) encode(w rlp.EncoderBuffer) {
  39. offset := w.List()
  40. w.WriteBytes(n.Key)
  41. if n.Val != nil {
  42. n.Val.encode(w)
  43. } else {
  44. w.Write(rlp.EmptyString)
  45. }
  46. w.ListEnd(offset)
  47. }
  48. func (n hashNode) encode(w rlp.EncoderBuffer) {
  49. w.WriteBytes(n)
  50. }
  51. func (n valueNode) encode(w rlp.EncoderBuffer) {
  52. w.WriteBytes(n)
  53. }
  54. func (n rawFullNode) encode(w rlp.EncoderBuffer) {
  55. offset := w.List()
  56. for _, c := range n {
  57. if c != nil {
  58. c.encode(w)
  59. } else {
  60. w.Write(rlp.EmptyString)
  61. }
  62. }
  63. w.ListEnd(offset)
  64. }
  65. func (n *rawShortNode) encode(w rlp.EncoderBuffer) {
  66. offset := w.List()
  67. w.WriteBytes(n.Key)
  68. if n.Val != nil {
  69. n.Val.encode(w)
  70. } else {
  71. w.Write(rlp.EmptyString)
  72. }
  73. w.ListEnd(offset)
  74. }
  75. func (n rawNode) encode(w rlp.EncoderBuffer) {
  76. w.Write(n)
  77. }