vector.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package protocol
  7. import (
  8. "encoding/binary"
  9. "encoding/hex"
  10. "fmt"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/syncthing/syncthing/internal/gen/bep"
  15. )
  16. // The Vector type represents a version vector. The zero value is a usable
  17. // version vector. The vector has slice semantics and some operations on it
  18. // are "append-like" in that they may return the same vector modified, or v
  19. // new allocated Vector with the modified contents.
  20. type Vector struct {
  21. Counters []Counter
  22. }
  23. func (v *Vector) String() string {
  24. var buf strings.Builder
  25. for i, c := range v.Counters {
  26. if i > 0 {
  27. buf.WriteRune(',')
  28. }
  29. fmt.Fprintf(&buf, "%x:%d", c.ID, c.Value)
  30. }
  31. return buf.String()
  32. }
  33. func (v *Vector) ToWire() *bep.Vector {
  34. counters := make([]*bep.Counter, len(v.Counters))
  35. for i, c := range v.Counters {
  36. counters[i] = c.toWire()
  37. }
  38. return &bep.Vector{
  39. Counters: counters,
  40. }
  41. }
  42. func VectorFromWire(w *bep.Vector) Vector {
  43. var v Vector
  44. if w == nil || len(w.Counters) == 0 {
  45. return v
  46. }
  47. v.Counters = make([]Counter, len(w.Counters))
  48. for i, c := range w.Counters {
  49. v.Counters[i] = counterFromWire(c)
  50. }
  51. return v
  52. }
  53. func VectorFromString(s string) (Vector, error) {
  54. pairs := strings.Split(s, ",")
  55. var v Vector
  56. v.Counters = make([]Counter, len(pairs))
  57. for i, pair := range pairs {
  58. idStr, valStr, ok := strings.Cut(pair, ":")
  59. if !ok {
  60. return Vector{}, fmt.Errorf("bad pair %q", pair)
  61. }
  62. idslice, err := hex.DecodeString(idStr)
  63. if err != nil {
  64. return Vector{}, fmt.Errorf("bad id in pair %q", pair)
  65. }
  66. var idbs [8]byte
  67. copy(idbs[8-len(idslice):], idslice)
  68. id := binary.BigEndian.Uint64(idbs[:])
  69. val, err := strconv.ParseUint(valStr, 10, 64)
  70. if err != nil {
  71. return Vector{}, fmt.Errorf("bad val in pair %q", pair)
  72. }
  73. v.Counters[i] = Counter{ID: ShortID(id), Value: val}
  74. }
  75. return v, nil
  76. }
  77. // Counter represents a single counter in the version vector.
  78. type Counter struct {
  79. ID ShortID
  80. Value uint64
  81. }
  82. func (c *Counter) toWire() *bep.Counter {
  83. return &bep.Counter{
  84. Id: uint64(c.ID),
  85. Value: c.Value,
  86. }
  87. }
  88. func counterFromWire(w *bep.Counter) Counter {
  89. return Counter{
  90. ID: ShortID(w.Id),
  91. Value: w.Value,
  92. }
  93. }
  94. // Update returns a Vector with the index for the specific ID incremented by
  95. // one. If it is possible, the vector v is updated and returned. If it is not,
  96. // a copy will be created, updated and returned.
  97. func (v Vector) Update(id ShortID) Vector {
  98. now := uint64(time.Now().Unix())
  99. return v.updateWithNow(id, now)
  100. }
  101. func (v Vector) updateWithNow(id ShortID, now uint64) Vector {
  102. for i := range v.Counters {
  103. if v.Counters[i].ID == id {
  104. // Update an existing index
  105. v.Counters[i].Value = max(v.Counters[i].Value+1, now)
  106. return v
  107. } else if v.Counters[i].ID > id {
  108. // Insert a new index
  109. nv := make([]Counter, len(v.Counters)+1)
  110. copy(nv, v.Counters[:i])
  111. nv[i].ID = id
  112. nv[i].Value = max(1, now)
  113. copy(nv[i+1:], v.Counters[i:])
  114. return Vector{Counters: nv}
  115. }
  116. }
  117. // Append a new index
  118. return Vector{Counters: append(v.Counters, Counter{
  119. ID: id,
  120. Value: max(1, now),
  121. })}
  122. }
  123. // Merge returns the vector containing the maximum indexes from v and b. If it
  124. // is possible, the vector v is updated and returned. If it is not, a copy
  125. // will be created, updated and returned.
  126. func (v Vector) Merge(b Vector) Vector {
  127. var vi, bi int
  128. for bi < len(b.Counters) {
  129. if vi == len(v.Counters) {
  130. // We've reach the end of v, all that remains are appends
  131. return Vector{Counters: append(v.Counters, b.Counters[bi:]...)}
  132. }
  133. if v.Counters[vi].ID > b.Counters[bi].ID {
  134. // The index from b should be inserted here
  135. n := make([]Counter, len(v.Counters)+1)
  136. copy(n, v.Counters[:vi])
  137. n[vi] = b.Counters[bi]
  138. copy(n[vi+1:], v.Counters[vi:])
  139. v.Counters = n
  140. }
  141. if v.Counters[vi].ID == b.Counters[bi].ID {
  142. if val := b.Counters[bi].Value; val > v.Counters[vi].Value {
  143. v.Counters[vi].Value = val
  144. }
  145. }
  146. if bi < len(b.Counters) && v.Counters[vi].ID == b.Counters[bi].ID {
  147. bi++
  148. }
  149. vi++
  150. }
  151. return v
  152. }
  153. // Copy returns an identical vector that is not shared with v.
  154. func (v Vector) Copy() Vector {
  155. nv := make([]Counter, len(v.Counters))
  156. copy(nv, v.Counters)
  157. return Vector{Counters: nv}
  158. }
  159. // Equal returns true when the two vectors are equivalent.
  160. func (v Vector) Equal(b Vector) bool {
  161. return v.Compare(b) == Equal
  162. }
  163. // LesserEqual returns true when the two vectors are equivalent or v is Lesser
  164. // than b.
  165. func (v Vector) LesserEqual(b Vector) bool {
  166. comp := v.Compare(b)
  167. return comp == Lesser || comp == Equal
  168. }
  169. // GreaterEqual returns true when the two vectors are equivalent or v is Greater
  170. // than b.
  171. func (v Vector) GreaterEqual(b Vector) bool {
  172. comp := v.Compare(b)
  173. return comp == Greater || comp == Equal
  174. }
  175. // Concurrent returns true when the two vectors are concurrent.
  176. func (v Vector) Concurrent(b Vector) bool {
  177. comp := v.Compare(b)
  178. return comp == ConcurrentGreater || comp == ConcurrentLesser
  179. }
  180. // Counter returns the current value of the given counter ID.
  181. func (v Vector) Counter(id ShortID) uint64 {
  182. for _, c := range v.Counters {
  183. if c.ID == id {
  184. return c.Value
  185. }
  186. }
  187. return 0
  188. }
  189. // IsEmpty returns true when there are no counters.
  190. func (v Vector) IsEmpty() bool {
  191. return len(v.Counters) == 0
  192. }
  193. // DropOthers removes all counters, keeping only the one with given id. If there
  194. // is no such counter, an empty Vector is returned.
  195. func (v Vector) DropOthers(id ShortID) Vector {
  196. for i, c := range v.Counters {
  197. if c.ID == id {
  198. v.Counters = v.Counters[i : i+1]
  199. return v
  200. }
  201. }
  202. return Vector{}
  203. }
  204. // Ordering represents the relationship between two Vectors.
  205. type Ordering int
  206. const (
  207. Equal Ordering = iota
  208. Greater
  209. Lesser
  210. ConcurrentLesser
  211. ConcurrentGreater
  212. )
  213. // There's really no such thing as "concurrent lesser" and "concurrent
  214. // greater" in version vectors, just "concurrent". But it's useful to be able
  215. // to get a strict ordering between versions for stable sorts and so on, so we
  216. // return both variants. The convenience method Concurrent() can be used to
  217. // check for either case.
  218. // Compare returns the Ordering that describes a's relation to b.
  219. func (v Vector) Compare(b Vector) Ordering {
  220. var ai, bi int // index into a and b
  221. var av, bv Counter // value at current index
  222. result := Equal
  223. for ai < len(v.Counters) || bi < len(b.Counters) {
  224. var aMissing, bMissing bool
  225. if ai < len(v.Counters) {
  226. av = v.Counters[ai]
  227. } else {
  228. av = Counter{}
  229. aMissing = true
  230. }
  231. if bi < len(b.Counters) {
  232. bv = b.Counters[bi]
  233. } else {
  234. bv = Counter{}
  235. bMissing = true
  236. }
  237. switch {
  238. case av.ID == bv.ID:
  239. // We have a counter value for each side
  240. if av.Value > bv.Value {
  241. if result == Lesser {
  242. return ConcurrentLesser
  243. }
  244. result = Greater
  245. } else if av.Value < bv.Value {
  246. if result == Greater {
  247. return ConcurrentGreater
  248. }
  249. result = Lesser
  250. }
  251. case !aMissing && av.ID < bv.ID || bMissing:
  252. // Value is missing on the b side
  253. if av.Value > 0 {
  254. if result == Lesser {
  255. return ConcurrentLesser
  256. }
  257. result = Greater
  258. }
  259. case !bMissing && bv.ID < av.ID || aMissing:
  260. // Value is missing on the a side
  261. if bv.Value > 0 {
  262. if result == Greater {
  263. return ConcurrentGreater
  264. }
  265. result = Lesser
  266. }
  267. }
  268. if ai < len(v.Counters) && (av.ID <= bv.ID || bMissing) {
  269. ai++
  270. }
  271. if bi < len(b.Counters) && (bv.ID <= av.ID || aMissing) {
  272. bi++
  273. }
  274. }
  275. return result
  276. }