file.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package hercules
  2. import "fmt"
  3. // A file encapsulates a balanced binary tree to store line intervals and
  4. // a cumulative mapping of values to the corresponding length counters. Users
  5. // are not supposed to create File-s directly; instead, they should call NewFile().
  6. // NewFileFromTree() is the special constructor which is useful in the tests.
  7. //
  8. // Len() returns the number of lines in File.
  9. //
  10. // Update() mutates File by introducing tree structural changes and updaing the
  11. // length mapping.
  12. //
  13. // Dump() writes the tree to a string and Validate() checks the tree integrity.
  14. type File struct {
  15. tree *RBTree
  16. status map[int]int64
  17. }
  18. // TreeEnd denotes the value of the last leaf in the tree.
  19. const TreeEnd int = -1
  20. // The ugly side of Go.
  21. // template <typename T> please!
  22. // min calculates the minimum of two 32-bit integers.
  23. func min(a int, b int) int {
  24. if a < b {
  25. return a
  26. }
  27. return b
  28. }
  29. // min64 calculates the minimum of two 64-bit integers.
  30. func min64(a int64, b int64) int64 {
  31. if a < b {
  32. return a
  33. }
  34. return b
  35. }
  36. // max calculates the maximum of two 32-bit integers.
  37. func max(a int, b int) int {
  38. if a < b {
  39. return b
  40. }
  41. return a
  42. }
  43. // max64 calculates the maximum of two 64-bit integers.
  44. func max64(a int64, b int64) int64 {
  45. if a < b {
  46. return b
  47. }
  48. return a
  49. }
  50. // abs64 calculates the absolute value of a 64-bit integer.
  51. func abs64(v int64) int64 {
  52. if v <= 0 {
  53. return -v
  54. }
  55. return v
  56. }
  57. // NewFile initializes a new instance of File struct.
  58. //
  59. // time is the starting value of the first node;
  60. //
  61. // length is the starting length of the tree (the key of the second and the
  62. // last node);
  63. //
  64. // status is the attached interval length mapping.
  65. func NewFile(time int, length int, status map[int]int64) *File {
  66. file := new(File)
  67. file.status = status
  68. file.tree = new(RBTree)
  69. if length > 0 {
  70. status[time] += int64(length)
  71. file.tree.Insert(Item{key: 0, value: time})
  72. }
  73. file.tree.Insert(Item{key: length, value: TreeEnd})
  74. return file
  75. }
  76. // NewFileFromTree is an alternative contructor for File which is used in tests.
  77. // The resulting tree is validated with Validate() to ensure the initial integrity.
  78. //
  79. // keys is a slice with the starting tree keys.
  80. //
  81. // vals is a slice with the starting tree values. Must match the size of keys.
  82. //
  83. // status is the attached interval length mapping.
  84. func NewFileFromTree(keys []int, vals []int, status map[int]int64) *File {
  85. file := new(File)
  86. file.status = status
  87. file.tree = new(RBTree)
  88. if len(keys) != len(vals) {
  89. panic("keys and vals must be of equal length")
  90. }
  91. for i := 0; i < len(keys); i++ {
  92. file.tree.Insert(Item{key: keys[i], value: vals[i]})
  93. }
  94. file.Validate()
  95. return file
  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, ins_length int, del_length 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 ins_length < 0 || del_length < 0 {
  125. panic("ins_length and del_length must be nonnegative")
  126. }
  127. if ins_length|del_length == 0 {
  128. return
  129. }
  130. tree := file.tree
  131. if pos > tree.Max().Item().key {
  132. panic(fmt.Sprintf("attempt to insert after the end of the file: %d < %d",
  133. tree.Max().Item().key, pos))
  134. }
  135. if tree.Len() < 2 && tree.Min().Item().key != 0 {
  136. panic("invalid tree state")
  137. }
  138. status := file.status
  139. iter := tree.FindLE(pos)
  140. origin := *iter.Item()
  141. status[time] += int64(ins_length)
  142. if del_length == 0 {
  143. // simple case with insertions only
  144. if origin.key < pos || (origin.value == time && pos == 0) {
  145. iter = iter.Next()
  146. }
  147. for ; !iter.Limit(); iter = iter.Next() {
  148. iter.Item().key += ins_length
  149. }
  150. if origin.value != time {
  151. tree.Insert(Item{key: pos, value: time})
  152. if origin.key < pos {
  153. tree.Insert(Item{key: pos + ins_length, value: origin.value})
  154. }
  155. }
  156. return
  157. }
  158. // delete nodes
  159. for true {
  160. node := iter.Item()
  161. next_iter := iter.Next()
  162. if next_iter.Limit() {
  163. if pos+del_length > node.key {
  164. panic("attempt to delete after the end of the file")
  165. }
  166. break
  167. }
  168. delta := min(next_iter.Item().key, pos+del_length) - max(node.key, pos)
  169. if delta <= 0 {
  170. break
  171. }
  172. status[node.value] -= int64(delta)
  173. if node.key >= pos {
  174. origin = *node
  175. tree.DeleteWithIterator(iter)
  176. }
  177. iter = next_iter
  178. }
  179. // prepare for the keys update
  180. var previous *Item
  181. if ins_length > 0 && (origin.value != time || origin.key == pos) {
  182. // insert our new interval
  183. if iter.Item().value == time {
  184. prev := iter.Prev()
  185. if prev.Item().value != time {
  186. iter.Item().key = pos
  187. } else {
  188. tree.DeleteWithIterator(iter)
  189. iter = prev
  190. }
  191. origin.value = time // cancels the insertion after applying the delta
  192. } else {
  193. _, iter = tree.Insert(Item{key: pos, value: time})
  194. }
  195. } else {
  196. // rollback 1 position back, see "for true" deletion cycle ^
  197. iter = iter.Prev()
  198. previous = iter.Item()
  199. }
  200. // update the keys of all subsequent nodes
  201. delta := ins_length - del_length
  202. if delta != 0 {
  203. for iter = iter.Next(); !iter.Limit(); iter = iter.Next() {
  204. // we do not need to re-balance the tree
  205. iter.Item().key += delta
  206. }
  207. // have to adjust origin in case ins_length == 0
  208. if origin.key > pos {
  209. origin.key += delta
  210. }
  211. }
  212. if ins_length > 0 {
  213. if origin.value != time {
  214. tree.Insert(Item{pos + ins_length, origin.value})
  215. } else if pos == 0 {
  216. // recover the beginning
  217. tree.Insert(Item{pos, time})
  218. }
  219. } else if (pos > origin.key && previous.value != origin.value) || pos == origin.key || pos == 0 {
  220. // continue the original interval
  221. tree.Insert(Item{pos, origin.value})
  222. }
  223. }
  224. // Dump formats the underlying line interval tree into a string.
  225. // Useful for error messages, panic()-s and debugging.
  226. func (file *File) Dump() string {
  227. buffer := ""
  228. for iter := file.tree.Min(); !iter.Limit(); iter = iter.Next() {
  229. node := iter.Item()
  230. buffer += fmt.Sprintf("%d %d\n", node.key, node.value)
  231. }
  232. return buffer
  233. }
  234. // Validate checks the underlying line interval tree integrity.
  235. // The checks are as follows:
  236. //
  237. // 1. The minimum key must be 0 because the first line index is always 0.
  238. //
  239. // 2. The last node must carry TreeEnd value. This is the maintained invariant
  240. // which marks the ending of the last line interval.
  241. //
  242. // 3. Node keys must monotonically increase and never duplicate.
  243. func (file *File) Validate() {
  244. if file.tree.Min().Item().key != 0 {
  245. panic("the tree must start with key 0")
  246. }
  247. if file.tree.Max().Item().value != TreeEnd {
  248. panic(fmt.Sprintf("the last value in the tree must be %d", TreeEnd))
  249. }
  250. prev_key := -1
  251. for iter := file.tree.Min(); !iter.Limit(); iter = iter.Next() {
  252. node := iter.Item()
  253. if node.key == prev_key {
  254. panic(fmt.Sprintf("duplicate tree key: %d", node.key))
  255. }
  256. prev_key = node.key
  257. }
  258. }