file.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package burndown
  2. import (
  3. "fmt"
  4. "log"
  5. "math"
  6. "gopkg.in/src-d/hercules.v6/internal"
  7. "gopkg.in/src-d/hercules.v6/internal/rbtree"
  8. )
  9. // Updater is the function which is called back on File.Update().
  10. type Updater = func(currentTime, previousTime, delta int)
  11. // File encapsulates a balanced binary tree to store line intervals and
  12. // a cumulative mapping of values to the corresponding length counters. Users
  13. // are not supposed to create File-s directly; instead, they should call NewFile().
  14. // NewFileFromTree() is the special constructor which is useful in the tests.
  15. //
  16. // Len() returns the number of lines in File.
  17. //
  18. // Update() mutates File by introducing tree structural changes and updating the
  19. // length mapping.
  20. //
  21. // Dump() writes the tree to a string and Validate() checks the tree integrity.
  22. type File struct {
  23. tree *rbtree.RBTree
  24. updaters []Updater
  25. }
  26. // TreeEnd denotes the value of the last leaf in the tree.
  27. const TreeEnd = math.MaxUint32
  28. // TreeMaxBinPower is the binary power value which corresponds to the maximum day which
  29. // can be stored in the tree.
  30. const TreeMaxBinPower = 14
  31. // TreeMergeMark is the special day which disables the status updates and is used in File.Merge().
  32. const TreeMergeMark = (1 << TreeMaxBinPower) - 1
  33. func (file *File) updateTime(currentTime, previousTime, delta int) {
  34. if previousTime&TreeMergeMark == TreeMergeMark {
  35. if currentTime == previousTime {
  36. return
  37. }
  38. panic("previousTime cannot be TreeMergeMark")
  39. }
  40. if currentTime&TreeMergeMark == TreeMergeMark {
  41. // merge mode - `delta` is negative and we have already applied it in a branch
  42. return
  43. }
  44. for _, update := range file.updaters {
  45. update(currentTime, previousTime, delta)
  46. }
  47. }
  48. // NewFile initializes a new instance of File struct.
  49. //
  50. // time is the starting value of the first node;
  51. //
  52. // length is the starting length of the tree (the key of the second and the
  53. // last node);
  54. //
  55. // updaters are the attached interval length mappings.
  56. func NewFile(time int, length int, allocator *rbtree.Allocator, updaters ...Updater) *File {
  57. file := &File{tree: rbtree.NewRBTree(allocator), updaters: updaters}
  58. file.updateTime(time, time, length)
  59. if time < 0 || time > math.MaxUint32 {
  60. log.Panicf("time is out of allowed range: %d", time)
  61. }
  62. if length > math.MaxUint32 {
  63. log.Panicf("length is out of allowed range: %d", length)
  64. }
  65. if length > 0 {
  66. file.tree.Insert(rbtree.Item{Key: 0, Value: uint32(time)})
  67. }
  68. file.tree.Insert(rbtree.Item{Key: uint32(length), Value: TreeEnd})
  69. return file
  70. }
  71. // NewFileFromTree is an alternative constructor for File which is used in tests.
  72. // The resulting tree is validated with Validate() to ensure the initial integrity.
  73. //
  74. // keys is a slice with the starting tree keys.
  75. //
  76. // vals is a slice with the starting tree values. Must match the size of keys.
  77. //
  78. // updaters are the attached interval length mappings.
  79. func NewFileFromTree(keys []int, vals []int, allocator *rbtree.Allocator, updaters ...Updater) *File {
  80. file := &File{tree: rbtree.NewRBTree(allocator), updaters: updaters}
  81. if len(keys) != len(vals) {
  82. panic("keys and vals must be of equal length")
  83. }
  84. for i, key := range keys {
  85. val := vals[i]
  86. if key < 0 || key >= math.MaxUint32 {
  87. log.Panicf("key is out of allowed range: [%d]=%d", i, key)
  88. }
  89. if val < 0 || val > math.MaxUint32 {
  90. log.Panicf("val is out of allowed range: [%d]=%d", i, val)
  91. }
  92. file.tree.Insert(rbtree.Item{Key: uint32(key), Value: uint32(val)})
  93. }
  94. file.Validate()
  95. return file
  96. }
  97. // Clone copies the file. It performs a deep copy of the tree;
  98. // depending on `clearStatuses` the original updaters are removed or not.
  99. // Any new `updaters` are appended.
  100. func (file *File) Clone(allocator *rbtree.Allocator) *File {
  101. return &File{tree: file.tree.Clone(allocator), updaters: file.updaters}
  102. }
  103. // Delete deallocates the file.
  104. func (file *File) Delete() {
  105. file.tree.Erase()
  106. }
  107. // Len returns the File's size - that is, the maximum key in the tree of line
  108. // intervals.
  109. func (file *File) Len() int {
  110. return int(file.tree.Max().Item().Key)
  111. }
  112. // Update modifies the underlying tree to adapt to the specified line changes.
  113. //
  114. // time is the time when the requested changes are made. Sets the values of the
  115. // inserted nodes.
  116. //
  117. // pos is the index of the line at which the changes are introduced.
  118. //
  119. // ins_length is the number of inserted lines after pos.
  120. //
  121. // del_length is the number of removed lines after pos. Deletions come before
  122. // the insertions.
  123. //
  124. // The code inside this function is probably the most important one throughout
  125. // the project. It is extensively covered with tests. If you find a bug, please
  126. // add the corresponding case in file_test.go.
  127. func (file *File) Update(time int, pos int, insLength int, delLength int) {
  128. if time < 0 {
  129. panic("time may not be negative")
  130. }
  131. if time >= math.MaxUint32 {
  132. panic("time may not be >= MaxUint32")
  133. }
  134. if pos < 0 {
  135. panic("attempt to insert/delete at a negative position")
  136. }
  137. if pos > math.MaxUint32 {
  138. panic("pos may not be > MaxUint32")
  139. }
  140. if insLength < 0 || delLength < 0 {
  141. panic("insLength and delLength must be non-negative")
  142. }
  143. if insLength|delLength == 0 {
  144. return
  145. }
  146. tree := file.tree
  147. if tree.Len() < 2 && tree.Min().Item().Key != 0 {
  148. panic("invalid tree state")
  149. }
  150. if uint32(pos) > tree.Max().Item().Key {
  151. panic(fmt.Sprintf("attempt to insert after the end of the file: %d < %d",
  152. tree.Max().Item().Key, pos))
  153. }
  154. iter := tree.FindLE(uint32(pos))
  155. origin := *iter.Item()
  156. prevOrigin := origin
  157. {
  158. prevIter := iter.Prev()
  159. if prevIter.Item() != nil {
  160. prevOrigin = *prevIter.Item()
  161. }
  162. }
  163. if insLength > 0 {
  164. file.updateTime(time, time, insLength)
  165. }
  166. if delLength == 0 {
  167. // simple case with insertions only
  168. if origin.Key < uint32(pos) || (origin.Value == uint32(time) && (pos == 0 || uint32(pos) == origin.Key)) {
  169. iter = iter.Next()
  170. }
  171. for ; !iter.Limit(); iter = iter.Next() {
  172. iter.Item().Key += uint32(insLength)
  173. }
  174. if origin.Value != uint32(time) {
  175. tree.Insert(rbtree.Item{Key: uint32(pos), Value: uint32(time)})
  176. if origin.Key < uint32(pos) {
  177. tree.Insert(rbtree.Item{Key: uint32(pos + insLength), Value: origin.Value})
  178. }
  179. }
  180. return
  181. }
  182. // delete nodes
  183. for true {
  184. node := iter.Item()
  185. nextIter := iter.Next()
  186. if nextIter.Limit() {
  187. if uint32(pos+delLength) > node.Key {
  188. panic("attempt to delete after the end of the file")
  189. }
  190. break
  191. }
  192. delta := internal.Min(int(nextIter.Item().Key), pos+delLength) - internal.Max(int(node.Key), pos)
  193. if delta == 0 && insLength == 0 && origin.Key == uint32(pos) && prevOrigin.Value == node.Value {
  194. origin = *node
  195. tree.DeleteWithIterator(iter)
  196. iter = nextIter
  197. }
  198. if delta <= 0 {
  199. break
  200. }
  201. file.updateTime(time, int(node.Value), -delta)
  202. if node.Key >= uint32(pos) {
  203. origin = *node
  204. tree.DeleteWithIterator(iter)
  205. }
  206. iter = nextIter
  207. }
  208. // prepare for the keys update
  209. var previous *rbtree.Item
  210. if insLength > 0 && (origin.Value != uint32(time) || origin.Key == uint32(pos)) {
  211. // insert our new interval
  212. if iter.Item().Value == uint32(time) && int(iter.Item().Key)-delLength == pos {
  213. prev := iter.Prev()
  214. if prev.NegativeLimit() || prev.Item().Value != uint32(time) {
  215. iter.Item().Key = uint32(pos)
  216. } else {
  217. tree.DeleteWithIterator(iter)
  218. iter = prev
  219. }
  220. origin.Value = uint32(time) // cancels the insertion after applying the delta
  221. } else {
  222. _, iter = tree.Insert(rbtree.Item{Key: uint32(pos), Value: uint32(time)})
  223. }
  224. } else {
  225. // rollback 1 position back, see "for true" deletion cycle ^
  226. iter = iter.Prev()
  227. previous = iter.Item()
  228. }
  229. // update the keys of all subsequent nodes
  230. delta := insLength - delLength
  231. if delta != 0 {
  232. for iter = iter.Next(); !iter.Limit(); iter = iter.Next() {
  233. // we do not need to re-balance the tree
  234. iter.Item().Key = uint32(int(iter.Item().Key)+delta)
  235. }
  236. // have to adjust origin in case insLength == 0
  237. if origin.Key > uint32(pos) {
  238. origin.Key = uint32(int(origin.Key)+delta)
  239. }
  240. }
  241. if insLength > 0 {
  242. if origin.Value != uint32(time) {
  243. tree.Insert(rbtree.Item{Key: uint32(pos + insLength), Value: origin.Value})
  244. } else if pos == 0 {
  245. // recover the beginning
  246. tree.Insert(rbtree.Item{Key: uint32(pos), Value: uint32(time)})
  247. }
  248. } else if (uint32(pos) > origin.Key && previous != nil && previous.Value != origin.Value) ||
  249. (uint32(pos) == origin.Key && origin.Value != prevOrigin.Value) ||
  250. pos == 0 {
  251. // continue the original interval
  252. tree.Insert(rbtree.Item{Key: uint32(pos), Value: origin.Value})
  253. }
  254. }
  255. // Merge combines several prepared File-s together.
  256. func (file *File) Merge(day int, others ...*File) {
  257. myself := file.flatten()
  258. for _, other := range others {
  259. if other == nil {
  260. log.Panic("merging with a nil file")
  261. }
  262. lines := other.flatten()
  263. if len(myself) != len(lines) {
  264. log.Panicf("file corruption, lines number mismatch during merge %d != %d",
  265. len(myself), len(lines))
  266. }
  267. for i, l := range myself {
  268. ol := lines[i]
  269. if ol&TreeMergeMark == TreeMergeMark {
  270. continue
  271. }
  272. if l&TreeMergeMark == TreeMergeMark || l&TreeMergeMark > ol&TreeMergeMark {
  273. // the line is merged in myself and exists in other
  274. // OR the same line introduced in different branches
  275. // consider the oldest version as the ground truth in that case
  276. myself[i] = ol
  277. continue
  278. }
  279. }
  280. }
  281. for i, l := range myself {
  282. if l&TreeMergeMark == TreeMergeMark {
  283. // original merge conflict resolution
  284. myself[i] = day
  285. file.updateTime(day, day, 1)
  286. }
  287. }
  288. // now we need to reconstruct the tree from the discrete values
  289. file.tree.Erase()
  290. tree := rbtree.NewRBTree(file.tree.Allocator())
  291. for i, v := range myself {
  292. if i == 0 || v != myself[i-1] {
  293. tree.Insert(rbtree.Item{Key: uint32(i), Value: uint32(v)})
  294. }
  295. }
  296. tree.Insert(rbtree.Item{Key: uint32(len(myself)), Value: TreeEnd})
  297. file.tree = tree
  298. }
  299. // Dump formats the underlying line interval tree into a string.
  300. // Useful for error messages, panic()-s and debugging.
  301. func (file *File) Dump() string {
  302. buffer := ""
  303. for iter := file.tree.Min(); !iter.Limit(); iter = iter.Next() {
  304. node := iter.Item()
  305. var val int
  306. if node.Value == math.MaxUint32 {
  307. val = -1
  308. } else {
  309. val = int(node.Value)
  310. }
  311. buffer += fmt.Sprintf("%d %d\n", node.Key, val)
  312. }
  313. return buffer
  314. }
  315. // Validate checks the underlying line interval tree integrity.
  316. // The checks are as follows:
  317. //
  318. // 1. The minimum key must be 0 because the first line index is always 0.
  319. //
  320. // 2. The last node must carry TreeEnd value. This is the maintained invariant
  321. // which marks the ending of the last line interval.
  322. //
  323. // 3. Node keys must monotonically increase and never duplicate.
  324. func (file *File) Validate() {
  325. if file.tree.Min().Item().Key != 0 {
  326. log.Panic("the tree must start with key 0")
  327. }
  328. if file.tree.Max().Item().Value != TreeEnd {
  329. log.Panicf("the last value in the tree must be %d", TreeEnd)
  330. }
  331. prevKey := uint32(math.MaxUint32)
  332. for iter := file.tree.Min(); !iter.Limit(); iter = iter.Next() {
  333. node := iter.Item()
  334. if node.Key == prevKey {
  335. log.Panicf("duplicate tree key: %d", node.Key)
  336. }
  337. if node.Value == TreeMergeMark {
  338. log.Panicf("unmerged lines left: %d", node.Key)
  339. }
  340. prevKey = node.Key
  341. }
  342. }
  343. // flatten represents the file as a slice of lines, each line's value being the corresponding day.
  344. func (file *File) flatten() []int {
  345. lines := make([]int, 0, file.Len())
  346. val := uint32(math.MaxUint32)
  347. for iter := file.tree.Min(); !iter.Limit(); iter = iter.Next() {
  348. for i := uint32(len(lines)); i < iter.Item().Key; i++ {
  349. lines = append(lines, int(val))
  350. }
  351. val = iter.Item().Value
  352. }
  353. return lines
  354. }