You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

760 lines
19 KiB

  1. package arbo
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "runtime"
  7. "sort"
  8. "sync"
  9. "github.com/iden3/go-merkletree/db"
  10. )
  11. /*
  12. AddBatch design
  13. ===============
  14. CASE A: Empty Tree --> if tree is empty (root==0)
  15. =================================================
  16. - Build the full tree from bottom to top (from all the leaf to the root)
  17. CASE B: ALMOST CASE A, Almost empty Tree --> if Tree has numLeafs < minLeafsThreshold
  18. ==============================================================================
  19. - Get the Leafs (key & value) (iterate the tree from the current root getting
  20. the leafs)
  21. - Create a new empty Tree
  22. - Do CASE A for the new Tree, giving the already existing key&values (leafs)
  23. from the original Tree + the new key&values to be added from the AddBatch call
  24. R R
  25. / \ / \
  26. A * / \
  27. / \ / \
  28. B C * *
  29. / | / \
  30. / | / \
  31. / | / \
  32. L: A B G D
  33. / \
  34. / \
  35. / \
  36. C *
  37. / \
  38. / \
  39. / \
  40. ... ... (nLeafs < minLeafsThreshold)
  41. CASE C: ALMOST CASE B --> if Tree has few Leafs (but numLeafs>=minLeafsThreshold)
  42. ==============================================================================
  43. - Use A, B, G, F as Roots of subtrees
  44. - Do CASE B for each subtree
  45. - Then go from L to the Root
  46. R
  47. / \
  48. / \
  49. / \
  50. * *
  51. / | / \
  52. / | / \
  53. / | / \
  54. L: A B G D
  55. / \
  56. / \
  57. / \
  58. C *
  59. / \
  60. / \
  61. / \
  62. ... ... (nLeafs >= minLeafsThreshold)
  63. CASE D: Already populated Tree
  64. ==============================
  65. - Use A, B, C, D as subtree
  66. - Sort the Keys in Buckets that share the initial part of the path
  67. - For each subtree add there the new leafs
  68. R
  69. / \
  70. / \
  71. / \
  72. * *
  73. / | / \
  74. / | / \
  75. / | / \
  76. L: A B C D
  77. /\ /\ / \ / \
  78. ... ... ... ... ... ...
  79. CASE E: Already populated Tree Unbalanced
  80. =========================================
  81. - Need to fill M1 and M2, and then will be able to use CASE D
  82. - Search for M1 & M2 in the inputed Keys
  83. - Add M1 & M2 to the Tree
  84. - From here can use CASE D
  85. R
  86. / \
  87. / \
  88. / \
  89. * *
  90. | \
  91. | \
  92. | \
  93. L: M1 * M2 * (where M1 and M2 are empty)
  94. / | /
  95. / | /
  96. / | /
  97. A * *
  98. / \ | \
  99. / \ | \
  100. / \ | \
  101. B * * C
  102. / \ |\
  103. ... ... | \
  104. | \
  105. D E
  106. Algorithm decision
  107. ==================
  108. - if nLeafs==0 (root==0): CASE A
  109. - if nLeafs<minLeafsThreshold: CASE B
  110. - if nLeafs>=minLeafsThreshold && (nLeafs/nBuckets) < minLeafsThreshold: CASE C
  111. - else: CASE D & CASE E
  112. - Multiple tree.Add calls: O(n log n)
  113. - Used in: cases A, B, C
  114. - Tree from bottom to top: O(log n)
  115. - Used in: cases D, E
  116. */
  117. const (
  118. minLeafsThreshold = 100 // nolint:gomnd // TMP WIP this will be autocalculated
  119. )
  120. // AddBatch adds a batch of key-values to the Tree. Returns an array containing
  121. // the indexes of the keys failed to add.
  122. func (t *Tree) AddBatch(keys, values [][]byte) ([]int, error) {
  123. // TODO: support vaules=nil
  124. t.updateAccessTime()
  125. t.Lock()
  126. defer t.Unlock()
  127. // when len(keyvalues) is not a power of 2, cut at the biggest power of
  128. // 2 under the len(keys), add those 2**n key-values using the AddBatch
  129. // approach, and then add the remaining key-values using tree.Add.
  130. kvs, err := t.keysValuesToKvs(keys, values)
  131. if err != nil {
  132. return nil, err
  133. }
  134. t.tx, err = t.db.NewTx()
  135. if err != nil {
  136. return nil, err
  137. }
  138. // if nCPU is not a power of two, cut at the highest power of two under
  139. // nCPU
  140. nCPU := highestPowerOfTwo(runtime.NumCPU())
  141. l := int(math.Log2(float64(nCPU)))
  142. var invalids []int
  143. // CASE A: if nLeafs==0 (root==0)
  144. if bytes.Equal(t.root, t.emptyHash) {
  145. invalids, err = t.caseA(nCPU, kvs)
  146. if err != nil {
  147. return nil, err
  148. }
  149. return t.finalizeAddBatch(len(keys), invalids)
  150. }
  151. // CASE B: if nLeafs<nBuckets
  152. nLeafs, err := t.GetNLeafs()
  153. if err != nil {
  154. return nil, err
  155. }
  156. if nLeafs < minLeafsThreshold { // CASE B
  157. var excedents []kv
  158. invalids, excedents, err = t.caseB(nCPU, 0, kvs)
  159. if err != nil {
  160. return nil, err
  161. }
  162. // add the excedents
  163. for i := 0; i < len(excedents); i++ {
  164. err = t.add(0, excedents[i].k, excedents[i].v)
  165. if err != nil {
  166. invalids = append(invalids, excedents[i].pos)
  167. }
  168. }
  169. return t.finalizeAddBatch(len(keys), invalids)
  170. }
  171. keysAtL, err := t.getKeysAtLevel(l + 1)
  172. if err != nil {
  173. return nil, err
  174. }
  175. // CASE C: if nLeafs>=minLeafsThreshold && (nLeafs/nBuckets) < minLeafsThreshold
  176. // available parallelization, will need to be a power of 2 (2**n)
  177. if nLeafs >= minLeafsThreshold &&
  178. (nLeafs/nCPU) < minLeafsThreshold &&
  179. len(keysAtL) == nCPU {
  180. invalids, err = t.caseC(nCPU, l, keysAtL, kvs)
  181. if err != nil {
  182. return nil, err
  183. }
  184. return t.finalizeAddBatch(len(keys), invalids)
  185. }
  186. // CASE E
  187. if len(keysAtL) != nCPU {
  188. // CASE E: add one key at each bucket, and then do CASE D
  189. buckets := splitInBuckets(kvs, nCPU)
  190. kvs = []kv{}
  191. for i := 0; i < len(buckets); i++ {
  192. // add one leaf of the bucket, if there is an error when
  193. // adding the k-v, try to add the next one of the bucket
  194. // (until one is added)
  195. var inserted int
  196. for j := 0; j < len(buckets[i]); j++ {
  197. if err := t.add(0, buckets[i][j].k, buckets[i][j].v); err == nil {
  198. inserted = j
  199. break
  200. }
  201. }
  202. // put the buckets elements except the inserted one
  203. kvs = append(kvs, buckets[i][:inserted]...)
  204. kvs = append(kvs, buckets[i][inserted+1:]...)
  205. }
  206. keysAtL, err = t.getKeysAtLevel(l + 1)
  207. if err != nil {
  208. return nil, err
  209. }
  210. }
  211. // CASE D
  212. if len(keysAtL) == nCPU { // enter in CASE D if len(keysAtL)=nCPU, if not, CASE E
  213. invalidsCaseD, err := t.caseD(nCPU, l, keysAtL, kvs)
  214. if err != nil {
  215. return nil, err
  216. }
  217. invalids = append(invalids, invalidsCaseD...)
  218. return t.finalizeAddBatch(len(keys), invalids)
  219. }
  220. return nil, fmt.Errorf("UNIMPLEMENTED")
  221. }
  222. func (t *Tree) finalizeAddBatch(nKeys int, invalids []int) ([]int, error) {
  223. // store root to db
  224. if err := t.tx.Put(dbKeyRoot, t.root); err != nil {
  225. return nil, err
  226. }
  227. // update nLeafs
  228. if err := t.incNLeafs(nKeys - len(invalids)); err != nil {
  229. return nil, err
  230. }
  231. // commit db tx
  232. if err := t.tx.Commit(); err != nil {
  233. return nil, err
  234. }
  235. return invalids, nil
  236. }
  237. func (t *Tree) caseA(nCPU int, kvs []kv) ([]int, error) {
  238. // if len(kvs) is not a power of 2, cut at the bigger power
  239. // of two under len(kvs), build the tree with that, and add
  240. // later the excedents
  241. kvsP2, kvsNonP2 := cutPowerOfTwo(kvs)
  242. invalids, err := t.buildTreeBottomUp(nCPU, kvsP2)
  243. if err != nil {
  244. return nil, err
  245. }
  246. for i := 0; i < len(kvsNonP2); i++ {
  247. if err = t.add(0, kvsNonP2[i].k, kvsNonP2[i].v); err != nil {
  248. invalids = append(invalids, kvsNonP2[i].pos)
  249. }
  250. }
  251. return invalids, nil
  252. }
  253. func (t *Tree) caseB(nCPU, l int, kvs []kv) ([]int, []kv, error) {
  254. // get already existing keys
  255. aKs, aVs, err := t.getLeafs(t.root)
  256. if err != nil {
  257. return nil, nil, err
  258. }
  259. aKvs, err := t.keysValuesToKvs(aKs, aVs)
  260. if err != nil {
  261. return nil, nil, err
  262. }
  263. // add already existing key-values to the inputted key-values
  264. // kvs = append(kvs, aKvs...)
  265. kvs, invalids := combineInKVSet(aKvs, kvs)
  266. // proceed with CASE A
  267. sortKvs(kvs)
  268. // cutPowerOfTwo, the excedent add it as normal Tree.Add
  269. kvsP2, kvsNonP2 := cutPowerOfTwo(kvs)
  270. var invalids2 []int
  271. if nCPU > 1 {
  272. invalids2, err = t.buildTreeBottomUp(nCPU, kvsP2)
  273. if err != nil {
  274. return nil, nil, err
  275. }
  276. } else {
  277. invalids2, err = t.buildTreeBottomUpSingleThread(kvsP2)
  278. if err != nil {
  279. return nil, nil, err
  280. }
  281. }
  282. invalids = append(invalids, invalids2...)
  283. // return the excedents which will be added at the full tree at the end
  284. return invalids, kvsNonP2, nil
  285. }
  286. func (t *Tree) caseC(nCPU, l int, keysAtL [][]byte, kvs []kv) ([]int, error) {
  287. // 1. go down until level L (L=log2(nBuckets)): keysAtL
  288. var excedents []kv
  289. buckets := splitInBuckets(kvs, nCPU)
  290. // 2. use keys at level L as roots of the subtrees under each one
  291. excedentsInBucket := make([][]kv, nCPU)
  292. subRoots := make([][]byte, nCPU)
  293. txs := make([]db.Tx, nCPU)
  294. var wg sync.WaitGroup
  295. wg.Add(nCPU)
  296. for i := 0; i < nCPU; i++ {
  297. go func(cpu int) {
  298. var err error
  299. txs[cpu], err = t.db.NewTx()
  300. if err != nil {
  301. panic(err) // TODO WIP
  302. }
  303. bucketTree := Tree{tx: txs[cpu], db: t.db, maxLevels: t.maxLevels,
  304. hashFunction: t.hashFunction, root: keysAtL[cpu]}
  305. // 3. do CASE B (with 1 cpu) for each key at level L
  306. _, bucketExcedents, err := bucketTree.caseB(1, l, buckets[cpu])
  307. if err != nil {
  308. panic(err) // TODO WIP
  309. // return nil, err
  310. }
  311. excedentsInBucket[cpu] = bucketExcedents
  312. subRoots[cpu] = bucketTree.root
  313. wg.Done()
  314. }(i)
  315. }
  316. wg.Wait()
  317. // merge buckets txs into Tree.tx
  318. for i := 0; i < len(txs); i++ {
  319. if err := t.tx.Add(txs[i]); err != nil {
  320. return nil, err
  321. }
  322. }
  323. for i := 0; i < len(excedentsInBucket); i++ {
  324. excedents = append(excedents, excedentsInBucket[i]...)
  325. }
  326. // 4. go upFromKeys from the new roots of the subtrees
  327. newRoot, err := t.upFromKeys(subRoots)
  328. if err != nil {
  329. return nil, err
  330. }
  331. t.root = newRoot
  332. // add the key-values that have not been used yet
  333. var invalids []int
  334. for i := 0; i < len(excedents); i++ {
  335. if err = t.add(0, excedents[i].k, excedents[i].v); err != nil {
  336. invalids = append(invalids, excedents[i].pos)
  337. }
  338. }
  339. return invalids, nil
  340. }
  341. func (t *Tree) caseD(nCPU, l int, keysAtL [][]byte, kvs []kv) ([]int, error) {
  342. if nCPU == 1 { // CASE D, but with 1 cpu
  343. var invalids []int
  344. for i := 0; i < len(kvs); i++ {
  345. if err := t.add(0, kvs[i].k, kvs[i].v); err != nil {
  346. invalids = append(invalids, kvs[i].pos)
  347. }
  348. }
  349. return invalids, nil
  350. }
  351. buckets := splitInBuckets(kvs, nCPU)
  352. subRoots := make([][]byte, nCPU)
  353. invalidsInBucket := make([][]int, nCPU)
  354. txs := make([]db.Tx, nCPU)
  355. var wg sync.WaitGroup
  356. wg.Add(nCPU)
  357. for i := 0; i < nCPU; i++ {
  358. go func(cpu int) {
  359. var err error
  360. txs[cpu], err = t.db.NewTx()
  361. if err != nil {
  362. panic(err) // TODO WIP
  363. }
  364. // put already existing tx into txs[cpu], as txs[cpu]
  365. // needs the pending key-values that are not in tree.db,
  366. // but are in tree.tx
  367. if err := txs[cpu].Add(t.tx); err != nil {
  368. panic(err) // TODO WIP
  369. }
  370. bucketTree := Tree{tx: txs[cpu], db: t.db, maxLevels: t.maxLevels - l,
  371. hashFunction: t.hashFunction, root: keysAtL[cpu]}
  372. for j := 0; j < len(buckets[cpu]); j++ {
  373. if err = bucketTree.add(l, buckets[cpu][j].k, buckets[cpu][j].v); err != nil {
  374. invalidsInBucket[cpu] = append(invalidsInBucket[cpu], buckets[cpu][j].pos)
  375. }
  376. }
  377. subRoots[cpu] = bucketTree.root
  378. wg.Done()
  379. }(i)
  380. }
  381. wg.Wait()
  382. // merge buckets txs into Tree.tx
  383. for i := 0; i < len(txs); i++ {
  384. if err := t.tx.Add(txs[i]); err != nil {
  385. return nil, err
  386. }
  387. }
  388. newRoot, err := t.upFromKeys(subRoots)
  389. if err != nil {
  390. return nil, err
  391. }
  392. t.root = newRoot
  393. var invalids []int
  394. for i := 0; i < len(invalidsInBucket); i++ {
  395. invalids = append(invalids, invalidsInBucket[i]...)
  396. }
  397. return invalids, nil
  398. }
  399. func splitInBuckets(kvs []kv, nBuckets int) [][]kv {
  400. buckets := make([][]kv, nBuckets)
  401. // 1. classify the keyvalues into buckets
  402. for i := 0; i < len(kvs); i++ {
  403. pair := kvs[i]
  404. // bucketnum := keyToBucket(pair.k, nBuckets)
  405. bucketnum := keyToBucket(pair.keyPath, nBuckets)
  406. buckets[bucketnum] = append(buckets[bucketnum], pair)
  407. }
  408. return buckets
  409. }
  410. // TODO rename in a more 'real' name (calculate bucket from/for key)
  411. func keyToBucket(k []byte, nBuckets int) int {
  412. nLevels := int(math.Log2(float64(nBuckets)))
  413. b := make([]int, nBuckets)
  414. for i := 0; i < nBuckets; i++ {
  415. b[i] = i
  416. }
  417. r := b
  418. mid := len(r) / 2 //nolint:gomnd
  419. for i := 0; i < nLevels; i++ {
  420. if int(k[i/8]&(1<<(i%8))) != 0 {
  421. r = r[mid:]
  422. mid = len(r) / 2 //nolint:gomnd
  423. } else {
  424. r = r[:mid]
  425. mid = len(r) / 2 //nolint:gomnd
  426. }
  427. }
  428. return r[0]
  429. }
  430. type kv struct {
  431. pos int // original position in the array
  432. keyPath []byte
  433. k []byte
  434. v []byte
  435. }
  436. // compareBytes compares byte slices where the bytes are compared from left to
  437. // right and each byte is compared by bit from right to left
  438. func compareBytes(a, b []byte) bool {
  439. // WIP
  440. for i := 0; i < len(a); i++ {
  441. for j := 0; j < 8; j++ {
  442. aBit := a[i] & (1 << j)
  443. bBit := b[i] & (1 << j)
  444. if aBit > bBit {
  445. return false
  446. } else if aBit < bBit {
  447. return true
  448. }
  449. }
  450. }
  451. return false
  452. }
  453. // sortKvs sorts the kv by path
  454. func sortKvs(kvs []kv) {
  455. sort.Slice(kvs, func(i, j int) bool {
  456. return compareBytes(kvs[i].keyPath, kvs[j].keyPath)
  457. })
  458. }
  459. func (t *Tree) keysValuesToKvs(ks, vs [][]byte) ([]kv, error) {
  460. if len(ks) != len(vs) {
  461. return nil, fmt.Errorf("len(keys)!=len(values) (%d!=%d)",
  462. len(ks), len(vs))
  463. }
  464. kvs := make([]kv, len(ks))
  465. for i := 0; i < len(ks); i++ {
  466. keyPath := make([]byte, t.hashFunction.Len())
  467. copy(keyPath[:], ks[i])
  468. kvs[i].pos = i
  469. kvs[i].keyPath = ks[i]
  470. kvs[i].k = ks[i]
  471. kvs[i].v = vs[i]
  472. }
  473. return kvs, nil
  474. }
  475. /*
  476. func (t *Tree) kvsToKeysValues(kvs []kv) ([][]byte, [][]byte) {
  477. ks := make([][]byte, len(kvs))
  478. vs := make([][]byte, len(kvs))
  479. for i := 0; i < len(kvs); i++ {
  480. ks[i] = kvs[i].k
  481. vs[i] = kvs[i].v
  482. }
  483. return ks, vs
  484. }
  485. */
  486. // buildTreeBottomUp splits the key-values into n Buckets (where n is the number
  487. // of CPUs), in parallel builds a subtree for each bucket, once all the subtrees
  488. // are built, uses the subtrees roots as keys for a new tree, which as result
  489. // will have the complete Tree build from bottom to up, where until the
  490. // log2(nCPU) level it has been computed in parallel.
  491. func (t *Tree) buildTreeBottomUp(nCPU int, kvs []kv) ([]int, error) {
  492. buckets := splitInBuckets(kvs, nCPU)
  493. subRoots := make([][]byte, nCPU)
  494. invalidsInBucket := make([][]int, nCPU)
  495. txs := make([]db.Tx, nCPU)
  496. var wg sync.WaitGroup
  497. wg.Add(nCPU)
  498. for i := 0; i < nCPU; i++ {
  499. go func(cpu int) {
  500. sortKvs(buckets[cpu])
  501. var err error
  502. txs[cpu], err = t.db.NewTx()
  503. if err != nil {
  504. panic(err) // TODO
  505. }
  506. bucketTree := Tree{tx: txs[cpu], db: t.db, maxLevels: t.maxLevels,
  507. hashFunction: t.hashFunction, root: t.emptyHash}
  508. currInvalids, err := bucketTree.buildTreeBottomUpSingleThread(buckets[cpu])
  509. if err != nil {
  510. panic(err) // TODO
  511. }
  512. invalidsInBucket[cpu] = currInvalids
  513. subRoots[cpu] = bucketTree.root
  514. wg.Done()
  515. }(i)
  516. }
  517. wg.Wait()
  518. // merge buckets txs into Tree.tx
  519. for i := 0; i < len(txs); i++ {
  520. if err := t.tx.Add(txs[i]); err != nil {
  521. return nil, err
  522. }
  523. }
  524. newRoot, err := t.upFromKeys(subRoots)
  525. if err != nil {
  526. return nil, err
  527. }
  528. t.root = newRoot
  529. var invalids []int
  530. for i := 0; i < len(invalidsInBucket); i++ {
  531. invalids = append(invalids, invalidsInBucket[i]...)
  532. }
  533. return invalids, err
  534. }
  535. // buildTreeBottomUpSingleThread builds the tree with the given []kv from bottom
  536. // to the root. keys & values must be sorted by path, and the array ks must be
  537. // length multiple of 2
  538. func (t *Tree) buildTreeBottomUpSingleThread(kvs []kv) ([]int, error) {
  539. // TODO check that log2(len(leafs)) < t.maxLevels, if not, maxLevels
  540. // would be reached and should return error
  541. var invalids []int
  542. // build the leafs
  543. leafKeys := make([][]byte, len(kvs))
  544. for i := 0; i < len(kvs); i++ {
  545. // TODO handle the case where Key&Value == 0
  546. leafKey, leafValue, err := newLeafValue(t.hashFunction, kvs[i].k, kvs[i].v)
  547. if err != nil {
  548. // return nil, err
  549. invalids = append(invalids, kvs[i].pos)
  550. }
  551. // store leafKey & leafValue to db
  552. if err := t.tx.Put(leafKey, leafValue); err != nil {
  553. // return nil, err
  554. invalids = append(invalids, kvs[i].pos)
  555. }
  556. leafKeys[i] = leafKey
  557. }
  558. r, err := t.upFromKeys(leafKeys)
  559. if err != nil {
  560. return invalids, err
  561. }
  562. t.root = r
  563. return invalids, nil
  564. }
  565. // keys & values must be sorted by path, and the array ks must be length
  566. // multiple of 2
  567. func (t *Tree) upFromKeys(ks [][]byte) ([]byte, error) {
  568. if len(ks) == 1 {
  569. return ks[0], nil
  570. }
  571. var rKs [][]byte
  572. for i := 0; i < len(ks); i += 2 {
  573. // TODO handle the case where Key&Value == 0
  574. k, v, err := newIntermediate(t.hashFunction, ks[i], ks[i+1])
  575. if err != nil {
  576. return nil, err
  577. }
  578. // store k-v to db
  579. if err = t.tx.Put(k, v); err != nil {
  580. return nil, err
  581. }
  582. rKs = append(rKs, k)
  583. }
  584. return t.upFromKeys(rKs)
  585. }
  586. func (t *Tree) getLeafs(root []byte) ([][]byte, [][]byte, error) {
  587. var ks, vs [][]byte
  588. err := t.iter(root, func(k, v []byte) {
  589. if v[0] != PrefixValueLeaf {
  590. return
  591. }
  592. leafK, leafV := ReadLeafValue(v)
  593. ks = append(ks, leafK)
  594. vs = append(vs, leafV)
  595. })
  596. return ks, vs, err
  597. }
  598. func (t *Tree) getKeysAtLevel(l int) ([][]byte, error) {
  599. var keys [][]byte
  600. err := t.iterWithStop(t.root, 0, func(currLvl int, k, v []byte) bool {
  601. if currLvl == l && !bytes.Equal(k, t.emptyHash) {
  602. keys = append(keys, k)
  603. }
  604. if currLvl >= l {
  605. return true // to stop the iter from going down
  606. }
  607. return false
  608. })
  609. return keys, err
  610. }
  611. // cutPowerOfTwo returns []kv of length that is a power of 2, and a second []kv
  612. // with the extra elements that don't fit in a power of 2 length
  613. func cutPowerOfTwo(kvs []kv) ([]kv, []kv) {
  614. x := len(kvs)
  615. if (x & (x - 1)) != 0 {
  616. p2 := highestPowerOfTwo(x)
  617. return kvs[:p2], kvs[p2:]
  618. }
  619. return kvs, nil
  620. }
  621. func highestPowerOfTwo(n int) int {
  622. res := 0
  623. for i := n; i >= 1; i-- {
  624. if (i & (i - 1)) == 0 {
  625. res = i
  626. break
  627. }
  628. }
  629. return res
  630. }
  631. // combineInKVSet combines two kv array in one single array without repeated
  632. // keys.
  633. func combineInKVSet(base, toAdd []kv) ([]kv, []int) {
  634. // TODO this is a naive version, this will be implemented in a more
  635. // efficient way or through maps, or through sorted binary search
  636. r := base
  637. var invalids []int
  638. for i := 0; i < len(toAdd); i++ {
  639. e := false
  640. // check if toAdd[i] exists in the base set
  641. for j := 0; j < len(base); j++ {
  642. if bytes.Equal(toAdd[i].k, base[j].k) {
  643. e = true
  644. }
  645. }
  646. if !e {
  647. r = append(r, toAdd[i])
  648. } else {
  649. invalids = append(invalids, toAdd[i].pos)
  650. }
  651. }
  652. return r, invalids
  653. }
  654. // func computeSimpleAddCost(nLeafs int) int {
  655. // // nLvls 2^nLvls
  656. // nLvls := int(math.Log2(float64(nLeafs)))
  657. // return nLvls * int(math.Pow(2, float64(nLvls)))
  658. // }
  659. //
  660. // func computeBottomUpAddCost(nLeafs int) int {
  661. // // 2^nLvls * 2 - 1
  662. // nLvls := int(math.Log2(float64(nLeafs)))
  663. // return (int(math.Pow(2, float64(nLvls))) * 2) - 1
  664. // }