sequence.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. // Package bitseq provides a structure and utilities for representing long bitmask
  2. // as sequence of run-length encoded blocks. It operates directly on the encoded
  3. // representation, it does not decode/encode.
  4. package bitseq
  5. import (
  6. "encoding/binary"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "sync"
  11. "github.com/docker/libnetwork/datastore"
  12. "github.com/docker/libnetwork/types"
  13. "github.com/sirupsen/logrus"
  14. )
  15. // block sequence constants
  16. // If needed we can think of making these configurable
  17. const (
  18. blockLen = uint32(32)
  19. blockBytes = uint64(blockLen / 8)
  20. blockMAX = uint32(1<<blockLen - 1)
  21. blockFirstBit = uint32(1) << (blockLen - 1)
  22. invalidPos = uint64(0xFFFFFFFFFFFFFFFF)
  23. )
  24. var (
  25. // ErrNoBitAvailable is returned when no more bits are available to set
  26. ErrNoBitAvailable = errors.New("no bit available")
  27. // ErrBitAllocated is returned when the specific bit requested is already set
  28. ErrBitAllocated = errors.New("requested bit is already allocated")
  29. )
  30. // Handle contains the sequence representing the bitmask and its identifier
  31. type Handle struct {
  32. bits uint64
  33. unselected uint64
  34. head *sequence
  35. app string
  36. id string
  37. dbIndex uint64
  38. dbExists bool
  39. curr uint64
  40. store datastore.DataStore
  41. sync.Mutex
  42. }
  43. // NewHandle returns a thread-safe instance of the bitmask handler
  44. func NewHandle(app string, ds datastore.DataStore, id string, numElements uint64) (*Handle, error) {
  45. h := &Handle{
  46. app: app,
  47. id: id,
  48. store: ds,
  49. bits: numElements,
  50. unselected: numElements,
  51. head: &sequence{
  52. block: 0x0,
  53. count: getNumBlocks(numElements),
  54. },
  55. }
  56. if h.store == nil {
  57. return h, nil
  58. }
  59. // Get the initial status from the ds if present.
  60. if err := h.store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
  61. return nil, err
  62. }
  63. // If the handle is not in store, write it.
  64. if !h.Exists() {
  65. if err := h.writeToStore(); err != nil {
  66. return nil, fmt.Errorf("failed to write bitsequence to store: %v", err)
  67. }
  68. }
  69. return h, nil
  70. }
  71. // sequence represents a recurring sequence of 32 bits long bitmasks
  72. type sequence struct {
  73. block uint32 // block is a symbol representing 4 byte long allocation bitmask
  74. count uint64 // number of consecutive blocks (symbols)
  75. next *sequence // next sequence
  76. }
  77. // String returns a string representation of the block sequence starting from this block
  78. func (s *sequence) toString() string {
  79. var nextBlock string
  80. if s.next == nil {
  81. nextBlock = "end"
  82. } else {
  83. nextBlock = s.next.toString()
  84. }
  85. return fmt.Sprintf("(0x%x, %d)->%s", s.block, s.count, nextBlock)
  86. }
  87. // GetAvailableBit returns the position of the first unset bit in the bitmask represented by this sequence
  88. func (s *sequence) getAvailableBit(from uint64) (uint64, uint64, error) {
  89. if s.block == blockMAX || s.count == 0 {
  90. return invalidPos, invalidPos, ErrNoBitAvailable
  91. }
  92. bits := from
  93. bitSel := blockFirstBit >> from
  94. for bitSel > 0 && s.block&bitSel != 0 {
  95. bitSel >>= 1
  96. bits++
  97. }
  98. // Check if the loop exited because it could not
  99. // find any available bit int block starting from
  100. // "from". Return invalid pos in that case.
  101. if bitSel == 0 {
  102. return invalidPos, invalidPos, ErrNoBitAvailable
  103. }
  104. return bits / 8, bits % 8, nil
  105. }
  106. // GetCopy returns a copy of the linked list rooted at this node
  107. func (s *sequence) getCopy() *sequence {
  108. n := &sequence{block: s.block, count: s.count}
  109. pn := n
  110. ps := s.next
  111. for ps != nil {
  112. pn.next = &sequence{block: ps.block, count: ps.count}
  113. pn = pn.next
  114. ps = ps.next
  115. }
  116. return n
  117. }
  118. // Equal checks if this sequence is equal to the passed one
  119. func (s *sequence) equal(o *sequence) bool {
  120. this := s
  121. other := o
  122. for this != nil {
  123. if other == nil {
  124. return false
  125. }
  126. if this.block != other.block || this.count != other.count {
  127. return false
  128. }
  129. this = this.next
  130. other = other.next
  131. }
  132. // Check if other is longer than this
  133. if other != nil {
  134. return false
  135. }
  136. return true
  137. }
  138. // ToByteArray converts the sequence into a byte array
  139. func (s *sequence) toByteArray() ([]byte, error) {
  140. var bb []byte
  141. p := s
  142. for p != nil {
  143. b := make([]byte, 12)
  144. binary.BigEndian.PutUint32(b[0:], p.block)
  145. binary.BigEndian.PutUint64(b[4:], p.count)
  146. bb = append(bb, b...)
  147. p = p.next
  148. }
  149. return bb, nil
  150. }
  151. // fromByteArray construct the sequence from the byte array
  152. func (s *sequence) fromByteArray(data []byte) error {
  153. l := len(data)
  154. if l%12 != 0 {
  155. return fmt.Errorf("cannot deserialize byte sequence of length %d (%v)", l, data)
  156. }
  157. p := s
  158. i := 0
  159. for {
  160. p.block = binary.BigEndian.Uint32(data[i : i+4])
  161. p.count = binary.BigEndian.Uint64(data[i+4 : i+12])
  162. i += 12
  163. if i == l {
  164. break
  165. }
  166. p.next = &sequence{}
  167. p = p.next
  168. }
  169. return nil
  170. }
  171. func (h *Handle) getCopy() *Handle {
  172. return &Handle{
  173. bits: h.bits,
  174. unselected: h.unselected,
  175. head: h.head.getCopy(),
  176. app: h.app,
  177. id: h.id,
  178. dbIndex: h.dbIndex,
  179. dbExists: h.dbExists,
  180. store: h.store,
  181. curr: h.curr,
  182. }
  183. }
  184. // SetAnyInRange atomically sets the first unset bit in the specified range in the sequence and returns the corresponding ordinal
  185. func (h *Handle) SetAnyInRange(start, end uint64, serial bool) (uint64, error) {
  186. if end < start || end >= h.bits {
  187. return invalidPos, fmt.Errorf("invalid bit range [%d, %d]", start, end)
  188. }
  189. if h.Unselected() == 0 {
  190. return invalidPos, ErrNoBitAvailable
  191. }
  192. return h.set(0, start, end, true, false, serial)
  193. }
  194. // SetAny atomically sets the first unset bit in the sequence and returns the corresponding ordinal
  195. func (h *Handle) SetAny(serial bool) (uint64, error) {
  196. if h.Unselected() == 0 {
  197. return invalidPos, ErrNoBitAvailable
  198. }
  199. return h.set(0, 0, h.bits-1, true, false, serial)
  200. }
  201. // Set atomically sets the corresponding bit in the sequence
  202. func (h *Handle) Set(ordinal uint64) error {
  203. if err := h.validateOrdinal(ordinal); err != nil {
  204. return err
  205. }
  206. _, err := h.set(ordinal, 0, 0, false, false, false)
  207. return err
  208. }
  209. // Unset atomically unsets the corresponding bit in the sequence
  210. func (h *Handle) Unset(ordinal uint64) error {
  211. if err := h.validateOrdinal(ordinal); err != nil {
  212. return err
  213. }
  214. _, err := h.set(ordinal, 0, 0, false, true, false)
  215. return err
  216. }
  217. // IsSet atomically checks if the ordinal bit is set. In case ordinal
  218. // is outside of the bit sequence limits, false is returned.
  219. func (h *Handle) IsSet(ordinal uint64) bool {
  220. if err := h.validateOrdinal(ordinal); err != nil {
  221. return false
  222. }
  223. h.Lock()
  224. _, _, err := checkIfAvailable(h.head, ordinal)
  225. h.Unlock()
  226. return err != nil
  227. }
  228. func (h *Handle) runConsistencyCheck() bool {
  229. corrupted := false
  230. for p, c := h.head, h.head.next; c != nil; c = c.next {
  231. if c.count == 0 {
  232. corrupted = true
  233. p.next = c.next
  234. continue // keep same p
  235. }
  236. p = c
  237. }
  238. return corrupted
  239. }
  240. // CheckConsistency checks if the bit sequence is in an inconsistent state and attempts to fix it.
  241. // It looks for a corruption signature that may happen in docker 1.9.0 and 1.9.1.
  242. func (h *Handle) CheckConsistency() error {
  243. for {
  244. h.Lock()
  245. store := h.store
  246. h.Unlock()
  247. if store != nil {
  248. if err := store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
  249. return err
  250. }
  251. }
  252. h.Lock()
  253. nh := h.getCopy()
  254. h.Unlock()
  255. if !nh.runConsistencyCheck() {
  256. return nil
  257. }
  258. if err := nh.writeToStore(); err != nil {
  259. if _, ok := err.(types.RetryError); !ok {
  260. return fmt.Errorf("internal failure while fixing inconsistent bitsequence: %v", err)
  261. }
  262. continue
  263. }
  264. logrus.Infof("Fixed inconsistent bit sequence in datastore:\n%s\n%s", h, nh)
  265. h.Lock()
  266. h.head = nh.head
  267. h.Unlock()
  268. return nil
  269. }
  270. }
  271. // set/reset the bit
  272. func (h *Handle) set(ordinal, start, end uint64, any bool, release bool, serial bool) (uint64, error) {
  273. var (
  274. bitPos uint64
  275. bytePos uint64
  276. ret uint64
  277. err error
  278. )
  279. for {
  280. var store datastore.DataStore
  281. curr := uint64(0)
  282. h.Lock()
  283. store = h.store
  284. if store != nil {
  285. h.Unlock() // The lock is acquired in the GetObject
  286. if err := store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
  287. return ret, err
  288. }
  289. h.Lock() // Acquire the lock back
  290. }
  291. if serial {
  292. curr = h.curr
  293. }
  294. // Get position if available
  295. if release {
  296. bytePos, bitPos = ordinalToPos(ordinal)
  297. } else {
  298. if any {
  299. bytePos, bitPos, err = getAvailableFromCurrent(h.head, start, curr, end)
  300. ret = posToOrdinal(bytePos, bitPos)
  301. if err == nil {
  302. h.curr = ret + 1
  303. }
  304. } else {
  305. bytePos, bitPos, err = checkIfAvailable(h.head, ordinal)
  306. ret = ordinal
  307. }
  308. }
  309. if err != nil {
  310. h.Unlock()
  311. return ret, err
  312. }
  313. // Create a private copy of h and work on it
  314. nh := h.getCopy()
  315. nh.head = pushReservation(bytePos, bitPos, nh.head, release)
  316. if release {
  317. nh.unselected++
  318. } else {
  319. nh.unselected--
  320. }
  321. if h.store != nil {
  322. h.Unlock()
  323. // Attempt to write private copy to store
  324. if err := nh.writeToStore(); err != nil {
  325. if _, ok := err.(types.RetryError); !ok {
  326. return ret, fmt.Errorf("internal failure while setting the bit: %v", err)
  327. }
  328. // Retry
  329. continue
  330. }
  331. h.Lock()
  332. }
  333. // Previous atomic push was successful. Save private copy to local copy
  334. h.unselected = nh.unselected
  335. h.head = nh.head
  336. h.dbExists = nh.dbExists
  337. h.dbIndex = nh.dbIndex
  338. h.Unlock()
  339. return ret, nil
  340. }
  341. }
  342. // checks is needed because to cover the case where the number of bits is not a multiple of blockLen
  343. func (h *Handle) validateOrdinal(ordinal uint64) error {
  344. h.Lock()
  345. defer h.Unlock()
  346. if ordinal >= h.bits {
  347. return errors.New("bit does not belong to the sequence")
  348. }
  349. return nil
  350. }
  351. // Destroy removes from the datastore the data belonging to this handle
  352. func (h *Handle) Destroy() error {
  353. for {
  354. if err := h.deleteFromStore(); err != nil {
  355. if _, ok := err.(types.RetryError); !ok {
  356. return fmt.Errorf("internal failure while destroying the sequence: %v", err)
  357. }
  358. // Fetch latest
  359. if err := h.store.GetObject(datastore.Key(h.Key()...), h); err != nil {
  360. if err == datastore.ErrKeyNotFound { // already removed
  361. return nil
  362. }
  363. return fmt.Errorf("failed to fetch from store when destroying the sequence: %v", err)
  364. }
  365. continue
  366. }
  367. return nil
  368. }
  369. }
  370. // ToByteArray converts this handle's data into a byte array
  371. func (h *Handle) ToByteArray() ([]byte, error) {
  372. h.Lock()
  373. defer h.Unlock()
  374. ba := make([]byte, 16)
  375. binary.BigEndian.PutUint64(ba[0:], h.bits)
  376. binary.BigEndian.PutUint64(ba[8:], h.unselected)
  377. bm, err := h.head.toByteArray()
  378. if err != nil {
  379. return nil, fmt.Errorf("failed to serialize head: %s", err.Error())
  380. }
  381. ba = append(ba, bm...)
  382. return ba, nil
  383. }
  384. // FromByteArray reads his handle's data from a byte array
  385. func (h *Handle) FromByteArray(ba []byte) error {
  386. if ba == nil {
  387. return errors.New("nil byte array")
  388. }
  389. nh := &sequence{}
  390. err := nh.fromByteArray(ba[16:])
  391. if err != nil {
  392. return fmt.Errorf("failed to deserialize head: %s", err.Error())
  393. }
  394. h.Lock()
  395. h.head = nh
  396. h.bits = binary.BigEndian.Uint64(ba[0:8])
  397. h.unselected = binary.BigEndian.Uint64(ba[8:16])
  398. h.Unlock()
  399. return nil
  400. }
  401. // Bits returns the length of the bit sequence
  402. func (h *Handle) Bits() uint64 {
  403. return h.bits
  404. }
  405. // Unselected returns the number of bits which are not selected
  406. func (h *Handle) Unselected() uint64 {
  407. h.Lock()
  408. defer h.Unlock()
  409. return h.unselected
  410. }
  411. func (h *Handle) String() string {
  412. h.Lock()
  413. defer h.Unlock()
  414. return fmt.Sprintf("App: %s, ID: %s, DBIndex: 0x%x, Bits: %d, Unselected: %d, Sequence: %s Curr:%d",
  415. h.app, h.id, h.dbIndex, h.bits, h.unselected, h.head.toString(), h.curr)
  416. }
  417. // MarshalJSON encodes Handle into json message
  418. func (h *Handle) MarshalJSON() ([]byte, error) {
  419. m := map[string]interface{}{
  420. "id": h.id,
  421. }
  422. b, err := h.ToByteArray()
  423. if err != nil {
  424. return nil, err
  425. }
  426. m["sequence"] = b
  427. return json.Marshal(m)
  428. }
  429. // UnmarshalJSON decodes json message into Handle
  430. func (h *Handle) UnmarshalJSON(data []byte) error {
  431. var (
  432. m map[string]interface{}
  433. b []byte
  434. err error
  435. )
  436. if err = json.Unmarshal(data, &m); err != nil {
  437. return err
  438. }
  439. h.id = m["id"].(string)
  440. bi, _ := json.Marshal(m["sequence"])
  441. if err := json.Unmarshal(bi, &b); err != nil {
  442. return err
  443. }
  444. return h.FromByteArray(b)
  445. }
  446. // getFirstAvailable looks for the first unset bit in passed mask starting from start
  447. func getFirstAvailable(head *sequence, start uint64) (uint64, uint64, error) {
  448. // Find sequence which contains the start bit
  449. byteStart, bitStart := ordinalToPos(start)
  450. current, _, precBlocks, inBlockBytePos := findSequence(head, byteStart)
  451. // Derive the this sequence offsets
  452. byteOffset := byteStart - inBlockBytePos
  453. bitOffset := inBlockBytePos*8 + bitStart
  454. for current != nil {
  455. if current.block != blockMAX {
  456. // If the current block is not full, check if there is any bit
  457. // from the current bit in the current block. If not, before proceeding to the
  458. // next block node, make sure we check for available bit in the next
  459. // instance of the same block. Due to RLE same block signature will be
  460. // compressed.
  461. retry:
  462. bytePos, bitPos, err := current.getAvailableBit(bitOffset)
  463. if err != nil && precBlocks == current.count-1 {
  464. // This is the last instance in the same block node,
  465. // so move to the next block.
  466. goto next
  467. }
  468. if err != nil {
  469. // There are some more instances of the same block, so add the offset
  470. // and be optimistic that you will find the available bit in the next
  471. // instance of the same block.
  472. bitOffset = 0
  473. byteOffset += blockBytes
  474. precBlocks++
  475. goto retry
  476. }
  477. return byteOffset + bytePos, bitPos, err
  478. }
  479. // Moving to next block: Reset bit offset.
  480. next:
  481. bitOffset = 0
  482. byteOffset += (current.count * blockBytes) - (precBlocks * blockBytes)
  483. precBlocks = 0
  484. current = current.next
  485. }
  486. return invalidPos, invalidPos, ErrNoBitAvailable
  487. }
  488. // getAvailableFromCurrent will look for available ordinal from the current ordinal.
  489. // If none found then it will loop back to the start to check of the available bit.
  490. // This can be further optimized to check from start till curr in case of a rollover
  491. func getAvailableFromCurrent(head *sequence, start, curr, end uint64) (uint64, uint64, error) {
  492. var bytePos, bitPos uint64
  493. var err error
  494. if curr != 0 && curr > start {
  495. bytePos, bitPos, err = getFirstAvailable(head, curr)
  496. ret := posToOrdinal(bytePos, bitPos)
  497. if end < ret || err != nil {
  498. goto begin
  499. }
  500. return bytePos, bitPos, nil
  501. }
  502. begin:
  503. bytePos, bitPos, err = getFirstAvailable(head, start)
  504. ret := posToOrdinal(bytePos, bitPos)
  505. if end < ret || err != nil {
  506. return invalidPos, invalidPos, ErrNoBitAvailable
  507. }
  508. return bytePos, bitPos, nil
  509. }
  510. // checkIfAvailable checks if the bit correspondent to the specified ordinal is unset
  511. // If the ordinal is beyond the sequence limits, a negative response is returned
  512. func checkIfAvailable(head *sequence, ordinal uint64) (uint64, uint64, error) {
  513. bytePos, bitPos := ordinalToPos(ordinal)
  514. // Find the sequence containing this byte
  515. current, _, _, inBlockBytePos := findSequence(head, bytePos)
  516. if current != nil {
  517. // Check whether the bit corresponding to the ordinal address is unset
  518. bitSel := blockFirstBit >> (inBlockBytePos*8 + bitPos)
  519. if current.block&bitSel == 0 {
  520. return bytePos, bitPos, nil
  521. }
  522. }
  523. return invalidPos, invalidPos, ErrBitAllocated
  524. }
  525. // Given the byte position and the sequences list head, return the pointer to the
  526. // sequence containing the byte (current), the pointer to the previous sequence,
  527. // the number of blocks preceding the block containing the byte inside the current sequence.
  528. // If bytePos is outside of the list, function will return (nil, nil, 0, invalidPos)
  529. func findSequence(head *sequence, bytePos uint64) (*sequence, *sequence, uint64, uint64) {
  530. // Find the sequence containing this byte
  531. previous := head
  532. current := head
  533. n := bytePos
  534. for current.next != nil && n >= (current.count*blockBytes) { // Nil check for less than 32 addresses masks
  535. n -= (current.count * blockBytes)
  536. previous = current
  537. current = current.next
  538. }
  539. // If byte is outside of the list, let caller know
  540. if n >= (current.count * blockBytes) {
  541. return nil, nil, 0, invalidPos
  542. }
  543. // Find the byte position inside the block and the number of blocks
  544. // preceding the block containing the byte inside this sequence
  545. precBlocks := n / blockBytes
  546. inBlockBytePos := bytePos % blockBytes
  547. return current, previous, precBlocks, inBlockBytePos
  548. }
  549. // PushReservation pushes the bit reservation inside the bitmask.
  550. // Given byte and bit positions, identify the sequence (current) which holds the block containing the affected bit.
  551. // Create a new block with the modified bit according to the operation (allocate/release).
  552. // Create a new sequence containing the new block and insert it in the proper position.
  553. // Remove current sequence if empty.
  554. // Check if new sequence can be merged with neighbour (previous/next) sequences.
  555. //
  556. //
  557. // Identify "current" sequence containing block:
  558. // [prev seq] [current seq] [next seq]
  559. //
  560. // Based on block position, resulting list of sequences can be any of three forms:
  561. //
  562. // block position Resulting list of sequences
  563. // A) block is first in current: [prev seq] [new] [modified current seq] [next seq]
  564. // B) block is last in current: [prev seq] [modified current seq] [new] [next seq]
  565. // C) block is in the middle of current: [prev seq] [curr pre] [new] [curr post] [next seq]
  566. func pushReservation(bytePos, bitPos uint64, head *sequence, release bool) *sequence {
  567. // Store list's head
  568. newHead := head
  569. // Find the sequence containing this byte
  570. current, previous, precBlocks, inBlockBytePos := findSequence(head, bytePos)
  571. if current == nil {
  572. return newHead
  573. }
  574. // Construct updated block
  575. bitSel := blockFirstBit >> (inBlockBytePos*8 + bitPos)
  576. newBlock := current.block
  577. if release {
  578. newBlock &^= bitSel
  579. } else {
  580. newBlock |= bitSel
  581. }
  582. // Quit if it was a redundant request
  583. if current.block == newBlock {
  584. return newHead
  585. }
  586. // Current sequence inevitably looses one block, upadate count
  587. current.count--
  588. // Create new sequence
  589. newSequence := &sequence{block: newBlock, count: 1}
  590. // Insert the new sequence in the list based on block position
  591. if precBlocks == 0 { // First in sequence (A)
  592. newSequence.next = current
  593. if current == head {
  594. newHead = newSequence
  595. previous = newHead
  596. } else {
  597. previous.next = newSequence
  598. }
  599. removeCurrentIfEmpty(&newHead, newSequence, current)
  600. mergeSequences(previous)
  601. } else if precBlocks == current.count { // Last in sequence (B)
  602. newSequence.next = current.next
  603. current.next = newSequence
  604. mergeSequences(current)
  605. } else { // In between the sequence (C)
  606. currPre := &sequence{block: current.block, count: precBlocks, next: newSequence}
  607. currPost := current
  608. currPost.count -= precBlocks
  609. newSequence.next = currPost
  610. if currPost == head {
  611. newHead = currPre
  612. } else {
  613. previous.next = currPre
  614. }
  615. // No merging or empty current possible here
  616. }
  617. return newHead
  618. }
  619. // Removes the current sequence from the list if empty, adjusting the head pointer if needed
  620. func removeCurrentIfEmpty(head **sequence, previous, current *sequence) {
  621. if current.count == 0 {
  622. if current == *head {
  623. *head = current.next
  624. } else {
  625. previous.next = current.next
  626. current = current.next
  627. }
  628. }
  629. }
  630. // Given a pointer to a sequence, it checks if it can be merged with any following sequences
  631. // It stops when no more merging is possible.
  632. // TODO: Optimization: only attempt merge from start to end sequence, no need to scan till the end of the list
  633. func mergeSequences(seq *sequence) {
  634. if seq != nil {
  635. // Merge all what possible from seq
  636. for seq.next != nil && seq.block == seq.next.block {
  637. seq.count += seq.next.count
  638. seq.next = seq.next.next
  639. }
  640. // Move to next
  641. mergeSequences(seq.next)
  642. }
  643. }
  644. func getNumBlocks(numBits uint64) uint64 {
  645. numBlocks := numBits / uint64(blockLen)
  646. if numBits%uint64(blockLen) != 0 {
  647. numBlocks++
  648. }
  649. return numBlocks
  650. }
  651. func ordinalToPos(ordinal uint64) (uint64, uint64) {
  652. return ordinal / 8, ordinal % 8
  653. }
  654. func posToOrdinal(bytePos, bitPos uint64) uint64 {
  655. return bytePos*8 + bitPos
  656. }