summaryrefslogtreecommitdiff
path: root/plugins/Dbx_tree/src/BTree.h
blob: f1d44ccd2785ab4f47a2f26f497c4c411ea26b23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
/*

dbx_tree: tree database driver for Miranda IM

Copyright 2007-2010 Michael "Protogenes" Kunz,

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#pragma once

#include <stack>
#include "lockfree_hashmultimap.h"
#include "sigslot.h"
#include <stdint.h>

#include "Logger.h"

template <typename TKey, uint16_t SizeParam = 4>
class CBTree
{
public:
	typedef uint32_t TNodeRef; /// 32bit indices (not storing pointers)
	typedef sigslot::signal2< void *, TNodeRef > TOnRootChanged;

	#pragma pack(push, 1)  // push current alignment to stack, set alignment to 1 byte boundary

		typedef struct TNode {
			uint16_t Info;                 /// Node information (IsLeaf and stored KeyCount)
			uint16_t Signature;            /// signature
			TNodeRef Parent;               /// Handle to the parent node
			TKey Key[SizeParam * 2 - 1];   /// array with Keys
			TNodeRef Child[SizeParam * 2]; /// array with child node handles
		} TNode;

	#pragma pack(pop)

	class iterator
	{
	public:
		iterator();
		iterator(CBTree* Tree, TNodeRef Node, uint16_t Index);
		iterator(const iterator& Other);
		~iterator();

		CBTree * Tree();

		/**
			\brief Keeps track of changes in the tree and refresh the iterator
		**/
		void setManaged();
		bool wasDeleted();

		operator bool() const;
		bool operator !() const;

		const TKey & operator *();
		const TKey * operator->();


		bool operator == (iterator & Other);
		bool operator <  (iterator & Other);
		bool operator >  (iterator & Other);

		iterator& operator =(const iterator& Other);

		iterator& operator ++(); //pre  ++i
		iterator& operator --(); //pre  --i
		iterator  operator ++(int); //post i++
		iterator  operator --(int); //post i--


	protected:
		friend class CBTree;

		TNodeRef m_Node;
		uint16_t m_Index;
		CBTree* m_Tree;

		bool m_Managed;
		bool m_LoadedKey;
		TKey m_ManagedKey;
		bool m_ManagedDeleted;

		void Backup();
		void Dec();
		void Inc();
		void RemoveManaged(TNodeRef FromNode);
		void InsertManaged();
	};


	CBTree(TNodeRef RootNode = 0);
	virtual ~CBTree();

	iterator Insert(const TKey & Key);
	iterator Find(const TKey & Key);
	iterator LowerBound(const TKey & Key);
	iterator UpperBound(const TKey & Key);
	bool Delete(const TKey & Key);

	typedef sigslot::signal3<void *, const TKey &, uint32_t> TDeleteCallback;
	void DeleteTree(TDeleteCallback * CallBack, uint32_t Param);

	TNodeRef getRoot();
	void setRoot(TNodeRef NewRoot);

	TOnRootChanged & sigRootChanged() {return m_sigRootChanged;};


protected:
	static const uint16_t cIsLeafMask = 0x8000;
	static const uint16_t cKeyCountMask = 0x7FFF;
	static const uint16_t cFullNode = SizeParam * 2 - 1;
	static const uint16_t cEmptyNode = SizeParam - 1;

	typedef lockfree::hash_multimap<TNodeRef, iterator*> TManagedMap;

	TNodeRef m_Root;
	TOnRootChanged m_sigRootChanged;
	TManagedMap	m_ManagedIterators;

	bool m_DestroyTree;

	uint32_t m_AllocCount;
	uint32_t m_Count;
	uint32_t m_FreeIndex;
	TNode *  m_Alloc;

	virtual void PrepareInsertOperation();
	virtual TNode * CreateNewNode(TNodeRef & NodeRef);
	virtual void DeleteNode(TNodeRef Node);
	virtual TNode * Read(TNodeRef Node);
	virtual void Write(TNodeRef Node);

	void DestroyTree();


private:
	friend class iterator;

	bool InNodeFind(const TNode * Node, const TKey & Key, uint16_t & GreaterEqual);
	void SplitNode(TNodeRef Node, TNode * NodeData, TNodeRef & Left, TNodeRef & Right, TKey & UpKey, TNodeRef ParentNode, uint16_t ParentIndex);
	TNodeRef MergeNodes(TNodeRef Left, TNode * LeftData, TNodeRef Right, TNode * RightData, const TKey & DownKey, TNodeRef ParentNode, uint16_t ParentIndex);
	void KeyInsert(TNodeRef Node, TNode * NodeData, uint16_t Where);
	void KeyDelete(TNodeRef Node, TNode * NodeData, uint16_t Where);
	void KeyMove(TNodeRef Source, uint16_t SourceIndex, const TNode * SourceData, TNodeRef Dest, uint16_t DestIndex, TNode * DestData);
};






