file.go 10 KB

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