sequence.go 19 KB

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