template <typename TKey, uint16_t SizeParam>
CBTree<TKey, SizeParam>::CBTree(TNodeRef RootNode = NULL)
: m_sigRootChanged(),
	m_ManagedIterators()
{
	m_Root = RootNode;
	m_DestroyTree = true;

	m_AllocCount = 0;
	m_Count = 0;
	m_FreeIndex = 0;
	m_Alloc = NULL;
}

template <typename TKey, uint16_t SizeParam>
CBTree<TKey, SizeParam>::~CBTree()
{
	typename TManagedMap::iterator i = m_ManagedIterators.begin();
	while (i != m_ManagedIterators.end())
	{
		i->second->m_Tree = NULL;
		++i;
	}

	if (m_DestroyTree)
		DestroyTree();
}

template <typename TKey, uint16_t SizeParam>
inline bool CBTree<TKey, SizeParam>::InNodeFind(const TNode * Node, const TKey & Key, uint16_t & GreaterEqual)
{
	uint16_t l = 0;
	uint16_t r = (Node->Info & cKeyCountMask);
	bool res = false;
	GreaterEqual = 0;
	while ((l < r) && !res)
	{
		GreaterEqual = (l + r) >> 1;
		if (Node->Key[GreaterEqual] < Key)
		{
			GreaterEqual++;
			l = GreaterEqual;
		} else if (Node->Key[GreaterEqual] == Key)
		{
			//r = -1;
			res = true;
		} else {
			r = GreaterEqual;
		}
	}

	return res;
}


template <typename TKey, uint16_t SizeParam>
inline void CBTree<TKey, SizeParam>::SplitNode(TNodeRef Node, TNode * NodeData, TNodeRef & Left, TNodeRef & Right, TKey & UpKey, TNodeRef ParentNode, uint16_t ParentIndex)
{
	const uint16_t upindex = SizeParam - 1;
	TNode *ldata, *rdata;
	Left = Node;
	ldata = NodeData;
	rdata = CreateNewNode(Right);
	
	typename TManagedMap::iterator it = m_ManagedIterators.find(Node);
	while ((it != m_ManagedIterators.end()) && (it->first == Node))
	{
		if (it->second->m_Index == upindex)
		{
			it->second->m_Index = ParentIndex;
			it->second->m_Node = ParentNode;
			m_ManagedIterators.insert(std::make_pair(ParentNode, it->second));
			it = m_ManagedIterators.erase(it);
		} else if (it->second->m_Index > upindex)
		{
			it->second->m_Index = it->second->m_Index - upindex - 1;
			it->second->m_Node = Right;
			m_ManagedIterators.insert(std::make_pair(Right, it->second));
			it = m_ManagedIterators.erase(it);
		} else {
			++it;
		}
	}

	UpKey = NodeData->Key[upindex];

	memcpy(&(rdata->Key[0]), &(NodeData->Key[upindex+1]), sizeof(TKey) * (cFullNode - upindex));
	if ((NodeData->Info & cIsLeafMask) == 0)
	{
		memcpy(&(rdata->Child[0]), &(NodeData->Child[upindex+1]), sizeof(TNodeRef) * (cFullNode - upindex + 1));

		for (int i = 0; i <= upindex; i++)
		{
			TNode * tmp = Read(rdata->Child[i]);
			tmp->Parent = Right;
			Write(rdata->Child[i]);
		}
	}

	rdata->Info = (NodeData->Info & cIsLeafMask) | upindex;
	NodeData->Info = rdata->Info;
	rdata->Parent = NodeData->Parent;

	Write(Left);
	Write(Right);
}

template <typename TKey, uint16_t SizeParam>
inline typename CBTree<TKey, SizeParam>::TNodeRef CBTree<TKey, SizeParam>::MergeNodes(TNodeRef Left, TNode * LeftData, TNodeRef Right, TNode * RightData, const TKey & DownKey, TNodeRef ParentNode, uint16_t ParentIndex)
{
	uint16_t downindex = LeftData->Info & cKeyCountMask;
	LeftData->Key[downindex] = DownKey;

	typename TManagedMap::iterator it = m_ManagedIterators.find(Right);
	while ((it != m_ManagedIterators.end()) && (it->first == Right))
	{
		it->second->m_Index = it->second->m_Index + downindex + 1;
		it->second->m_Node = Left;
		m_ManagedIterators.insert(std::make_pair(Left, it->second));
		it = m_ManagedIterators.erase(it);
	}

	it = m_ManagedIterators.find(ParentNode);
	while ((it != m_ManagedIterators.end()) && (it->first == ParentNode))
	{
		if (it->second->m_Index == ParentIndex)
		{
			it->second->m_Index = downindex;
			it->second->m_Node = Left;
			m_ManagedIterators.insert(std::make_pair(Left, it->second));
			it = m_ManagedIterators.erase(it);
		} else {
			++it;
		}
	}

	memcpy(&(LeftData->Key[downindex+1]), &(RightData->Key[0]), sizeof(TKey) * (RightData->Info & cKeyCountMask));
	if ((LeftData->Info & cIsLeafMask) == 0)
	{
		memcpy(&(LeftData->Child[downindex+1]), &(RightData->Child[0]), sizeof(TNodeRef) * ((RightData->Info & cKeyCountMask) + 1));

		for (int i = 0; i <= (RightData->Info & cKeyCountMask); i++)
		{
			TNode * tmp = Read(RightData->Child[i]);
			tmp->Parent = Left;
			Write(RightData->Child[i]);
		}
	}

	LeftData->Info = ((LeftData->Info & cIsLeafMask) | (downindex + 1 + (RightData->Info & cKeyCountMask)));

	Write(Left);
	DeleteNode(Right);

	return Left;
}


