DS_BPlusTree.h 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. /// \file DS_BPlusTree.h
  11. ///
  12. #ifndef __B_PLUS_TREE_CPP
  13. #define __B_PLUS_TREE_CPP
  14. #include "DS_MemoryPool.h"
  15. #include "DS_Queue.h"
  16. #include <stdio.h>
  17. #include "Export.h"
  18. // Java
  19. // http://www.seanster.com/BplusTree/BplusTree.html
  20. // Overview
  21. // http://babbage.clarku.edu/~achou/cs160/B+Trees/B+Trees.htm
  22. // Deletion
  23. // http://dbpubs.stanford.edu:8090/pub/1995-19
  24. #ifdef _MSC_VER
  25. #pragma warning( push )
  26. #endif
  27. #include "RakMemoryOverride.h"
  28. /// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures
  29. /// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish.
  30. namespace DataStructures
  31. {
  32. /// Used in the BPlusTree. Used for both leaf and index nodes.
  33. /// Don't use a constructor or destructor, due to the memory pool I am using
  34. template <class KeyType, class DataType, int order>
  35. struct RAK_DLL_EXPORT Page
  36. {
  37. // We use the same data structure for both leaf and index nodes.
  38. // It uses a little more memory for index nodes but reduces
  39. // memory fragmentation, allocations, and deallocations.
  40. bool isLeaf;
  41. // Used for both leaf and index nodes.
  42. // For a leaf it means the number of elements in data
  43. // For an index it means the number of keys and is one less than the number of children pointers.
  44. int size;
  45. // Used for both leaf and index nodes.
  46. KeyType keys[order];
  47. // Used only for leaf nodes. Data is the actual data, while next is the pointer to the next leaf (for B+)
  48. DataType data[order];
  49. Page<KeyType, DataType, order> *next;
  50. Page<KeyType, DataType, order> *previous;
  51. // Used only for index nodes. Pointers to the children of this node.
  52. Page *children[order+1];
  53. };
  54. /// A BPlus tree
  55. /// Written with efficiency and speed in mind.
  56. template <class KeyType, class DataType, int order>
  57. class RAK_DLL_EXPORT BPlusTree
  58. {
  59. public:
  60. struct ReturnAction
  61. {
  62. KeyType key1;
  63. KeyType key2;
  64. enum
  65. {
  66. NO_ACTION,
  67. REPLACE_KEY1_WITH_KEY2,
  68. PUSH_KEY_TO_PARENT,
  69. SET_BRANCH_KEY,
  70. } action; // 0=none, 1=replace key1 with key2
  71. };
  72. BPlusTree();
  73. ~BPlusTree();
  74. void SetPoolPageSize(int size); // Set the page size for the memory pool. Optionsl
  75. bool Get(const KeyType key, DataType &out) const;
  76. bool Delete(const KeyType key);
  77. bool Delete(const KeyType key, DataType &out);
  78. bool Insert(const KeyType key, const DataType &data);
  79. void Clear(void);
  80. unsigned Size(void) const;
  81. bool IsEmpty(void) const;
  82. Page<KeyType, DataType, order> *GetListHead(void) const;
  83. DataType GetDataHead(void) const;
  84. void PrintLeaves(void);
  85. void ForEachLeaf(void (*func)(Page<KeyType, DataType, order> * leaf, int index));
  86. void ForEachData(void (*func)(DataType input, int index));
  87. void PrintGraph(void);
  88. protected:
  89. void ValidateTreeRecursive(Page<KeyType, DataType, order> *cur);
  90. void DeleteFromPageAtIndex(const int index, Page<KeyType, DataType, order> *cur);
  91. static void PrintLeaf(Page<KeyType, DataType, order> * leaf, int index);
  92. void FreePages(void);
  93. bool GetIndexOf(const KeyType key, Page<KeyType, DataType, order> *page, int *out) const;
  94. void ShiftKeysLeft(Page<KeyType, DataType, order> *cur);
  95. bool CanRotateLeft(Page<KeyType, DataType, order> *cur, int childIndex);
  96. bool CanRotateRight(Page<KeyType, DataType, order> *cur, int childIndex);
  97. void RotateRight(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction);
  98. void RotateLeft(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction);
  99. Page<KeyType, DataType, order>* InsertIntoNode(const KeyType key, const DataType &childData, int insertionIndex, Page<KeyType, DataType, order> *nodeData, Page<KeyType, DataType, order> *cur, ReturnAction* returnAction);
  100. Page<KeyType, DataType, order>* InsertBranchDown(const KeyType key, const DataType &data,Page<KeyType, DataType, order> *cur, ReturnAction* returnAction, bool *success);
  101. Page<KeyType, DataType, order>* GetLeafFromKey(const KeyType key) const;
  102. bool FindDeleteRebalance(const KeyType key, Page<KeyType, DataType, order> *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out);
  103. bool FixUnderflow(int branchIndex, Page<KeyType, DataType, order> *cur, KeyType rightRootKey, ReturnAction *returnAction);
  104. void ShiftNodeLeft(Page<KeyType, DataType, order> *cur);
  105. void ShiftNodeRight(Page<KeyType, DataType, order> *cur);
  106. MemoryPool<Page<KeyType, DataType, order> > pagePool;
  107. Page<KeyType, DataType, order> *root, *leftmostLeaf;
  108. };
  109. template<class KeyType, class DataType, int order>
  110. BPlusTree<KeyType, DataType, order>::BPlusTree ()
  111. {
  112. RakAssert(order>1);
  113. root=0;
  114. leftmostLeaf=0;
  115. }
  116. template<class KeyType, class DataType, int order>
  117. BPlusTree<KeyType, DataType, order>::~BPlusTree ()
  118. {
  119. Clear();
  120. }
  121. template<class KeyType, class DataType, int order>
  122. void BPlusTree<KeyType, DataType, order>::SetPoolPageSize(int size)
  123. {
  124. pagePool.SetPageSize(size);
  125. }
  126. template<class KeyType, class DataType, int order>
  127. bool BPlusTree<KeyType, DataType, order>::Get(const KeyType key, DataType &out) const
  128. {
  129. if (root==0)
  130. return false;
  131. Page<KeyType, DataType, order>* leaf = GetLeafFromKey(key);
  132. int childIndex;
  133. if (GetIndexOf(key, leaf, &childIndex))
  134. {
  135. out=leaf->data[childIndex];
  136. return true;
  137. }
  138. return false;
  139. }
  140. template<class KeyType, class DataType, int order>
  141. void BPlusTree<KeyType, DataType, order>::DeleteFromPageAtIndex(const int index, Page<KeyType, DataType, order> *cur)
  142. {
  143. int i;
  144. for (i=index; i < cur->size-1; i++)
  145. cur->keys[i]=cur->keys[i+1];
  146. if (cur->isLeaf)
  147. {
  148. for (i=index; i < cur->size-1; i++)
  149. cur->data[i]=cur->data[i+1];
  150. }
  151. else
  152. {
  153. for (i=index; i < cur->size-1; i++)
  154. cur->children[i+1]=cur->children[i+2];
  155. }
  156. cur->size--;
  157. }
  158. template<class KeyType, class DataType, int order>
  159. bool BPlusTree<KeyType, DataType, order>::Delete(const KeyType key)
  160. {
  161. DataType temp;
  162. return Delete(key, temp);
  163. }
  164. template<class KeyType, class DataType, int order>
  165. bool BPlusTree<KeyType, DataType, order>::Delete(const KeyType key, DataType &out)
  166. {
  167. if (root==0)
  168. return false;
  169. ReturnAction returnAction;
  170. returnAction.action=ReturnAction::NO_ACTION;
  171. int childIndex;
  172. bool underflow=false;
  173. if (root==leftmostLeaf)
  174. {
  175. if (GetIndexOf(key, root, &childIndex)==false)
  176. return false;
  177. out=root->data[childIndex];
  178. DeleteFromPageAtIndex(childIndex,root);
  179. if (root->size==0)
  180. {
  181. pagePool.Release(root, _FILE_AND_LINE_);
  182. root=0;
  183. leftmostLeaf=0;
  184. }
  185. return true;
  186. }
  187. else if (FindDeleteRebalance(key, root, &underflow,root->keys[0], &returnAction, out)==false)
  188. return false;
  189. // RakAssert(returnAction.action==ReturnAction::NO_ACTION);
  190. if (underflow && root->size==0)
  191. {
  192. // Move the root down.
  193. Page<KeyType, DataType, order> *oldRoot=root;
  194. root=root->children[0];
  195. pagePool.Release(oldRoot, _FILE_AND_LINE_);
  196. // memset(oldRoot,0,sizeof(root));
  197. }
  198. return true;
  199. }
  200. template<class KeyType, class DataType, int order>
  201. bool BPlusTree<KeyType, DataType, order>::FindDeleteRebalance(const KeyType key, Page<KeyType, DataType, order> *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out)
  202. {
  203. // Get index of child to follow.
  204. int branchIndex, childIndex;
  205. if (GetIndexOf(key, cur, &childIndex))
  206. branchIndex=childIndex+1;
  207. else
  208. branchIndex=childIndex;
  209. // If child is not a leaf, call recursively
  210. if (cur->children[branchIndex]->isLeaf==false)
  211. {
  212. if (branchIndex<cur->size)
  213. rightRootKey=cur->keys[branchIndex]; // Shift right to left
  214. else
  215. rightRootKey=cur->keys[branchIndex-1]; // Shift center to left
  216. if (FindDeleteRebalance(key, cur->children[branchIndex], underflow, rightRootKey, returnAction, out)==false)
  217. return false;
  218. // Call again in case the root key changed
  219. if (branchIndex<cur->size)
  220. rightRootKey=cur->keys[branchIndex]; // Shift right to left
  221. else
  222. rightRootKey=cur->keys[branchIndex-1]; // Shift center to left
  223. if (returnAction->action==ReturnAction::SET_BRANCH_KEY && branchIndex!=childIndex)
  224. {
  225. returnAction->action=ReturnAction::NO_ACTION;
  226. cur->keys[childIndex]=returnAction->key1;
  227. if (branchIndex<cur->size)
  228. rightRootKey=cur->keys[branchIndex]; // Shift right to left
  229. else
  230. rightRootKey=cur->keys[branchIndex-1]; // Shift center to left
  231. }
  232. }
  233. else
  234. {
  235. // If child is a leaf, get the index of the key. If the item is not found, cancel delete.
  236. if (GetIndexOf(key, cur->children[branchIndex], &childIndex)==false)
  237. return false;
  238. // Delete:
  239. // Remove childIndex from the child at branchIndex
  240. out=cur->children[branchIndex]->data[childIndex];
  241. DeleteFromPageAtIndex(childIndex, cur->children[branchIndex]);
  242. if (childIndex==0)
  243. {
  244. if (branchIndex>0)
  245. cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0];
  246. if (branchIndex==0)
  247. {
  248. returnAction->action=ReturnAction::SET_BRANCH_KEY;
  249. returnAction->key1=cur->children[0]->keys[0];
  250. }
  251. }
  252. if (cur->children[branchIndex]->size < order/2)
  253. *underflow=true;
  254. else
  255. *underflow=false;
  256. }
  257. // Fix underflow:
  258. if (*underflow)
  259. {
  260. *underflow=FixUnderflow(branchIndex, cur, rightRootKey, returnAction);
  261. }
  262. return true;
  263. }
  264. template<class KeyType, class DataType, int order>
  265. bool BPlusTree<KeyType, DataType, order>::FixUnderflow(int branchIndex, Page<KeyType, DataType, order> *cur, KeyType rightRootKey, ReturnAction *returnAction)
  266. {
  267. // Borrow from a neighbor that has excess.
  268. Page<KeyType, DataType, order> *source;
  269. Page<KeyType, DataType, order> *dest;
  270. if (branchIndex>0 && cur->children[branchIndex-1]->size > order/2)
  271. {
  272. dest=cur->children[branchIndex];
  273. source=cur->children[branchIndex-1];
  274. // Left has excess
  275. ShiftNodeRight(dest);
  276. if (dest->isLeaf)
  277. {
  278. dest->keys[0]=source->keys[source->size-1];
  279. dest->data[0]=source->data[source->size-1];
  280. }
  281. else
  282. {
  283. dest->children[0]=source->children[source->size];
  284. dest->keys[0]=cur->keys[branchIndex-1];
  285. }
  286. // Update the parent key for the child (middle)
  287. cur->keys[branchIndex-1]=source->keys[source->size-1];
  288. source->size--;
  289. // if (branchIndex==0)
  290. // {
  291. // returnAction->action=ReturnAction::SET_BRANCH_KEY;
  292. // returnAction->key1=dest->keys[0];
  293. // }
  294. // No underflow
  295. return false;
  296. }
  297. else if (branchIndex<cur->size && cur->children[branchIndex+1]->size > order/2)
  298. {
  299. dest=cur->children[branchIndex];
  300. source=cur->children[branchIndex+1];
  301. // Right has excess
  302. if (dest->isLeaf)
  303. {
  304. dest->keys[dest->size]=source->keys[0];
  305. dest->data[dest->size]=source->data[0];
  306. // The first key in the leaf after shifting is the parent key for the right branch
  307. cur->keys[branchIndex]=source->keys[1];
  308. #ifdef _MSC_VER
  309. #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant
  310. #endif
  311. if (order<=3 && dest->size==0)
  312. {
  313. if (branchIndex==0)
  314. {
  315. returnAction->action=ReturnAction::SET_BRANCH_KEY;
  316. returnAction->key1=dest->keys[0];
  317. }
  318. else
  319. cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0];
  320. }
  321. }
  322. else
  323. {
  324. if (returnAction->action==ReturnAction::NO_ACTION)
  325. {
  326. returnAction->action=ReturnAction::SET_BRANCH_KEY;
  327. returnAction->key1=dest->keys[0];
  328. }
  329. dest->keys[dest->size]=rightRootKey;
  330. dest->children[dest->size+1]=source->children[0];
  331. // The shifted off key is the leftmost key for a node
  332. cur->keys[branchIndex]=source->keys[0];
  333. }
  334. dest->size++;
  335. ShiftNodeLeft(source);
  336. //cur->keys[branchIndex]=source->keys[0];
  337. // returnAction->action=ReturnAction::SET_BRANCH_KEY;
  338. // returnAction->key1=dest->keys[dest->size-1];
  339. // No underflow
  340. return false;
  341. }
  342. else
  343. {
  344. int sourceIndex;
  345. // If no neighbors have excess, merge two branches.
  346. //
  347. // To merge two leaves, just copy the data and keys over.
  348. //
  349. // To merge two branches, copy the pointers and keys over, using rightRootKey as the key for the extra pointer
  350. if (branchIndex<cur->size)
  351. {
  352. // Merge right child to current child and delete right child.
  353. dest=cur->children[branchIndex];
  354. source=cur->children[branchIndex+1];
  355. }
  356. else
  357. {
  358. // Move current child to left and delete current child
  359. dest=cur->children[branchIndex-1];
  360. source=cur->children[branchIndex];
  361. }
  362. // Merge
  363. if (dest->isLeaf)
  364. {
  365. for (sourceIndex=0; sourceIndex<source->size; sourceIndex++)
  366. {
  367. dest->keys[dest->size]=source->keys[sourceIndex];
  368. dest->data[dest->size++]=source->data[sourceIndex];
  369. }
  370. }
  371. else
  372. {
  373. // We want the tree root key of the source, not the current.
  374. dest->keys[dest->size]=rightRootKey;
  375. dest->children[dest->size++ + 1]=source->children[0];
  376. for (sourceIndex=0; sourceIndex<source->size; sourceIndex++)
  377. {
  378. dest->keys[dest->size]=source->keys[sourceIndex];
  379. dest->children[dest->size++ + 1]=source->children[sourceIndex + 1];
  380. }
  381. }
  382. #ifdef _MSC_VER
  383. #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant
  384. #endif
  385. if (order<=3 && branchIndex>0 && cur->children[branchIndex]->isLeaf) // With order==2 it is possible to delete data[0], which is not possible with higher orders.
  386. cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0];
  387. if (branchIndex<cur->size)
  388. {
  389. // Update the parent key, removing the source (right)
  390. DeleteFromPageAtIndex(branchIndex, cur);
  391. }
  392. else
  393. {
  394. if (branchIndex>0)
  395. {
  396. // Update parent key, removing the source (current)
  397. DeleteFromPageAtIndex(branchIndex-1, cur);
  398. }
  399. }
  400. if (branchIndex==0 && dest->isLeaf)
  401. {
  402. returnAction->action=ReturnAction::SET_BRANCH_KEY;
  403. returnAction->key1=dest->keys[0];
  404. }
  405. if (source==leftmostLeaf)
  406. leftmostLeaf=source->next;
  407. if (source->isLeaf)
  408. {
  409. if (source->previous)
  410. source->previous->next=source->next;
  411. if (source->next)
  412. source->next->previous=source->previous;
  413. }
  414. // Free the source node
  415. pagePool.Release(source, _FILE_AND_LINE_);
  416. // memset(source,0,sizeof(root));
  417. // Return underflow or not of parent.
  418. return cur->size < order/2;
  419. }
  420. }
  421. template<class KeyType, class DataType, int order>
  422. void BPlusTree<KeyType, DataType, order>::ShiftNodeRight(Page<KeyType, DataType, order> *cur)
  423. {
  424. int i;
  425. for (i=cur->size; i>0; i--)
  426. cur->keys[i]=cur->keys[i-1];
  427. if (cur->isLeaf)
  428. {
  429. for (i=cur->size; i>0; i--)
  430. cur->data[i]=cur->data[i-1];
  431. }
  432. else
  433. {
  434. for (i=cur->size+1; i>0; i--)
  435. cur->children[i]=cur->children[i-1];
  436. }
  437. cur->size++;
  438. }
  439. template<class KeyType, class DataType, int order>
  440. void BPlusTree<KeyType, DataType, order>::ShiftNodeLeft(Page<KeyType, DataType, order> *cur)
  441. {
  442. int i;
  443. for (i=0; i < cur->size-1; i++)
  444. cur->keys[i]=cur->keys[i+1];
  445. if (cur->isLeaf)
  446. {
  447. for (i=0; i < cur->size; i++)
  448. cur->data[i]=cur->data[i+1];
  449. }
  450. else
  451. {
  452. for (i=0; i < cur->size; i++)
  453. cur->children[i]=cur->children[i+1];
  454. }
  455. cur->size--;
  456. }
  457. template<class KeyType, class DataType, int order>
  458. Page<KeyType, DataType, order>* BPlusTree<KeyType, DataType, order>::InsertIntoNode(const KeyType key, const DataType &leafData, int insertionIndex, Page<KeyType, DataType, order> *nodeData, Page<KeyType, DataType, order> *cur, ReturnAction* returnAction)
  459. {
  460. int i;
  461. if (cur->size < order)
  462. {
  463. for (i=cur->size; i > insertionIndex; i--)
  464. cur->keys[i]=cur->keys[i-1];
  465. if (cur->isLeaf)
  466. {
  467. for (i=cur->size; i > insertionIndex; i--)
  468. cur->data[i]=cur->data[i-1];
  469. }
  470. else
  471. {
  472. for (i=cur->size+1; i > insertionIndex+1; i--)
  473. cur->children[i]=cur->children[i-1];
  474. }
  475. cur->keys[insertionIndex]=key;
  476. if (cur->isLeaf)
  477. cur->data[insertionIndex]=leafData;
  478. else
  479. cur->children[insertionIndex+1]=nodeData;
  480. cur->size++;
  481. }
  482. else
  483. {
  484. Page<KeyType, DataType, order>* newPage = pagePool.Allocate( _FILE_AND_LINE_ );
  485. newPage->isLeaf=cur->isLeaf;
  486. if (cur->isLeaf)
  487. {
  488. newPage->next=cur->next;
  489. if (cur->next)
  490. cur->next->previous=newPage;
  491. newPage->previous=cur;
  492. cur->next=newPage;
  493. }
  494. int destIndex, sourceIndex;
  495. if (insertionIndex>=(order+1)/2)
  496. {
  497. destIndex=0;
  498. sourceIndex=order/2;
  499. for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++)
  500. {
  501. newPage->keys[destIndex]=cur->keys[sourceIndex];
  502. }
  503. newPage->keys[destIndex++]=key;
  504. for (; sourceIndex < order; sourceIndex++, destIndex++)
  505. {
  506. newPage->keys[destIndex]=cur->keys[sourceIndex];
  507. }
  508. destIndex=0;
  509. sourceIndex=order/2;
  510. if (cur->isLeaf)
  511. {
  512. for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++)
  513. {
  514. newPage->data[destIndex]=cur->data[sourceIndex];
  515. }
  516. newPage->data[destIndex++]=leafData;
  517. for (; sourceIndex < order; sourceIndex++, destIndex++)
  518. {
  519. newPage->data[destIndex]=cur->data[sourceIndex];
  520. }
  521. }
  522. else
  523. {
  524. for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++)
  525. {
  526. newPage->children[destIndex]=cur->children[sourceIndex+1];
  527. }
  528. newPage->children[destIndex++]=nodeData;
  529. // sourceIndex+1 is sort of a hack but it works - because there is one extra child than keys
  530. // skip past the last child for cur
  531. for (; sourceIndex+1 < cur->size+1; sourceIndex++, destIndex++)
  532. {
  533. newPage->children[destIndex]=cur->children[sourceIndex+1];
  534. }
  535. // the first key is the middle key. Remove it from the page and push it to the parent
  536. returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT;
  537. returnAction->key1=newPage->keys[0];
  538. for (int j=0; j < destIndex-1; j++)
  539. newPage->keys[j]=newPage->keys[j+1];
  540. }
  541. cur->size=order/2;
  542. }
  543. else
  544. {
  545. destIndex=0;
  546. sourceIndex=(order+1)/2-1;
  547. for (; sourceIndex < order; sourceIndex++, destIndex++)
  548. newPage->keys[destIndex]=cur->keys[sourceIndex];
  549. destIndex=0;
  550. if (cur->isLeaf)
  551. {
  552. sourceIndex=(order+1)/2-1;
  553. for (; sourceIndex < order; sourceIndex++, destIndex++)
  554. newPage->data[destIndex]=cur->data[sourceIndex];
  555. }
  556. else
  557. {
  558. sourceIndex=(order+1)/2;
  559. for (; sourceIndex < order+1; sourceIndex++, destIndex++)
  560. newPage->children[destIndex]=cur->children[sourceIndex];
  561. // the first key is the middle key. Remove it from the page and push it to the parent
  562. returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT;
  563. returnAction->key1=newPage->keys[0];
  564. for (int j=0; j < destIndex-1; j++)
  565. newPage->keys[j]=newPage->keys[j+1];
  566. }
  567. cur->size=(order+1)/2-1;
  568. if (cur->size)
  569. {
  570. bool b = GetIndexOf(key, cur, &insertionIndex);
  571. (void) b;
  572. RakAssert(b==false);
  573. }
  574. else
  575. insertionIndex=0;
  576. InsertIntoNode(key, leafData, insertionIndex, nodeData, cur, returnAction);
  577. }
  578. newPage->size=destIndex;
  579. return newPage;
  580. }
  581. return 0;
  582. }
  583. template<class KeyType, class DataType, int order>
  584. bool BPlusTree<KeyType, DataType, order>::CanRotateLeft(Page<KeyType, DataType, order> *cur, int childIndex)
  585. {
  586. return childIndex>0 && cur->children[childIndex-1]->size<order;
  587. }
  588. template<class KeyType, class DataType, int order>
  589. void BPlusTree<KeyType, DataType, order>::RotateLeft(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction)
  590. {
  591. Page<KeyType, DataType, order> *dest = cur->children[childIndex-1];
  592. Page<KeyType, DataType, order> *source = cur->children[childIndex];
  593. returnAction->key1=source->keys[0];
  594. dest->keys[dest->size]=source->keys[0];
  595. dest->data[dest->size]=source->data[0];
  596. dest->size++;
  597. for (int i=0; i < source->size-1; i++)
  598. {
  599. source->keys[i]=source->keys[i+1];
  600. source->data[i]=source->data[i+1];
  601. }
  602. source->size--;
  603. cur->keys[childIndex-1]=source->keys[0];
  604. returnAction->key2=source->keys[0];
  605. }
  606. template<class KeyType, class DataType, int order>
  607. bool BPlusTree<KeyType, DataType, order>::CanRotateRight(Page<KeyType, DataType, order> *cur, int childIndex)
  608. {
  609. return childIndex < cur->size && cur->children[childIndex+1]->size<order;
  610. }
  611. template<class KeyType, class DataType, int order>
  612. void BPlusTree<KeyType, DataType, order>::RotateRight(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction)
  613. {
  614. Page<KeyType, DataType, order> *dest = cur->children[childIndex+1];
  615. Page<KeyType, DataType, order> *source = cur->children[childIndex];
  616. returnAction->key1=dest->keys[0];
  617. for (int i= dest->size; i > 0; i--)
  618. {
  619. dest->keys[i]=dest->keys[i-1];
  620. dest->data[i]=dest->data[i-1];
  621. }
  622. dest->keys[0]=source->keys[source->size-1];
  623. dest->data[0]=source->data[source->size-1];
  624. dest->size++;
  625. source->size--;
  626. cur->keys[childIndex]=dest->keys[0];
  627. returnAction->key2=dest->keys[0];
  628. }
  629. template<class KeyType, class DataType, int order>
  630. Page<KeyType, DataType, order>* BPlusTree<KeyType, DataType, order>::GetLeafFromKey(const KeyType key) const
  631. {
  632. Page<KeyType, DataType, order>* cur = root;
  633. int childIndex;
  634. while (cur->isLeaf==false)
  635. {
  636. // When searching, if we match the exact key we go down the pointer after that index
  637. if (GetIndexOf(key, cur, &childIndex))
  638. childIndex++;
  639. cur = cur->children[childIndex];
  640. }
  641. return cur;
  642. }
  643. template<class KeyType, class DataType, int order>
  644. Page<KeyType, DataType, order>* BPlusTree<KeyType, DataType, order>::InsertBranchDown(const KeyType key, const DataType &data,Page<KeyType, DataType, order> *cur, ReturnAction *returnAction, bool *success)
  645. {
  646. int childIndex;
  647. int branchIndex;
  648. if (GetIndexOf(key, cur, &childIndex))
  649. branchIndex=childIndex+1;
  650. else
  651. branchIndex=childIndex;
  652. Page<KeyType, DataType, order>* newPage;
  653. if (cur->isLeaf==false)
  654. {
  655. if (cur->children[branchIndex]->isLeaf==true && cur->children[branchIndex]->size==order)
  656. {
  657. if (branchIndex==childIndex+1)
  658. {
  659. *success=false;
  660. return 0; // Already exists
  661. }
  662. if (CanRotateLeft(cur, branchIndex))
  663. {
  664. returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2;
  665. if (key > cur->children[branchIndex]->keys[0])
  666. {
  667. RotateLeft(cur, branchIndex, returnAction);
  668. int insertionIndex;
  669. GetIndexOf(key, cur->children[branchIndex], &insertionIndex);
  670. InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0);
  671. }
  672. else
  673. {
  674. // Move head element to left and replace it with key,data
  675. Page<KeyType, DataType, order>* dest=cur->children[branchIndex-1];
  676. Page<KeyType, DataType, order>* source=cur->children[branchIndex];
  677. returnAction->key1=source->keys[0];
  678. returnAction->key2=key;
  679. dest->keys[dest->size]=source->keys[0];
  680. dest->data[dest->size]=source->data[0];
  681. dest->size++;
  682. source->keys[0]=key;
  683. source->data[0]=data;
  684. }
  685. cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0];
  686. return 0;
  687. }
  688. else if (CanRotateRight(cur, branchIndex))
  689. {
  690. returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2;
  691. if (key < cur->children[branchIndex]->keys[cur->children[branchIndex]->size-1])
  692. {
  693. RotateRight(cur, branchIndex, returnAction);
  694. int insertionIndex;
  695. GetIndexOf(key, cur->children[branchIndex], &insertionIndex);
  696. InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0);
  697. }
  698. else
  699. {
  700. // Insert to the head of the right leaf instead and change our key
  701. returnAction->key1=cur->children[branchIndex+1]->keys[0];
  702. InsertIntoNode(key, data, 0, 0, cur->children[branchIndex+1], 0);
  703. returnAction->key2=key;
  704. }
  705. cur->keys[branchIndex]=cur->children[branchIndex+1]->keys[0];
  706. return 0;
  707. }
  708. }
  709. newPage=InsertBranchDown(key,data,cur->children[branchIndex], returnAction, success);
  710. if (returnAction->action==ReturnAction::REPLACE_KEY1_WITH_KEY2)
  711. {
  712. if (branchIndex>0 && cur->keys[branchIndex-1]==returnAction->key1)
  713. cur->keys[branchIndex-1]=returnAction->key2;
  714. }
  715. if (newPage)
  716. {
  717. if (newPage->isLeaf==false)
  718. {
  719. RakAssert(returnAction->action==ReturnAction::PUSH_KEY_TO_PARENT);
  720. newPage->size--;
  721. return InsertIntoNode(returnAction->key1, data, branchIndex, newPage, cur, returnAction);
  722. }
  723. else
  724. {
  725. return InsertIntoNode(newPage->keys[0], data, branchIndex, newPage, cur, returnAction);
  726. }
  727. }
  728. }
  729. else
  730. {
  731. if (branchIndex==childIndex+1)
  732. {
  733. *success=false;
  734. return 0; // Already exists
  735. }
  736. else
  737. {
  738. return InsertIntoNode(key, data, branchIndex, 0, cur, returnAction);
  739. }
  740. }
  741. return 0;
  742. }
  743. template<class KeyType, class DataType, int order>
  744. bool BPlusTree<KeyType, DataType, order>::Insert(const KeyType key, const DataType &data)
  745. {
  746. if (root==0)
  747. {
  748. // Allocate root and make root a leaf
  749. root = pagePool.Allocate( _FILE_AND_LINE_ );
  750. root->isLeaf=true;
  751. leftmostLeaf=root;
  752. root->size=1;
  753. root->keys[0]=key;
  754. root->data[0]=data;
  755. root->next=0;
  756. root->previous=0;
  757. }
  758. else
  759. {
  760. bool success=true;
  761. ReturnAction returnAction;
  762. returnAction.action=ReturnAction::NO_ACTION;
  763. Page<KeyType, DataType, order>* newPage = InsertBranchDown(key, data, root, &returnAction, &success);
  764. if (success==false)
  765. return false;
  766. if (newPage)
  767. {
  768. KeyType newKey;
  769. if (newPage->isLeaf==false)
  770. {
  771. // One key is pushed up through the stack. I store that at keys[0] but it has to be removed for the page to be correct
  772. RakAssert(returnAction.action==ReturnAction::PUSH_KEY_TO_PARENT);
  773. newKey=returnAction.key1;
  774. newPage->size--;
  775. }
  776. else
  777. newKey = newPage->keys[0];
  778. // propagate the root
  779. Page<KeyType, DataType, order>* newRoot = pagePool.Allocate( _FILE_AND_LINE_ );
  780. newRoot->isLeaf=false;
  781. newRoot->size=1;
  782. newRoot->keys[0]=newKey;
  783. newRoot->children[0]=root;
  784. newRoot->children[1]=newPage;
  785. root=newRoot;
  786. }
  787. }
  788. return true;
  789. }
  790. template<class KeyType, class DataType, int order>
  791. void BPlusTree<KeyType, DataType, order>::ShiftKeysLeft(Page<KeyType, DataType, order> *cur)
  792. {
  793. int i;
  794. for (i=0; i < cur->size; i++)
  795. cur->keys[i]=cur->keys[i+1];
  796. }
  797. template<class KeyType, class DataType, int order>
  798. void BPlusTree<KeyType, DataType, order>::Clear(void)
  799. {
  800. if (root)
  801. {
  802. FreePages();
  803. leftmostLeaf=0;
  804. root=0;
  805. }
  806. pagePool.Clear(_FILE_AND_LINE_);
  807. }
  808. template<class KeyType, class DataType, int order>
  809. unsigned BPlusTree<KeyType, DataType, order>::Size(void) const
  810. {
  811. unsigned int count=0;
  812. DataStructures::Page<KeyType, DataType, order> *cur = GetListHead();
  813. while (cur)
  814. {
  815. count+=cur->size;
  816. cur=cur->next;
  817. }
  818. return count;
  819. }
  820. template<class KeyType, class DataType, int order>
  821. bool BPlusTree<KeyType, DataType, order>::IsEmpty(void) const
  822. {
  823. return root==0;
  824. }
  825. template<class KeyType, class DataType, int order>
  826. bool BPlusTree<KeyType, DataType, order>::GetIndexOf(const KeyType key, Page<KeyType, DataType, order> *page, int *out) const
  827. {
  828. RakAssert(page->size>0);
  829. int index, upperBound, lowerBound;
  830. upperBound=page->size-1;
  831. lowerBound=0;
  832. index = page->size/2;
  833. #ifdef _MSC_VER
  834. #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant
  835. #endif
  836. while (1)
  837. {
  838. if (key==page->keys[index])
  839. {
  840. *out=index;
  841. return true;
  842. }
  843. else if (key<page->keys[index])
  844. upperBound=index-1;
  845. else
  846. lowerBound=index+1;
  847. index=lowerBound+(upperBound-lowerBound)/2;
  848. if (lowerBound>upperBound)
  849. {
  850. *out=lowerBound;
  851. return false; // No match
  852. }
  853. }
  854. }
  855. template<class KeyType, class DataType, int order>
  856. void BPlusTree<KeyType, DataType, order>::FreePages(void)
  857. {
  858. DataStructures::Queue<DataStructures::Page<KeyType, DataType, order> *> queue;
  859. DataStructures::Page<KeyType, DataType, order> *ptr;
  860. int i;
  861. queue.Push(root, _FILE_AND_LINE_ );
  862. while (queue.Size())
  863. {
  864. ptr=queue.Pop();
  865. if (ptr->isLeaf==false)
  866. {
  867. for (i=0; i < ptr->size+1; i++)
  868. queue.Push(ptr->children[i], _FILE_AND_LINE_ );
  869. }
  870. pagePool.Release(ptr, _FILE_AND_LINE_);
  871. // memset(ptr,0,sizeof(root));
  872. };
  873. }
  874. template<class KeyType, class DataType, int order>
  875. Page<KeyType, DataType, order> *BPlusTree<KeyType, DataType, order>::GetListHead(void) const
  876. {
  877. return leftmostLeaf;
  878. }
  879. template<class KeyType, class DataType, int order>
  880. DataType BPlusTree<KeyType, DataType, order>::GetDataHead(void) const
  881. {
  882. return leftmostLeaf->data[0];
  883. }
  884. template<class KeyType, class DataType, int order>
  885. void BPlusTree<KeyType, DataType, order>::ForEachLeaf(void (*func)(Page<KeyType, DataType, order> * leaf, int index))
  886. {
  887. int count=0;
  888. DataStructures::Page<KeyType, DataType, order> *cur = GetListHead();
  889. while (cur)
  890. {
  891. func(cur, count++);
  892. cur=cur->next;
  893. }
  894. }
  895. template<class KeyType, class DataType, int order>
  896. void BPlusTree<KeyType, DataType, order>::ForEachData(void (*func)(DataType input, int index))
  897. {
  898. int count=0,i;
  899. DataStructures::Page<KeyType, DataType, order> *cur = GetListHead();
  900. while (cur)
  901. {
  902. for (i=0; i < cur->size; i++)
  903. func(cur->data[i], count++);
  904. cur=cur->next;
  905. }
  906. }
  907. template<class KeyType, class DataType, int order>
  908. void BPlusTree<KeyType, DataType, order>::PrintLeaf(Page<KeyType, DataType, order> * leaf, int index)
  909. {
  910. int i;
  911. RAKNET_DEBUG_PRINTF("%i] SELF=%p\n", index+1, leaf);
  912. for (i=0; i < leaf->size; i++)
  913. RAKNET_DEBUG_PRINTF(" %i. %i\n", i+1, leaf->data[i]);
  914. }
  915. template<class KeyType, class DataType, int order>
  916. void BPlusTree<KeyType, DataType, order>::PrintLeaves(void)
  917. {
  918. ForEachLeaf(PrintLeaf);
  919. }
  920. template<class KeyType, class DataType, int order>
  921. void BPlusTree<KeyType, DataType, order>::ValidateTreeRecursive(Page<KeyType, DataType, order> *cur)
  922. {
  923. RakAssert(cur==root || cur->size>=order/2);
  924. if (cur->children[0]->isLeaf)
  925. {
  926. RakAssert(cur->children[0]->keys[0] < cur->keys[0]);
  927. for (int i=0; i < cur->size; i++)
  928. {
  929. RakAssert(cur->children[i+1]->keys[0]==cur->keys[i]);
  930. }
  931. }
  932. else
  933. {
  934. for (int i=0; i < cur->size+1; i++)
  935. ValidateTreeRecursive(cur->children[i]);
  936. }
  937. }
  938. template<class KeyType, class DataType, int order>
  939. void BPlusTree<KeyType, DataType, order>::PrintGraph(void)
  940. {
  941. DataStructures::Queue<DataStructures::Page<KeyType, DataType, order> *> queue;
  942. queue.Push(root,_FILE_AND_LINE_);
  943. queue.Push(0,_FILE_AND_LINE_);
  944. DataStructures::Page<KeyType, DataType, order> *ptr;
  945. int i,j;
  946. if (root)
  947. {
  948. RAKNET_DEBUG_PRINTF("%p(", root);
  949. for (i=0; i < root->size; i++)
  950. {
  951. RAKNET_DEBUG_PRINTF("%i ", root->keys[i]);
  952. }
  953. RAKNET_DEBUG_PRINTF(") ");
  954. RAKNET_DEBUG_PRINTF("\n");
  955. }
  956. while (queue.Size())
  957. {
  958. ptr=queue.Pop();
  959. if (ptr==0)
  960. RAKNET_DEBUG_PRINTF("\n");
  961. else if (ptr->isLeaf==false)
  962. {
  963. for (i=0; i < ptr->size+1; i++)
  964. {
  965. RAKNET_DEBUG_PRINTF("%p(", ptr->children[i]);
  966. //RAKNET_DEBUG_PRINTF("(", ptr->children[i]);
  967. for (j=0; j < ptr->children[i]->size; j++)
  968. RAKNET_DEBUG_PRINTF("%i ", ptr->children[i]->keys[j]);
  969. RAKNET_DEBUG_PRINTF(") ");
  970. queue.Push(ptr->children[i],_FILE_AND_LINE_);
  971. }
  972. queue.Push(0,_FILE_AND_LINE_);
  973. RAKNET_DEBUG_PRINTF(" -- ");
  974. }
  975. }
  976. RAKNET_DEBUG_PRINTF("\n");
  977. }
  978. }
  979. #ifdef _MSC_VER
  980. #pragma warning( pop )
  981. #endif
  982. #endif
  983. // Code to test this hellish data structure.
  984. /*
  985. #include "DS_BPlusTree.h"
  986. #include <stdio.h>
  987. // Handle underflow on root. If there is only one item left then I can go downwards.
  988. // Make sure I keep the leftmost pointer valid by traversing it
  989. // When I free a leaf, be sure to adjust the pointers around it.
  990. #include "Rand.h"
  991. void main(void)
  992. {
  993. DataStructures::BPlusTree<int, int, 16> btree;
  994. DataStructures::List<int> haveList, removedList;
  995. int temp;
  996. int i, j, index;
  997. int testSize;
  998. bool b;
  999. for (testSize=0; testSize < 514; testSize++)
  1000. {
  1001. RAKNET_DEBUG_PRINTF("TestSize=%i\n", testSize);
  1002. for (i=0; i < testSize; i++)
  1003. haveList.Insert(i);
  1004. for (i=0; i < testSize; i++)
  1005. {
  1006. index=i+randomMT()%(testSize-i);
  1007. temp=haveList[index];
  1008. haveList[index]=haveList[i];
  1009. haveList[i]=temp;
  1010. }
  1011. for (i=0; i<testSize; i++)
  1012. {
  1013. btree.Insert(haveList[i], haveList[i]);
  1014. btree.ValidateTree();
  1015. }
  1016. for (i=0; i < testSize; i++)
  1017. {
  1018. index=i+randomMT()%(testSize-i);
  1019. temp=haveList[index];
  1020. haveList[index]=haveList[i];
  1021. haveList[i]=temp;
  1022. }
  1023. for (i=0; i<testSize; i++)
  1024. {
  1025. btree.Delete(haveList[0]); // Asserts on 8th call. Fails on going to remove 8 (7th call)
  1026. removedList.Insert(haveList[0]);
  1027. haveList.RemoveAtIndex(0);
  1028. for (j=0; j < removedList.Size(); j++)
  1029. {
  1030. b=btree.Get(removedList[j], temp);
  1031. RakAssert(b==false);
  1032. }
  1033. for (j=0; j < haveList.Size(); j++)
  1034. {
  1035. b=btree.Get(haveList[j], temp);
  1036. RakAssert(b==true);
  1037. RakAssert(haveList[j]==temp);
  1038. }
  1039. RakAssert(btree.Size()==haveList.Size());
  1040. btree.ValidateTree();
  1041. }
  1042. btree.Clear(_FILE_AND_LINE_);
  1043. removedList.Clear(_FILE_AND_LINE_);
  1044. haveList.Clear(_FILE_AND_LINE_);
  1045. }
  1046. RAKNET_DEBUG_PRINTF("Done. %i\n", btree.Size());
  1047. char ch[256];
  1048. Gets(ch, sizeof(ch));
  1049. }
  1050. */
粤ICP备19079148号