1
0

vector.go 7.6 KB

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