iterator_fast.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. // Copyright 2019 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 snapshot
  17. import (
  18. "bytes"
  19. "fmt"
  20. "sort"
  21. "github.com/ethereum/go-ethereum/common"
  22. )
  23. type weightedIterator struct {
  24. it AccountIterator
  25. priority int
  26. }
  27. // fastAccountIterator is a more optimized multi-layer iterator which maintains a
  28. // direct mapping of all iterators leading down to the bottom layer
  29. type fastAccountIterator struct {
  30. iterators []*weightedIterator
  31. initiated bool
  32. fail error
  33. }
  34. // newFastAccountIterator creates a new fastAccountIterator
  35. func (dl *diffLayer) newFastAccountIterator() AccountIterator {
  36. f := &fastAccountIterator{
  37. initiated: false,
  38. }
  39. for i, it := range dl.iterators() {
  40. f.iterators = append(f.iterators, &weightedIterator{it, -i})
  41. }
  42. f.Seek(common.Hash{})
  43. return f
  44. }
  45. // Len returns the number of active iterators
  46. func (fi *fastAccountIterator) Len() int {
  47. return len(fi.iterators)
  48. }
  49. // Less implements sort.Interface
  50. func (fi *fastAccountIterator) Less(i, j int) bool {
  51. a := fi.iterators[i].it.Key()
  52. b := fi.iterators[j].it.Key()
  53. bDiff := bytes.Compare(a[:], b[:])
  54. if bDiff < 0 {
  55. return true
  56. }
  57. if bDiff > 0 {
  58. return false
  59. }
  60. // keys are equal, sort by iterator priority
  61. return fi.iterators[i].priority < fi.iterators[j].priority
  62. }
  63. // Swap implements sort.Interface
  64. func (fi *fastAccountIterator) Swap(i, j int) {
  65. fi.iterators[i], fi.iterators[j] = fi.iterators[j], fi.iterators[i]
  66. }
  67. func (fi *fastAccountIterator) Seek(key common.Hash) {
  68. // We need to apply this across all iterators
  69. var seen = make(map[common.Hash]int)
  70. length := len(fi.iterators)
  71. for i := 0; i < len(fi.iterators); i++ {
  72. //for i, it := range fi.iterators {
  73. it := fi.iterators[i]
  74. it.it.Seek(key)
  75. for {
  76. if !it.it.Next() {
  77. // To be removed
  78. // swap it to the last position for now
  79. fi.iterators[i], fi.iterators[length-1] = fi.iterators[length-1], fi.iterators[i]
  80. length--
  81. break
  82. }
  83. v := it.it.Key()
  84. if other, exist := seen[v]; !exist {
  85. seen[v] = i
  86. break
  87. } else {
  88. // This whole else-block can be avoided, if we instead
  89. // do an inital priority-sort of the iterators. If we do that,
  90. // then we'll only wind up here if a lower-priority (preferred) iterator
  91. // has the same value, and then we will always just continue.
  92. // However, it costs an extra sort, so it's probably not better
  93. // One needs to be progressed, use priority to determine which
  94. if fi.iterators[other].priority < it.priority {
  95. // the 'it' should be progressed
  96. continue
  97. } else {
  98. // the 'other' should be progressed - swap them
  99. it = fi.iterators[other]
  100. fi.iterators[other], fi.iterators[i] = fi.iterators[i], fi.iterators[other]
  101. continue
  102. }
  103. }
  104. }
  105. }
  106. // Now remove those that were placed in the end
  107. fi.iterators = fi.iterators[:length]
  108. // The list is now totally unsorted, need to re-sort the entire list
  109. sort.Sort(fi)
  110. fi.initiated = false
  111. }
  112. // Next implements the Iterator interface. It returns false if no more elemnts
  113. // can be retrieved (false == exhausted)
  114. func (fi *fastAccountIterator) Next() bool {
  115. if len(fi.iterators) == 0 {
  116. return false
  117. }
  118. if !fi.initiated {
  119. // Don't forward first time -- we had to 'Next' once in order to
  120. // do the sorting already
  121. fi.initiated = true
  122. return true
  123. }
  124. return fi.innerNext(0)
  125. }
  126. // innerNext handles the next operation internally,
  127. // and should be invoked when we know that two elements in the list may have
  128. // the same value.
  129. // For example, if the list becomes [2,3,5,5,8,9,10], then we should invoke
  130. // innerNext(3), which will call Next on elem 3 (the second '5'). It will continue
  131. // along the list and apply the same operation if needed
  132. func (fi *fastAccountIterator) innerNext(pos int) bool {
  133. if !fi.iterators[pos].it.Next() {
  134. //Exhausted, remove this iterator
  135. fi.remove(pos)
  136. if len(fi.iterators) == 0 {
  137. return false
  138. }
  139. return true
  140. }
  141. if pos == len(fi.iterators)-1 {
  142. // Only one iterator left
  143. return true
  144. }
  145. // We next:ed the elem at 'pos'. Now we may have to re-sort that elem
  146. var (
  147. current, neighbour = fi.iterators[pos], fi.iterators[pos+1]
  148. val, neighbourVal = current.it.Key(), neighbour.it.Key()
  149. )
  150. if diff := bytes.Compare(val[:], neighbourVal[:]); diff < 0 {
  151. // It is still in correct place
  152. return true
  153. } else if diff == 0 && current.priority < neighbour.priority {
  154. // So still in correct place, but we need to iterate on the neighbour
  155. fi.innerNext(pos + 1)
  156. return true
  157. }
  158. // At this point, the elem is in the wrong location, but the
  159. // remaining list is sorted. Find out where to move the elem
  160. iteratee := -1
  161. index := sort.Search(len(fi.iterators), func(n int) bool {
  162. if n < pos {
  163. // No need to search 'behind' us
  164. return false
  165. }
  166. if n == len(fi.iterators)-1 {
  167. // Can always place an elem last
  168. return true
  169. }
  170. neighbour := fi.iterators[n+1].it.Key()
  171. if diff := bytes.Compare(val[:], neighbour[:]); diff < 0 {
  172. return true
  173. } else if diff > 0 {
  174. return false
  175. }
  176. // The elem we're placing it next to has the same value,
  177. // so whichever winds up on n+1 will need further iteraton
  178. iteratee = n + 1
  179. if current.priority < fi.iterators[n+1].priority {
  180. // We can drop the iterator here
  181. return true
  182. }
  183. // We need to move it one step further
  184. return false
  185. // TODO benchmark which is best, this works too:
  186. //iteratee = n
  187. //return true
  188. // Doing so should finish the current search earlier
  189. })
  190. fi.move(pos, index)
  191. if iteratee != -1 {
  192. fi.innerNext(iteratee)
  193. }
  194. return true
  195. }
  196. // move moves an iterator to another position in the list
  197. func (fi *fastAccountIterator) move(index, newpos int) {
  198. if newpos > len(fi.iterators)-1 {
  199. newpos = len(fi.iterators) - 1
  200. }
  201. var (
  202. elem = fi.iterators[index]
  203. middle = fi.iterators[index+1 : newpos+1]
  204. suffix []*weightedIterator
  205. )
  206. if newpos < len(fi.iterators)-1 {
  207. suffix = fi.iterators[newpos+1:]
  208. }
  209. fi.iterators = append(fi.iterators[:index], middle...)
  210. fi.iterators = append(fi.iterators, elem)
  211. fi.iterators = append(fi.iterators, suffix...)
  212. }
  213. // remove drops an iterator from the list
  214. func (fi *fastAccountIterator) remove(index int) {
  215. fi.iterators = append(fi.iterators[:index], fi.iterators[index+1:]...)
  216. }
  217. // Error returns any failure that occurred during iteration, which might have
  218. // caused a premature iteration exit (e.g. snapshot stack becoming stale).
  219. func (fi *fastAccountIterator) Error() error {
  220. return fi.fail
  221. }
  222. // Key returns the current key
  223. func (fi *fastAccountIterator) Key() common.Hash {
  224. return fi.iterators[0].it.Key()
  225. }
  226. // Value returns the current key
  227. func (fi *fastAccountIterator) Value() []byte {
  228. return fi.iterators[0].it.Value()
  229. }
  230. // Debug is a convencience helper during testing
  231. func (fi *fastAccountIterator) Debug() {
  232. for _, it := range fi.iterators {
  233. fmt.Printf("[p=%v v=%v] ", it.priority, it.it.Key()[0])
  234. }
  235. fmt.Println()
  236. }