template <typename TKey, uint16_t SizeParam>
inline void CBTree<TKey, SizeParam>::KeyInsert(TNodeRef Node, TNode * NodeData, uint16_t Where)
{
	memcpy(&(NodeData->Key[Where+1]), &(NodeData->Key[Where]), sizeof(TKey) * ((NodeData->Info & cKeyCountMask) - Where));

	if ((NodeData->Info & cIsLeafMask) == 0)
		memcpy(&(NodeData->Child[Where+1]), &(NodeData->Child[Where]), sizeof(TNodeRef) * ((NodeData->Info & cKeyCountMask) - Where + 1));

	NodeData->Info++;

	typename TManagedMap::iterator it = m_ManagedIterators.find(Node);
	while ((it != m_ManagedIterators.end()) && (it->first == Node))
	{
		if (it->second->m_Index >= Where)
			it->second->m_Index++;

		++it;
	}
}

template <typename TKey, uint16_t SizeParam>
inline void CBTree<TKey, SizeParam>::KeyDelete(TNodeRef Node, TNode * NodeData, uint16_t Where)
{
	NodeData->Info--;

	typename TManagedMap::iterator it = m_ManagedIterators.find(Node);
	while ((it != m_ManagedIterators.end()) && (it->first == Node))
	{
		if (it->second->m_Index == Where)
		{
			it->second->Backup();
		} else if (it->second->m_Index > Where)
		{
			it->second->m_Index--;
		}

		++it;
	}

	memcpy(&(NodeData->Key[Where]), &(NodeData->Key[Where+1]), sizeof(TKey) * ((NodeData->Info & cKeyCountMask) - Where));

	if ((NodeData->Info & cIsLeafMask) == 0)
		memcpy(&(NodeData->Child[Where]), &(NodeData->Child[Where+1]), sizeof(TNodeRef) * ((NodeData->Info & cKeyCountMask) - Where + 1));
}


