roaringarray.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. package roaring
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "github.com/RoaringBitmap/roaring/internal"
  7. "io"
  8. )
  9. type container interface {
  10. // addOffset returns the (low, high) parts of the shifted container.
  11. // Whenever one of them would be empty, nil will be returned instead to
  12. // avoid unnecessary allocations.
  13. addOffset(uint16) (container, container)
  14. clone() container
  15. and(container) container
  16. andCardinality(container) int
  17. iand(container) container // i stands for inplace
  18. andNot(container) container
  19. iandNot(container) container // i stands for inplace
  20. isEmpty() bool
  21. getCardinality() int
  22. // rank returns the number of integers that are
  23. // smaller or equal to x. rank(infinity) would be getCardinality().
  24. rank(uint16) int
  25. iadd(x uint16) bool // inplace, returns true if x was new.
  26. iaddReturnMinimized(uint16) container // may change return type to minimize storage.
  27. //addRange(start, final int) container // range is [firstOfRange,lastOfRange) (unused)
  28. iaddRange(start, endx int) container // i stands for inplace, range is [firstOfRange,endx)
  29. iremove(x uint16) bool // inplace, returns true if x was present.
  30. iremoveReturnMinimized(uint16) container // may change return type to minimize storage.
  31. not(start, final int) container // range is [firstOfRange,lastOfRange)
  32. inot(firstOfRange, endx int) container // i stands for inplace, range is [firstOfRange,endx)
  33. xor(r container) container
  34. getShortIterator() shortPeekable
  35. iterate(cb func(x uint16) bool) bool
  36. getReverseIterator() shortIterable
  37. getManyIterator() manyIterable
  38. contains(i uint16) bool
  39. maximum() uint16
  40. minimum() uint16
  41. // equals is now logical equals; it does not require the
  42. // same underlying container types, but compares across
  43. // any of the implementations.
  44. equals(r container) bool
  45. fillLeastSignificant16bits(array []uint32, i int, mask uint32) int
  46. or(r container) container
  47. orCardinality(r container) int
  48. isFull() bool
  49. ior(r container) container // i stands for inplace
  50. intersects(r container) bool // whether the two containers intersect
  51. lazyOR(r container) container
  52. lazyIOR(r container) container
  53. getSizeInBytes() int
  54. //removeRange(start, final int) container // range is [firstOfRange,lastOfRange) (unused)
  55. iremoveRange(start, final int) container // i stands for inplace, range is [firstOfRange,lastOfRange)
  56. selectInt(x uint16) int // selectInt returns the xth integer in the container
  57. serializedSizeInBytes() int
  58. writeTo(io.Writer) (int, error)
  59. numberOfRuns() int
  60. toEfficientContainer() container
  61. String() string
  62. containerType() contype
  63. }
  64. type contype uint8
  65. const (
  66. bitmapContype contype = iota
  67. arrayContype
  68. run16Contype
  69. run32Contype
  70. )
  71. // careful: range is [firstOfRange,lastOfRange]
  72. func rangeOfOnes(start, last int) container {
  73. if start > MaxUint16 {
  74. panic("rangeOfOnes called with start > MaxUint16")
  75. }
  76. if last > MaxUint16 {
  77. panic("rangeOfOnes called with last > MaxUint16")
  78. }
  79. if start < 0 {
  80. panic("rangeOfOnes called with start < 0")
  81. }
  82. if last < 0 {
  83. panic("rangeOfOnes called with last < 0")
  84. }
  85. return newRunContainer16Range(uint16(start), uint16(last))
  86. }
  87. type roaringArray struct {
  88. keys []uint16
  89. containers []container `msg:"-"` // don't try to serialize directly.
  90. needCopyOnWrite []bool
  91. copyOnWrite bool
  92. }
  93. func newRoaringArray() *roaringArray {
  94. return &roaringArray{}
  95. }
  96. // runOptimize compresses the element containers to minimize space consumed.
  97. // Q: how does this interact with copyOnWrite and needCopyOnWrite?
  98. // A: since we aren't changing the logical content, just the representation,
  99. // we don't bother to check the needCopyOnWrite bits. We replace
  100. // (possibly all) elements of ra.containers in-place with space
  101. // optimized versions.
  102. func (ra *roaringArray) runOptimize() {
  103. for i := range ra.containers {
  104. ra.containers[i] = ra.containers[i].toEfficientContainer()
  105. }
  106. }
  107. func (ra *roaringArray) appendContainer(key uint16, value container, mustCopyOnWrite bool) {
  108. ra.keys = append(ra.keys, key)
  109. ra.containers = append(ra.containers, value)
  110. ra.needCopyOnWrite = append(ra.needCopyOnWrite, mustCopyOnWrite)
  111. }
  112. func (ra *roaringArray) appendWithoutCopy(sa roaringArray, startingindex int) {
  113. mustCopyOnWrite := sa.needCopyOnWrite[startingindex]
  114. ra.appendContainer(sa.keys[startingindex], sa.containers[startingindex], mustCopyOnWrite)
  115. }
  116. func (ra *roaringArray) appendCopy(sa roaringArray, startingindex int) {
  117. // cow only if the two request it, or if we already have a lightweight copy
  118. copyonwrite := (ra.copyOnWrite && sa.copyOnWrite) || sa.needsCopyOnWrite(startingindex)
  119. if !copyonwrite {
  120. // since there is no copy-on-write, we need to clone the container (this is important)
  121. ra.appendContainer(sa.keys[startingindex], sa.containers[startingindex].clone(), copyonwrite)
  122. } else {
  123. ra.appendContainer(sa.keys[startingindex], sa.containers[startingindex], copyonwrite)
  124. if !sa.needsCopyOnWrite(startingindex) {
  125. sa.setNeedsCopyOnWrite(startingindex)
  126. }
  127. }
  128. }
  129. func (ra *roaringArray) appendWithoutCopyMany(sa roaringArray, startingindex, end int) {
  130. for i := startingindex; i < end; i++ {
  131. ra.appendWithoutCopy(sa, i)
  132. }
  133. }
  134. func (ra *roaringArray) appendCopyMany(sa roaringArray, startingindex, end int) {
  135. for i := startingindex; i < end; i++ {
  136. ra.appendCopy(sa, i)
  137. }
  138. }
  139. func (ra *roaringArray) appendCopiesUntil(sa roaringArray, stoppingKey uint16) {
  140. // cow only if the two request it, or if we already have a lightweight copy
  141. copyonwrite := ra.copyOnWrite && sa.copyOnWrite
  142. for i := 0; i < sa.size(); i++ {
  143. if sa.keys[i] >= stoppingKey {
  144. break
  145. }
  146. thiscopyonewrite := copyonwrite || sa.needsCopyOnWrite(i)
  147. if thiscopyonewrite {
  148. ra.appendContainer(sa.keys[i], sa.containers[i], thiscopyonewrite)
  149. if !sa.needsCopyOnWrite(i) {
  150. sa.setNeedsCopyOnWrite(i)
  151. }
  152. } else {
  153. // since there is no copy-on-write, we need to clone the container (this is important)
  154. ra.appendContainer(sa.keys[i], sa.containers[i].clone(), thiscopyonewrite)
  155. }
  156. }
  157. }
  158. func (ra *roaringArray) appendCopiesAfter(sa roaringArray, beforeStart uint16) {
  159. // cow only if the two request it, or if we already have a lightweight copy
  160. copyonwrite := ra.copyOnWrite && sa.copyOnWrite
  161. startLocation := sa.getIndex(beforeStart)
  162. if startLocation >= 0 {
  163. startLocation++
  164. } else {
  165. startLocation = -startLocation - 1
  166. }
  167. for i := startLocation; i < sa.size(); i++ {
  168. thiscopyonewrite := copyonwrite || sa.needsCopyOnWrite(i)
  169. if thiscopyonewrite {
  170. ra.appendContainer(sa.keys[i], sa.containers[i], thiscopyonewrite)
  171. if !sa.needsCopyOnWrite(i) {
  172. sa.setNeedsCopyOnWrite(i)
  173. }
  174. } else {
  175. // since there is no copy-on-write, we need to clone the container (this is important)
  176. ra.appendContainer(sa.keys[i], sa.containers[i].clone(), thiscopyonewrite)
  177. }
  178. }
  179. }
  180. func (ra *roaringArray) removeIndexRange(begin, end int) {
  181. if end <= begin {
  182. return
  183. }
  184. r := end - begin
  185. copy(ra.keys[begin:], ra.keys[end:])
  186. copy(ra.containers[begin:], ra.containers[end:])
  187. copy(ra.needCopyOnWrite[begin:], ra.needCopyOnWrite[end:])
  188. ra.resize(len(ra.keys) - r)
  189. }
  190. func (ra *roaringArray) resize(newsize int) {
  191. for k := newsize; k < len(ra.containers); k++ {
  192. ra.containers[k] = nil
  193. }
  194. ra.keys = ra.keys[:newsize]
  195. ra.containers = ra.containers[:newsize]
  196. ra.needCopyOnWrite = ra.needCopyOnWrite[:newsize]
  197. }
  198. func (ra *roaringArray) clear() {
  199. ra.resize(0)
  200. ra.copyOnWrite = false
  201. }
  202. func (ra *roaringArray) clone() *roaringArray {
  203. sa := roaringArray{}
  204. sa.copyOnWrite = ra.copyOnWrite
  205. // this is where copyOnWrite is used.
  206. if ra.copyOnWrite {
  207. sa.keys = make([]uint16, len(ra.keys))
  208. copy(sa.keys, ra.keys)
  209. sa.containers = make([]container, len(ra.containers))
  210. copy(sa.containers, ra.containers)
  211. sa.needCopyOnWrite = make([]bool, len(ra.needCopyOnWrite))
  212. ra.markAllAsNeedingCopyOnWrite()
  213. sa.markAllAsNeedingCopyOnWrite()
  214. // sa.needCopyOnWrite is shared
  215. } else {
  216. // make a full copy
  217. sa.keys = make([]uint16, len(ra.keys))
  218. copy(sa.keys, ra.keys)
  219. sa.containers = make([]container, len(ra.containers))
  220. for i := range sa.containers {
  221. sa.containers[i] = ra.containers[i].clone()
  222. }
  223. sa.needCopyOnWrite = make([]bool, len(ra.needCopyOnWrite))
  224. }
  225. return &sa
  226. }
  227. // clone all containers which have needCopyOnWrite set to true
  228. // This can be used to make sure it is safe to munmap a []byte
  229. // that the roaring array may still have a reference to.
  230. func (ra *roaringArray) cloneCopyOnWriteContainers() {
  231. for i, needCopyOnWrite := range ra.needCopyOnWrite {
  232. if needCopyOnWrite {
  233. ra.containers[i] = ra.containers[i].clone()
  234. ra.needCopyOnWrite[i] = false
  235. }
  236. }
  237. }
  238. // unused function:
  239. //func (ra *roaringArray) containsKey(x uint16) bool {
  240. // return (ra.binarySearch(0, int64(len(ra.keys)), x) >= 0)
  241. //}
  242. func (ra *roaringArray) getContainer(x uint16) container {
  243. i := ra.binarySearch(0, int64(len(ra.keys)), x)
  244. if i < 0 {
  245. return nil
  246. }
  247. return ra.containers[i]
  248. }
  249. func (ra *roaringArray) getContainerAtIndex(i int) container {
  250. return ra.containers[i]
  251. }
  252. func (ra *roaringArray) getFastContainerAtIndex(i int, needsWriteable bool) container {
  253. c := ra.getContainerAtIndex(i)
  254. switch t := c.(type) {
  255. case *arrayContainer:
  256. c = t.toBitmapContainer()
  257. case *runContainer16:
  258. if !t.isFull() {
  259. c = t.toBitmapContainer()
  260. }
  261. case *bitmapContainer:
  262. if needsWriteable && ra.needCopyOnWrite[i] {
  263. c = ra.containers[i].clone()
  264. }
  265. }
  266. return c
  267. }
  268. // getUnionedWritableContainer switches behavior for in-place Or
  269. // depending on whether the container requires a copy on write.
  270. // If it does using the non-inplace or() method leads to fewer allocations.
  271. func (ra *roaringArray) getUnionedWritableContainer(pos int, other container) container {
  272. if ra.needCopyOnWrite[pos] {
  273. return ra.getContainerAtIndex(pos).or(other)
  274. }
  275. return ra.getContainerAtIndex(pos).ior(other)
  276. }
  277. func (ra *roaringArray) getWritableContainerAtIndex(i int) container {
  278. if ra.needCopyOnWrite[i] {
  279. ra.containers[i] = ra.containers[i].clone()
  280. ra.needCopyOnWrite[i] = false
  281. }
  282. return ra.containers[i]
  283. }
  284. func (ra *roaringArray) getIndex(x uint16) int {
  285. // before the binary search, we optimize for frequent cases
  286. size := len(ra.keys)
  287. if (size == 0) || (ra.keys[size-1] == x) {
  288. return size - 1
  289. }
  290. return ra.binarySearch(0, int64(size), x)
  291. }
  292. func (ra *roaringArray) getKeyAtIndex(i int) uint16 {
  293. return ra.keys[i]
  294. }
  295. func (ra *roaringArray) insertNewKeyValueAt(i int, key uint16, value container) {
  296. ra.keys = append(ra.keys, 0)
  297. ra.containers = append(ra.containers, nil)
  298. copy(ra.keys[i+1:], ra.keys[i:])
  299. copy(ra.containers[i+1:], ra.containers[i:])
  300. ra.keys[i] = key
  301. ra.containers[i] = value
  302. ra.needCopyOnWrite = append(ra.needCopyOnWrite, false)
  303. copy(ra.needCopyOnWrite[i+1:], ra.needCopyOnWrite[i:])
  304. ra.needCopyOnWrite[i] = false
  305. }
  306. func (ra *roaringArray) remove(key uint16) bool {
  307. i := ra.binarySearch(0, int64(len(ra.keys)), key)
  308. if i >= 0 { // if a new key
  309. ra.removeAtIndex(i)
  310. return true
  311. }
  312. return false
  313. }
  314. func (ra *roaringArray) removeAtIndex(i int) {
  315. copy(ra.keys[i:], ra.keys[i+1:])
  316. copy(ra.containers[i:], ra.containers[i+1:])
  317. copy(ra.needCopyOnWrite[i:], ra.needCopyOnWrite[i+1:])
  318. ra.resize(len(ra.keys) - 1)
  319. }
  320. func (ra *roaringArray) setContainerAtIndex(i int, c container) {
  321. ra.containers[i] = c
  322. }
  323. func (ra *roaringArray) replaceKeyAndContainerAtIndex(i int, key uint16, c container, mustCopyOnWrite bool) {
  324. ra.keys[i] = key
  325. ra.containers[i] = c
  326. ra.needCopyOnWrite[i] = mustCopyOnWrite
  327. }
  328. func (ra *roaringArray) size() int {
  329. return len(ra.keys)
  330. }
  331. func (ra *roaringArray) binarySearch(begin, end int64, ikey uint16) int {
  332. low := begin
  333. high := end - 1
  334. for low+16 <= high {
  335. middleIndex := low + (high-low)/2 // avoid overflow
  336. middleValue := ra.keys[middleIndex]
  337. if middleValue < ikey {
  338. low = middleIndex + 1
  339. } else if middleValue > ikey {
  340. high = middleIndex - 1
  341. } else {
  342. return int(middleIndex)
  343. }
  344. }
  345. for ; low <= high; low++ {
  346. val := ra.keys[low]
  347. if val >= ikey {
  348. if val == ikey {
  349. return int(low)
  350. }
  351. break
  352. }
  353. }
  354. return -int(low + 1)
  355. }
  356. func (ra *roaringArray) equals(o interface{}) bool {
  357. srb, ok := o.(roaringArray)
  358. if ok {
  359. if srb.size() != ra.size() {
  360. return false
  361. }
  362. for i, k := range ra.keys {
  363. if k != srb.keys[i] {
  364. return false
  365. }
  366. }
  367. for i, c := range ra.containers {
  368. if !c.equals(srb.containers[i]) {
  369. return false
  370. }
  371. }
  372. return true
  373. }
  374. return false
  375. }
  376. func (ra *roaringArray) headerSize() uint64 {
  377. size := uint64(len(ra.keys))
  378. if ra.hasRunCompression() {
  379. if size < noOffsetThreshold { // for small bitmaps, we omit the offsets
  380. return 4 + (size+7)/8 + 4*size
  381. }
  382. return 4 + (size+7)/8 + 8*size // - 4 because we pack the size with the cookie
  383. }
  384. return 4 + 4 + 8*size
  385. }
  386. // should be dirt cheap
  387. func (ra *roaringArray) serializedSizeInBytes() uint64 {
  388. answer := ra.headerSize()
  389. for _, c := range ra.containers {
  390. answer += uint64(c.serializedSizeInBytes())
  391. }
  392. return answer
  393. }
  394. //
  395. // spec: https://github.com/RoaringBitmap/RoaringFormatSpec
  396. //
  397. func (ra *roaringArray) writeTo(w io.Writer) (n int64, err error) {
  398. hasRun := ra.hasRunCompression()
  399. isRunSizeInBytes := 0
  400. cookieSize := 8
  401. if hasRun {
  402. cookieSize = 4
  403. isRunSizeInBytes = (len(ra.keys) + 7) / 8
  404. }
  405. descriptiveHeaderSize := 4 * len(ra.keys)
  406. preambleSize := cookieSize + isRunSizeInBytes + descriptiveHeaderSize
  407. buf := make([]byte, preambleSize+4*len(ra.keys))
  408. nw := 0
  409. if hasRun {
  410. binary.LittleEndian.PutUint16(buf[0:], uint16(serialCookie))
  411. nw += 2
  412. binary.LittleEndian.PutUint16(buf[2:], uint16(len(ra.keys)-1))
  413. nw += 2
  414. // compute isRun bitmap without temporary allocation
  415. var runbitmapslice = buf[nw : nw+isRunSizeInBytes]
  416. for i, c := range ra.containers {
  417. switch c.(type) {
  418. case *runContainer16:
  419. runbitmapslice[i/8] |= 1 << (uint(i) % 8)
  420. }
  421. }
  422. nw += isRunSizeInBytes
  423. } else {
  424. binary.LittleEndian.PutUint32(buf[0:], uint32(serialCookieNoRunContainer))
  425. nw += 4
  426. binary.LittleEndian.PutUint32(buf[4:], uint32(len(ra.keys)))
  427. nw += 4
  428. }
  429. // descriptive header
  430. for i, key := range ra.keys {
  431. binary.LittleEndian.PutUint16(buf[nw:], key)
  432. nw += 2
  433. c := ra.containers[i]
  434. binary.LittleEndian.PutUint16(buf[nw:], uint16(c.getCardinality()-1))
  435. nw += 2
  436. }
  437. startOffset := int64(preambleSize + 4*len(ra.keys))
  438. if !hasRun || (len(ra.keys) >= noOffsetThreshold) {
  439. // offset header
  440. for _, c := range ra.containers {
  441. binary.LittleEndian.PutUint32(buf[nw:], uint32(startOffset))
  442. nw += 4
  443. switch rc := c.(type) {
  444. case *runContainer16:
  445. startOffset += 2 + int64(len(rc.iv))*4
  446. default:
  447. startOffset += int64(getSizeInBytesFromCardinality(c.getCardinality()))
  448. }
  449. }
  450. }
  451. written, err := w.Write(buf[:nw])
  452. if err != nil {
  453. return n, err
  454. }
  455. n += int64(written)
  456. for _, c := range ra.containers {
  457. written, err := c.writeTo(w)
  458. if err != nil {
  459. return n, err
  460. }
  461. n += int64(written)
  462. }
  463. return n, nil
  464. }
  465. //
  466. // spec: https://github.com/RoaringBitmap/RoaringFormatSpec
  467. //
  468. func (ra *roaringArray) toBytes() ([]byte, error) {
  469. var buf bytes.Buffer
  470. _, err := ra.writeTo(&buf)
  471. return buf.Bytes(), err
  472. }
  473. func (ra *roaringArray) readFrom(stream internal.ByteInput, cookieHeader ...byte) (int64, error) {
  474. var cookie uint32
  475. var err error
  476. if len(cookieHeader) > 0 && len(cookieHeader) != 4 {
  477. return int64(len(cookieHeader)), fmt.Errorf("error in roaringArray.readFrom: could not read initial cookie: incorrect size of cookie header")
  478. }
  479. if len(cookieHeader) == 4 {
  480. cookie = binary.LittleEndian.Uint32(cookieHeader)
  481. } else {
  482. cookie, err = stream.ReadUInt32()
  483. if err != nil {
  484. return stream.GetReadBytes(), fmt.Errorf("error in roaringArray.readFrom: could not read initial cookie: %s", err)
  485. }
  486. }
  487. var size uint32
  488. var isRunBitmap []byte
  489. if cookie&0x0000FFFF == serialCookie {
  490. size = uint32(cookie>>16 + 1)
  491. // create is-run-container bitmap
  492. isRunBitmapSize := (int(size) + 7) / 8
  493. isRunBitmap, err = stream.Next(isRunBitmapSize)
  494. if err != nil {
  495. return stream.GetReadBytes(), fmt.Errorf("malformed bitmap, failed to read is-run bitmap, got: %s", err)
  496. }
  497. } else if cookie == serialCookieNoRunContainer {
  498. size, err = stream.ReadUInt32()
  499. if err != nil {
  500. return stream.GetReadBytes(), fmt.Errorf("malformed bitmap, failed to read a bitmap size: %s", err)
  501. }
  502. } else {
  503. return stream.GetReadBytes(), fmt.Errorf("error in roaringArray.readFrom: did not find expected serialCookie in header")
  504. }
  505. if size > (1 << 16) {
  506. return stream.GetReadBytes(), fmt.Errorf("it is logically impossible to have more than (1<<16) containers")
  507. }
  508. // descriptive header
  509. buf, err := stream.Next(2 * 2 * int(size))
  510. if err != nil {
  511. return stream.GetReadBytes(), fmt.Errorf("failed to read descriptive header: %s", err)
  512. }
  513. keycard := byteSliceAsUint16Slice(buf)
  514. if isRunBitmap == nil || size >= noOffsetThreshold {
  515. if err := stream.SkipBytes(int(size) * 4); err != nil {
  516. return stream.GetReadBytes(), fmt.Errorf("failed to skip bytes: %s", err)
  517. }
  518. }
  519. // Allocate slices upfront as number of containers is known
  520. if cap(ra.containers) >= int(size) {
  521. ra.containers = ra.containers[:size]
  522. } else {
  523. ra.containers = make([]container, size)
  524. }
  525. if cap(ra.keys) >= int(size) {
  526. ra.keys = ra.keys[:size]
  527. } else {
  528. ra.keys = make([]uint16, size)
  529. }
  530. if cap(ra.needCopyOnWrite) >= int(size) {
  531. ra.needCopyOnWrite = ra.needCopyOnWrite[:size]
  532. } else {
  533. ra.needCopyOnWrite = make([]bool, size)
  534. }
  535. for i := uint32(0); i < size; i++ {
  536. key := keycard[2*i]
  537. card := int(keycard[2*i+1]) + 1
  538. ra.keys[i] = key
  539. ra.needCopyOnWrite[i] = true
  540. if isRunBitmap != nil && isRunBitmap[i/8]&(1<<(i%8)) != 0 {
  541. // run container
  542. nr, err := stream.ReadUInt16()
  543. if err != nil {
  544. return 0, fmt.Errorf("failed to read runtime container size: %s", err)
  545. }
  546. buf, err := stream.Next(int(nr) * 4)
  547. if err != nil {
  548. return stream.GetReadBytes(), fmt.Errorf("failed to read runtime container content: %s", err)
  549. }
  550. nb := runContainer16{
  551. iv: byteSliceAsInterval16Slice(buf),
  552. }
  553. ra.containers[i] = &nb
  554. } else if card > arrayDefaultMaxSize {
  555. // bitmap container
  556. buf, err := stream.Next(arrayDefaultMaxSize * 2)
  557. if err != nil {
  558. return stream.GetReadBytes(), fmt.Errorf("failed to read bitmap container: %s", err)
  559. }
  560. nb := bitmapContainer{
  561. cardinality: card,
  562. bitmap: byteSliceAsUint64Slice(buf),
  563. }
  564. ra.containers[i] = &nb
  565. } else {
  566. // array container
  567. buf, err := stream.Next(card * 2)
  568. if err != nil {
  569. return stream.GetReadBytes(), fmt.Errorf("failed to read array container: %s", err)
  570. }
  571. nb := arrayContainer{
  572. byteSliceAsUint16Slice(buf),
  573. }
  574. ra.containers[i] = &nb
  575. }
  576. }
  577. return stream.GetReadBytes(), nil
  578. }
  579. func (ra *roaringArray) hasRunCompression() bool {
  580. for _, c := range ra.containers {
  581. switch c.(type) {
  582. case *runContainer16:
  583. return true
  584. }
  585. }
  586. return false
  587. }
  588. func (ra *roaringArray) advanceUntil(min uint16, pos int) int {
  589. lower := pos + 1
  590. if lower >= len(ra.keys) || ra.keys[lower] >= min {
  591. return lower
  592. }
  593. spansize := 1
  594. for lower+spansize < len(ra.keys) && ra.keys[lower+spansize] < min {
  595. spansize *= 2
  596. }
  597. var upper int
  598. if lower+spansize < len(ra.keys) {
  599. upper = lower + spansize
  600. } else {
  601. upper = len(ra.keys) - 1
  602. }
  603. if ra.keys[upper] == min {
  604. return upper
  605. }
  606. if ra.keys[upper] < min {
  607. // means
  608. // array
  609. // has no
  610. // item
  611. // >= min
  612. // pos = array.length;
  613. return len(ra.keys)
  614. }
  615. // we know that the next-smallest span was too small
  616. lower += (spansize >> 1)
  617. mid := 0
  618. for lower+1 != upper {
  619. mid = (lower + upper) >> 1
  620. if ra.keys[mid] == min {
  621. return mid
  622. } else if ra.keys[mid] < min {
  623. lower = mid
  624. } else {
  625. upper = mid
  626. }
  627. }
  628. return upper
  629. }
  630. func (ra *roaringArray) markAllAsNeedingCopyOnWrite() {
  631. for i := range ra.needCopyOnWrite {
  632. ra.needCopyOnWrite[i] = true
  633. }
  634. }
  635. func (ra *roaringArray) needsCopyOnWrite(i int) bool {
  636. return ra.needCopyOnWrite[i]
  637. }
  638. func (ra *roaringArray) setNeedsCopyOnWrite(i int) {
  639. ra.needCopyOnWrite[i] = true
  640. }