intervals.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // Copyright 2018 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 intervals
  17. import (
  18. "bytes"
  19. "fmt"
  20. "strconv"
  21. "sync"
  22. )
  23. // Intervals store a list of intervals. Its purpose is to provide
  24. // methods to add new intervals and retrieve missing intervals that
  25. // need to be added.
  26. // It may be used in synchronization of streaming data to persist
  27. // retrieved data ranges between sessions.
  28. type Intervals struct {
  29. start uint64
  30. ranges [][2]uint64
  31. mu sync.RWMutex
  32. }
  33. // New creates a new instance of Intervals.
  34. // Start argument limits the lower bound of intervals.
  35. // No range bellow start bound will be added by Add method or
  36. // returned by Next method. This limit may be used for
  37. // tracking "live" synchronization, where the sync session
  38. // starts from a specific value, and if "live" sync intervals
  39. // need to be merged with historical ones, it can be safely done.
  40. func NewIntervals(start uint64) *Intervals {
  41. return &Intervals{
  42. start: start,
  43. }
  44. }
  45. // Add adds a new range to intervals. Range start and end are values
  46. // are both inclusive.
  47. func (i *Intervals) Add(start, end uint64) {
  48. i.mu.Lock()
  49. defer i.mu.Unlock()
  50. i.add(start, end)
  51. }
  52. func (i *Intervals) add(start, end uint64) {
  53. if start < i.start {
  54. start = i.start
  55. }
  56. if end < i.start {
  57. return
  58. }
  59. minStartJ := -1
  60. maxEndJ := -1
  61. j := 0
  62. for ; j < len(i.ranges); j++ {
  63. if minStartJ < 0 {
  64. if (start <= i.ranges[j][0] && end+1 >= i.ranges[j][0]) || (start <= i.ranges[j][1]+1 && end+1 >= i.ranges[j][1]) {
  65. if i.ranges[j][0] < start {
  66. start = i.ranges[j][0]
  67. }
  68. minStartJ = j
  69. }
  70. }
  71. if (start <= i.ranges[j][1] && end+1 >= i.ranges[j][1]) || (start <= i.ranges[j][0] && end+1 >= i.ranges[j][0]) {
  72. if i.ranges[j][1] > end {
  73. end = i.ranges[j][1]
  74. }
  75. maxEndJ = j
  76. }
  77. if end+1 <= i.ranges[j][0] {
  78. break
  79. }
  80. }
  81. if minStartJ < 0 && maxEndJ < 0 {
  82. i.ranges = append(i.ranges[:j], append([][2]uint64{{start, end}}, i.ranges[j:]...)...)
  83. return
  84. }
  85. if minStartJ >= 0 {
  86. i.ranges[minStartJ][0] = start
  87. }
  88. if maxEndJ >= 0 {
  89. i.ranges[maxEndJ][1] = end
  90. }
  91. if minStartJ >= 0 && maxEndJ >= 0 && minStartJ != maxEndJ {
  92. i.ranges[maxEndJ][0] = start
  93. i.ranges = append(i.ranges[:minStartJ], i.ranges[maxEndJ:]...)
  94. }
  95. }
  96. // Merge adds all the intervals from the m Interval to current one.
  97. func (i *Intervals) Merge(m *Intervals) {
  98. m.mu.RLock()
  99. defer m.mu.RUnlock()
  100. i.mu.Lock()
  101. defer i.mu.Unlock()
  102. for _, r := range m.ranges {
  103. i.add(r[0], r[1])
  104. }
  105. }
  106. // Next returns the first range interval that is not fulfilled. Returned
  107. // start and end values are both inclusive, meaning that the whole range
  108. // including start and end need to be added in order to full the gap
  109. // in intervals.
  110. // Returned value for end is 0 if the next interval is after the whole
  111. // range that is stored in Intervals. Zero end value represents no limit
  112. // on the next interval length.
  113. func (i *Intervals) Next() (start, end uint64) {
  114. i.mu.RLock()
  115. defer i.mu.RUnlock()
  116. l := len(i.ranges)
  117. if l == 0 {
  118. return i.start, 0
  119. }
  120. if i.ranges[0][0] != i.start {
  121. return i.start, i.ranges[0][0] - 1
  122. }
  123. if l == 1 {
  124. return i.ranges[0][1] + 1, 0
  125. }
  126. return i.ranges[0][1] + 1, i.ranges[1][0] - 1
  127. }
  128. // Last returns the value that is at the end of the last interval.
  129. func (i *Intervals) Last() (end uint64) {
  130. i.mu.RLock()
  131. defer i.mu.RUnlock()
  132. l := len(i.ranges)
  133. if l == 0 {
  134. return 0
  135. }
  136. return i.ranges[l-1][1]
  137. }
  138. // String returns a descriptive representation of range intervals
  139. // in [] notation, as a list of two element vectors.
  140. func (i *Intervals) String() string {
  141. return fmt.Sprint(i.ranges)
  142. }
  143. // MarshalBinary encodes Intervals parameters into a semicolon separated list.
  144. // The first element in the list is base36-encoded start value. The following
  145. // elements are two base36-encoded value ranges separated by comma.
  146. func (i *Intervals) MarshalBinary() (data []byte, err error) {
  147. d := make([][]byte, len(i.ranges)+1)
  148. d[0] = []byte(strconv.FormatUint(i.start, 36))
  149. for j := range i.ranges {
  150. r := i.ranges[j]
  151. d[j+1] = []byte(strconv.FormatUint(r[0], 36) + "," + strconv.FormatUint(r[1], 36))
  152. }
  153. return bytes.Join(d, []byte(";")), nil
  154. }
  155. // UnmarshalBinary decodes data according to the Intervals.MarshalBinary format.
  156. func (i *Intervals) UnmarshalBinary(data []byte) (err error) {
  157. d := bytes.Split(data, []byte(";"))
  158. l := len(d)
  159. if l == 0 {
  160. return nil
  161. }
  162. if l >= 1 {
  163. i.start, err = strconv.ParseUint(string(d[0]), 36, 64)
  164. if err != nil {
  165. return err
  166. }
  167. }
  168. if l == 1 {
  169. return nil
  170. }
  171. i.ranges = make([][2]uint64, 0, l-1)
  172. for j := 1; j < l; j++ {
  173. r := bytes.SplitN(d[j], []byte(","), 2)
  174. if len(r) < 2 {
  175. return fmt.Errorf("range %d has less then 2 elements", j)
  176. }
  177. start, err := strconv.ParseUint(string(r[0]), 36, 64)
  178. if err != nil {
  179. return fmt.Errorf("parsing the first element in range %d: %v", j, err)
  180. }
  181. end, err := strconv.ParseUint(string(r[1]), 36, 64)
  182. if err != nil {
  183. return fmt.Errorf("parsing the second element in range %d: %v", j, err)
  184. }
  185. i.ranges = append(i.ranges, [2]uint64{start, end})
  186. }
  187. return nil
  188. }