template <typename TKey, uint16_t SizeParam>
inline void CBTree<TKey, SizeParam>::KeyMove(TNodeRef Source, uint16_t SourceIndex, const TNode * SourceData, TNodeRef Dest, uint16_t DestIndex, TNode * DestData)
{
	DestData->Key[DestIndex] = SourceData->Key[SourceIndex];

	typename TManagedMap::iterator it = m_ManagedIterators.find(Source);
	while ((it != m_ManagedIterators.end()) && (it->first == Source))
	{
		if (it->second->m_Index == SourceIndex)
		{
			it->second->m_Index = DestIndex;
			it->second->m_Node = Dest;
			m_ManagedIterators.insert(std::make_pair(Dest, it->second));
			it = m_ManagedIterators.erase(it);
		} else {
			++it;
		}
	}
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator
CBTree<TKey, SizeParam>::Insert(const TKey & Key)
{
	TNode *node, *node2;
	TNodeRef actnode;
	TNodeRef nextnode;
	bool exists;
	uint16_t ge;

	PrepareInsertOperation();

	if (!m_Root)
	{
		node = CreateNewNode(m_Root);
		node->Info = cIsLeafMask;
		Write(m_Root);
		m_sigRootChanged.emit(this, m_Root);
	}

	actnode = m_Root;
	node = Read(actnode);
	if ((node->Info & cKeyCountMask) == cFullNode)  // root split
	{
		// be a little tricky and let the main code handle the actual splitting.
		// just assign a new root with keycount to zero and one child = old root
		// the InNode test will fail with GreaterEqual = 0
		node2 = CreateNewNode(nextnode);
		node2->Info = 0;
		node2->Child[0] = actnode;
		Write(nextnode);

		node->Parent = nextnode;
		Write(actnode);

		node = node2;
		actnode = nextnode;

		m_Root = nextnode;
		m_sigRootChanged.emit(this, m_Root);
	}

	while (actnode)
	{
		exists = InNodeFind(node, Key, ge);
		if (exists)  // already exists
		{
			return iterator(this, actnode, ge);
		} else {
			if (node->Info & cIsLeafMask) // direct insert to leaf node
			{
				KeyInsert(actnode, node, ge);

				node->Key[ge] = Key;

				Write(actnode);

				return iterator(this, actnode, ge);

			} else {  // middle node
				nextnode = node->Child[ge];
				node2 = Read(nextnode);

				if ((node2->Info & cKeyCountMask) == cFullNode) // split the childnode
				{
					KeyInsert(actnode, node, ge);
					SplitNode(nextnode, node2, node->Child[ge], node->Child[ge+1], node->Key[ge], actnode, ge);

					Write(actnode);
					if (node->Key[ge] == Key)
					{
						return iterator(this, actnode, ge);
					} else {
						if (node->Key[ge] < Key)
						{
							nextnode = node->Child[ge+1];
						} else {
							nextnode = node->Child[ge];
						}
					}

				}
				actnode = nextnode;
				node = Read(actnode);
				
			} // if (node.Info & cIsLeafMask)
		} // if (exists)
	}	// while (actnode)

	// something went wrong
	return iterator(this, 0, 0xFFFF);
}


template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator
CBTree<TKey, SizeParam>::Find(const TKey & Key)
{
	TNode * node;
	TNodeRef actnode = m_Root;
	uint16_t ge;

	if (!m_Root) return iterator(this, 0, 0xFFFF);

	node = Read(actnode);

	while (actnode)
	{
		if (InNodeFind(node, Key, ge))
		{
			return iterator(this, actnode, ge);
		}

		if (!(node->Info & cIsLeafMask))
		{
			actnode = node->Child[ge];
			node = Read(actnode);
		} else {
			actnode = 0;
		}
	}

	return iterator(this, 0, 0xFFFF);
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator
CBTree<TKey, SizeParam>::LowerBound(const TKey & Key)
{
	TNode * node;
	TNodeRef actnode = m_Root;
	uint16_t ge;

	if (!m_Root) return iterator(this, 0, 0xFFFF);

	node = Read(actnode);

	while (actnode)
	{
		if (InNodeFind(node, Key, ge))
		{
			return iterator(this, actnode, ge);
		}

		if (node->Info & cIsLeafMask)
		{
			if (ge >= (node->Info & cKeyCountMask))
			{
				iterator i(this, actnode, ge - 1);
				++i;
				return i;
			} else {
				return iterator(this, actnode, ge);
			}
		} else {
			actnode = node->Child[ge];
			node = Read(actnode);
		}
	}

	return iterator(this, 0, 0xFFFF);
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator
CBTree<TKey, SizeParam>::UpperBound(const TKey & Key)
{
	TNode * node;
	TNodeRef actnode = m_Root;
	uint16_t ge;
	if (!m_Root) return iterator(this, 0, 0xFFFF);

	node = Read(actnode);

	while (actnode)
	{
		if (InNodeFind(node, Key, ge))
		{
			return iterator(this, actnode, ge);
		}

		if (node->Info & cIsLeafMask)
		{
			if (ge == 0)
			{
				iterator i(this, actnode, 0);
				--i;
				return i;
			} else {
				return iterator(this, actnode, ge - 1);
			}
		} else {
			actnode = node->Child[ge];
			node = Read(actnode);
		}
	}

	return iterator(this, 0, 0xFFFF);
}

template <typename TKey, uint16_t SizeParam>
bool CBTree<TKey, SizeParam>::Delete(const TKey& Key)
{
	if (!m_Root) return false;

	TNode *node, *node2, *lnode, *rnode;
	
	TNodeRef actnode = m_Root;
	TNodeRef nextnode, l, r;
	bool exists, skipread;
	uint16_t ge;

	bool foundininnernode = false;
	bool wantleftmost = false;
	TNodeRef innernode = 0;
	TNode * innernodedata = NULL;
	uint16_t innerindex = 0xFFFF;

	node = Read(actnode);

	while (actnode)
	{
		skipread = false;

		if (foundininnernode)
		{
			exists = false;
			if (wantleftmost)
				ge = 0;
			else
				ge = node->Info & cKeyCountMask;

		} else {
			exists = InNodeFind(node, Key, ge);
		}

		if (exists)
		{
			if (node->Info & cIsLeafMask)  // delete in leaf
			{
				KeyDelete(actnode, node, ge);
				Write(actnode);

				return true;

			} else { // delete in inner node
				l = node->Child[ge];
				r = node->Child[ge+1];
				lnode = Read(l);
				rnode = Read(r);


				if (((rnode->Info & cKeyCountMask) == cEmptyNode) && ((lnode->Info & cKeyCountMask) == cEmptyNode))
				{ // merge childnodes and keep going
					nextnode = MergeNodes(l, lnode, r, rnode, node->Key[ge], actnode, ge);

					KeyDelete(actnode, node, ge);
					node->Child[ge] = nextnode;

					if ((actnode == m_Root) && ((node->Info & cKeyCountMask) == 0))
					{ // root node is empty. delete it
						DeleteNode(actnode);
						m_Root = nextnode;
						m_sigRootChanged.emit(this, m_Root);
					} else {
						Write(actnode);
					}

				} else { // need a key-data-pair from a leaf to replace deleted pair -> save position
					foundininnernode = true;
					innernode = actnode;
					innerindex = ge;
					innernodedata = node;

					if ((lnode->Info & cKeyCountMask) == cEmptyNode)
					{
						wantleftmost = true;
						nextnode = r;
					} else {
						wantleftmost = false;
						nextnode = l;
					}
				}
			}

		} else if (node->Info & cIsLeafMask) { // we are at the bottom. finish it
			if (foundininnernode)
			{
				if (wantleftmost)
				{
					KeyMove(actnode, 0, node, innernode, innerindex, innernodedata);
					Write(innernode);

					KeyDelete(actnode, node, 0);
					Write(actnode);

				} else {
					KeyMove(actnode, (node->Info & cKeyCountMask) - 1, node, innernode, innerindex, innernodedata);
					Write(innernode);

					//KeyDelete(actnode, node, node.Info & cKeyCountMask);
					node->Info--;
					Write(actnode);
				}
			}
			return foundininnernode;

		} else { // inner node. go on and check if moving or merging is neccessary
			nextnode = node->Child[ge];
			node2 = Read(nextnode);

			if ((node2->Info & cKeyCountMask) == cEmptyNode) // move or merge
			{
				// set l and r for easier access
				if (ge > 0)
				{
					l = node->Child[ge - 1];
					lnode = Read(l);
				} else
					l = 0;

				if (ge < (node->Info & cKeyCountMask))
				{
					r = node->Child[ge + 1];
					rnode = Read(r);
				} else
					r = 0;

				if ((r != 0) && ((rnode->Info & cKeyCountMask) > cEmptyNode)) // move a Key-Data-pair from the right
				{
					// move key-data-pair down from current to the next node
					KeyMove(actnode, ge, node, nextnode, node2->Info & cKeyCountMask, node2);

					// move the child from right to next node
					node2->Child[(node2->Info & cKeyCountMask) + 1] = rnode->Child[0];

					// move key-data-pair up from right to current node
					KeyMove(r, 0, rnode, actnode, ge, node);
					Write(actnode);

					// decrement right node key count and remove the first key-data-pair
					KeyDelete(r, rnode, 0);

					// increment KeyCount of the next node
					node2->Info++;

					if ((node2->Info & cIsLeafMask) == 0) // update the parent property of moved child
					{
						TNode * tmp = Read(node2->Child[node2->Info & cKeyCountMask]);
						tmp->Parent = nextnode;
						Write(node2->Child[node2->Info & cKeyCountMask]);
					}


					Write(r);
					Write(nextnode);
					node = node2;
					skipread = true;

				} else if ((l != 0) && ((lnode->Info & cKeyCountMask) > cEmptyNode)) // move a Key-Data-pair from the left
				{					
					// increment next node key count and make new first key-data-pair
					KeyInsert(nextnode, node2, 0);

					// move key-data-pair down from current to the next node
					KeyMove(actnode, ge - 1, node, nextnode, 0, node2);

					// move the child from left to next node
					node2->Child[0] = lnode->Child[lnode->Info & cKeyCountMask];

					// move key-data-pair up from left to current node
					KeyMove(l, (lnode->Info & cKeyCountMask) - 1, lnode, actnode, ge - 1, node);
					Write(actnode);

					// decrement left node key count
					lnode->Info--;
					Write(l);

					if ((node2->Info & cIsLeafMask) == 0) // update the parent property of moved child
					{
						TNode * tmp = Read(node2->Child[0]);
						tmp->Parent = nextnode;
						Write(node2->Child[0]);
					}

					Write(nextnode);
					node = node2;
					skipread = true;

				} else {
					if (l != 0) // merge with the left node
					{
						nextnode = MergeNodes(l, lnode, nextnode, node2, node->Key[ge - 1], actnode, ge - 1);
						KeyDelete(actnode, node, ge - 1);
						node->Child[ge - 1] = nextnode;

					} else { // merge with the right node
						nextnode = MergeNodes(nextnode, node2, r, rnode, node->Key[ge], actnode, ge);
						KeyDelete(actnode, node, ge);
						node->Child[ge] = nextnode;
					}

					if ((actnode == m_Root) && ((node->Info & cKeyCountMask) == 0))
					{
						DeleteNode(actnode);
						m_Root = nextnode;
						m_sigRootChanged(this, nextnode);
					} else {
						Write(actnode);
					}
				}
			}
		} // if (exists) else if (node.Info & cIsLeafMask)

		actnode = nextnode;
		if (!skipread)
			node = Read(actnode);

	} // while(actnode)

	return false;
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::TNodeRef CBTree<TKey, SizeParam>::getRoot()
{
	return m_Root;
}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::setRoot(TNodeRef NewRoot)
{
	m_Root = NewRoot;
	return;
}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::PrepareInsertOperation()
{
	if (m_Count + 64 > m_AllocCount)
	{
		m_AllocCount += 64;
		m_Alloc = (TNode *)realloc(m_Alloc, sizeof(TNode) * m_AllocCount);

		for (TNodeRef i = m_AllocCount - 64; i < m_AllocCount; ++i)
			m_Alloc[i].Parent = i + 1;
		
		m_Alloc[m_AllocCount - 1].Parent = 0;
		
		if (m_FreeIndex)
		{
			TNodeRef i = m_FreeIndex; 
			while (m_Alloc[i].Parent)
				i = m_Alloc[i].Parent;
			
			m_Alloc[i].Parent = m_AllocCount - 64;
			
		} else {
			m_FreeIndex = m_AllocCount - 63;
		}
		
	}
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::TNode * CBTree<TKey, SizeParam>::CreateNewNode(TNodeRef & NodeRef)
{
	NodeRef = m_FreeIndex;
	m_FreeIndex = m_Alloc[m_FreeIndex].Parent;
	m_Count++;
	memset(m_Alloc + NodeRef, 0, sizeof(TNode));
	return m_Alloc + NodeRef;
}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::DeleteNode(TNodeRef Node)
{
	CHECK((Node > 0) && (Node < m_AllocCount), logERROR, _T("Invalid Node"));
	m_Alloc[Node].Parent = m_FreeIndex;
	m_FreeIndex = Node;
	m_Count--;
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::TNode * CBTree<TKey, SizeParam>::Read(TNodeRef Node)
{
	CHECK((Node > 0) && (Node < m_AllocCount), logERROR, _T("Invalid Node"));
	return m_Alloc + Node;
}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::Write(TNodeRef Node)
{
	return;
}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::DestroyTree()
{
	std::stack<TNodeRef> s;
	TNodeRef node;
	TNode* nodedata;
	uint16_t i;

	if (m_Root)
		s.push(m_Root);
	while (!s.empty())
	{
		node = s.top();
		nodedata = Read(node);
		s.pop();

		if ((nodedata->Info & cIsLeafMask) == 0)
		{
			for (i = 0; i <= (nodedata->Info & cKeyCountMask); i++)
				s.push(nodedata->Child[i]);
		}

		DeleteNode(node);
	}

	free(m_Alloc);
	m_Alloc = NULL;
	m_AllocCount = 0;
	m_Count = 0;
	m_FreeIndex = 0;
}


template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::DeleteTree(TDeleteCallback * CallBack, uint32_t Param)
{
	std::stack<TNodeRef> s;
	TNodeRef actnode;
	TNode * node;
	uint16_t i;

	typename TManagedMap::iterator it = m_ManagedIterators.begin();
	while (it != m_ManagedIterators.end())
	{
		it->second->m_Node = 0;
		it->second->m_Index = 0xffff;
		++it;
	}

	if (m_Root)
		s.push(m_Root);

	m_Root = 0;
	m_sigRootChanged.emit(this, m_Root);

	while (!s.empty())
	{
		actnode = s.top();
		s.pop();

		node = Read(actnode);

		if ((node->Info & cIsLeafMask) == 0)
		{
			for (i = 0; i <= (node->Info & cKeyCountMask); i++)
				s.push(node->Child[i]);
		
		}
		if (CallBack)
		{
			for (i = 0; i < (node->Info & cKeyCountMask); i++)
				CallBack->emit(this, node->Key[i], Param);
		}

		DeleteNode(actnode);
	}
}







template <typename TKey, uint16_t SizeParam>
CBTree<TKey, SizeParam>::iterator::iterator()
{
	m_Tree = NULL;
	m_Node = 0;
	m_Index = 0xFFFF;
	m_Managed = false;
	m_ManagedDeleted = false;
	m_LoadedKey = false;
}
template <typename TKey, uint16_t SizeParam>
CBTree<TKey, SizeParam>::iterator::iterator(CBTree* Tree, TNodeRef Node, uint16_t Index)
{
	m_Tree = Tree;
	m_Node = Node;
	m_Index = Index;
	m_Managed = false;
	m_ManagedDeleted = false;
	m_LoadedKey = false;
}
template <typename TKey, uint16_t SizeParam>
CBTree<TKey, SizeParam>::iterator::iterator(const iterator& Other)
{
	m_Tree = Other.m_Tree;
	m_Node = Other.m_Node;
	m_Index = Other.m_Index;
	m_ManagedDeleted = Other.m_ManagedDeleted;
	m_Managed = Other.m_Managed;
	m_LoadedKey = Other.m_LoadedKey;
	m_ManagedKey = Other.m_ManagedKey;

	if (m_Managed)
		InsertManaged();
}

template <typename TKey, uint16_t SizeParam>
CBTree<TKey, SizeParam>::iterator::~iterator()
{
	RemoveManaged(m_Node);
}


template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::iterator::setManaged()
{
	if (!m_Managed)
		InsertManaged();

	m_Managed = true;
}

template <typename TKey, uint16_t SizeParam>
inline void CBTree<TKey, SizeParam>::iterator::RemoveManaged(TNodeRef FromNode)
{
	if (m_Managed && m_Tree)
	{
		typename TManagedMap::iterator i = m_Tree->m_ManagedIterators.find(FromNode);

		while ((i != m_Tree->m_ManagedIterators.end()) && (i->second != this) && (i->first == FromNode))
			++i;

		if ((i != m_Tree->m_ManagedIterators.end()) && (i->second == this))
			m_Tree->m_ManagedIterators.erase(i);
	}
}
template <typename TKey, uint16_t SizeParam>
inline void CBTree<TKey, SizeParam>::iterator::InsertManaged()
{
	if (m_Tree)
		m_Tree->m_ManagedIterators.insert(std::make_pair(m_Node, this));
}

template <typename TKey, uint16_t SizeParam>
bool CBTree<TKey, SizeParam>::iterator::wasDeleted()
{
	return m_ManagedDeleted;
}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::iterator::Backup()
{
	if ((!m_ManagedDeleted) && (*this))
	{
		TNode * tmp;
		if (!m_LoadedKey)
		{
			tmp = m_Tree->Read(m_Node);
			m_ManagedKey = tmp->Key[m_Index];
		}
		m_LoadedKey = true;
	}

	m_ManagedDeleted = true;
}

template <typename TKey, uint16_t SizeParam>
CBTree<TKey, SizeParam> * CBTree<TKey, SizeParam>::iterator::Tree()
{
	return m_Tree;
}

template <typename TKey, uint16_t SizeParam>
const TKey& CBTree<TKey, SizeParam>::iterator::operator *()
{
	if (!m_LoadedKey)
	{
		TNode * node;
		node = m_Tree->Read(m_Node);
		m_ManagedKey = node->Key[m_Index];
		m_LoadedKey = true;
	}
	return m_ManagedKey;
}

template <typename TKey, uint16_t SizeParam>
const TKey* CBTree<TKey, SizeParam>::iterator::operator ->()
{
	if (!m_LoadedKey)
	{
		TNode * node;
		node = m_Tree->Read(m_Node);
		m_ManagedKey = node->Key[m_Index];
		m_LoadedKey = true;
	}
	return &m_ManagedKey;
}

template <typename TKey, uint16_t SizeParam>
inline CBTree<TKey, SizeParam>::iterator::operator bool() const
{
	if (m_Tree && m_Node)
	{
		TNode * node;
		node = m_Tree->Read(m_Node);
		return (m_Index < (node->Info & cKeyCountMask));
	} else
		return false;
}

template <typename TKey, uint16_t SizeParam>
inline bool CBTree<TKey, SizeParam>::iterator::operator !() const
{
	if (m_Tree && m_Node)
	{
		TNode * node;
		node = m_Tree->Read(m_Node);
		return (m_Index > (node->Info & cKeyCountMask));
	} else
		return true;
}

template <typename TKey, uint16_t SizeParam>
inline bool CBTree<TKey, SizeParam>::iterator::operator ==(iterator & Other)
{
	//return (m_Tree == Other.m_Tree) && (m_Node == Other.m_Node) && (m_Index == Other.m_Index) && (!m_ManagedDeleted) && (!Other.m_ManagedDeleted);
	return Key() == Other.Key();
}

template <typename TKey, uint16_t SizeParam>
inline bool CBTree<TKey, SizeParam>::iterator::operator <  (iterator & Other)
{
	return Key() < Other.Key();
}
template <typename TKey, uint16_t SizeParam>
inline bool CBTree<TKey, SizeParam>::iterator::operator >  (iterator & Other)
{
	return Key() > Other.Key();
}


template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator&
CBTree<TKey, SizeParam>::iterator::operator =(const iterator& Other)
{
	RemoveManaged(m_Node);

	m_Tree = Other.m_Tree;
	m_Node = Other.m_Node;
	m_Index = Other.m_Index;
	m_ManagedDeleted = Other.m_ManagedDeleted;
	m_Managed = Other.m_Managed;
	m_LoadedKey = Other.m_LoadedKey;
	m_ManagedKey = Other.m_ManagedKey;

	if (m_Managed)
		InsertManaged();

	return *this;
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator&
CBTree<TKey, SizeParam>::iterator::operator ++() //pre  ++i
{
	TNodeRef oldnode = m_Node;
	if (m_Managed && m_ManagedDeleted)
	{
		TKey oldkey = m_ManagedKey;
		m_LoadedKey = false;
		m_ManagedDeleted = false;
		iterator other = m_Tree->LowerBound(m_ManagedKey);
		m_Node = other.m_Node;
		m_Index = other.m_Index;
		while (((**this) == oldkey) && (*this))
			Inc();

	} else
		Inc();

	if (m_Managed && (oldnode != m_Node))
	{
		RemoveManaged(oldnode);
		InsertManaged();
	}
	return *this;
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator&
CBTree<TKey, SizeParam>::iterator::operator --() //pre  --i
{
	TNodeRef oldnode = m_Node;
	if (m_Managed && m_ManagedDeleted)
	{
		TKey oldkey = m_ManagedKey;
		m_LoadedKey = false;

		m_ManagedDeleted = false;
		iterator other = m_Tree->UpperBound(m_ManagedKey);
		m_Node = other.m_Node;
		m_Index = other.m_Index;
		while (((**this) == oldkey) && (*this))
			Dec();
	} else
		Dec();

	if (m_Managed && (oldnode != m_Node))
	{
		RemoveManaged(oldnode);
		InsertManaged();
	}
	return *this;
}

template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator
CBTree<TKey, SizeParam>::iterator::operator ++(int) //post i++
{
	iterator tmp(*this);
	++(*this);
	return tmp;
}
template <typename TKey, uint16_t SizeParam>
typename CBTree<TKey, SizeParam>::iterator
CBTree<TKey, SizeParam>::iterator::operator --(int) //post i--
{
	iterator tmp(*this);
	--(*this);
	return tmp;
}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::iterator::Inc()
{
	TNode * node;
	TNodeRef nextnode;
	node = m_Tree->Read(m_Node);

	m_LoadedKey = false;

	if ((node->Info & cIsLeafMask) && ((node->Info & cKeyCountMask) > m_Index + 1)) // leaf
	{
		m_Index++;
		return;
	}

	if ((node->Info & cIsLeafMask) == 0) // inner node. go down
	{
		m_Node = node->Child[m_Index + 1];
		node = m_Tree->Read(m_Node);

		m_Index = 0;

		while ((node->Info & cIsLeafMask) == 0)  // go down to a leaf
		{
			m_Node = node->Child[0];
			node = m_Tree->Read(m_Node);
		}

		return;
	}

	while (m_Index >= (node->Info & cKeyCountMask) - 1) // go up
	{
		if (m_Node == m_Tree->m_Root) // the root is the top, we cannot go further
		{
			m_Index = 0xFFFF;
			m_Node = 0;
			return;
		}

		nextnode = node->Parent;
		node = m_Tree->Read(nextnode);
		m_Index = 0;

		while ((m_Index <= (node->Info & cKeyCountMask)) && (node->Child[m_Index] != m_Node))
			m_Index++;

		m_Node = nextnode;

		if (m_Index < (node->Info & cKeyCountMask))
			return;
	}

}

template <typename TKey, uint16_t SizeParam>
void CBTree<TKey, SizeParam>::iterator::Dec()
{
	TNode * node;
	TNodeRef nextnode;
	node = m_Tree->Read(m_Node);

	m_LoadedKey = false;

	if ((node->Info & cIsLeafMask) && (m_Index > 0)) // leaf
	{
		m_Index--;
		return;
	}

	if ((node->Info & cIsLeafMask) == 0) // inner node. go down
	{
		m_Node = node->Child[m_Index];
		node = m_Tree->Read(m_Node);
		m_Index = (node->Info & cKeyCountMask) - 1;

		while ((node->Info & cIsLeafMask) == 0)  // go down to a leaf
		{
			m_Node = node->Child[node->Info & cKeyCountMask];
			node = m_Tree->Read(m_Node);
			m_Index = (node->Info & cKeyCountMask) - 1;
		}

		return;
	}

	while (m_Index == 0) // go up
	{
		if (m_Node == m_Tree->m_Root) // the root is the top, we cannot go further
		{
			m_Index = 0xFFFF;
			m_Node = 0;
			return;
		}

		nextnode = node->Parent;
		node = m_Tree->Read(nextnode);
		m_Index = 0;

		while ((m_Index <= (node->Info & cKeyCountMask)) && (node->Child[m_Index] != m_Node))
			m_Index++;

		m_Node = nextnode;

		if (m_Index > 0)
		{
			m_Index--;
			return;
		}
	}
}