4 BTree::BTree (const std::string &name, unsigned int block_size, int kt, bool create_new_file)
10 fp = fopen (name.c_str(), "wb+");
12 /* TODO : mandar una exception ? */
16 /* Nombre de archivo */
19 /* Inicializo el header */
20 header.block_size = block_size;
23 /* Creo el primer bloque vacio */
24 node = new uchar[block_size];
25 ReadNodoHeader (node, &nh);
27 nh.free_space = block_size - sizeof (BTreeNodeHeader);
29 WriteNodoHeader (node, &nh);
40 void BTree::WriteFileHeader ()
42 fseek (fp, 0L, SEEK_SET);
43 fwrite (&header, 1, sizeof (BTreeFileHeader), fp);
46 void BTree::WriteBlock (uchar *block, uint num)
49 fseek (fp, num*header.block_size, SEEK_SET);
50 fwrite (block, 1, header.block_size, fp);
53 void BTree::AddKey (const Clave &k)
56 Clave *kout = AddKeyR (&k, 0, left, right);
60 /* Debo dejar la raiz en el nodo 0, por lo que paso el nodo
61 * que esta usando el hijo izquierdo a un nuevo nodo */
62 std::list<BTreeData *> node_keys;
63 BTreeNodeHeader node_header;
64 uchar *node = ReadBlock (left);
65 ReadNodoHeader (node, &node_header);
66 node_keys = ReadKeys (node, node_header);
67 level = node_header.level + 1;
69 uchar *new_node = NewBlock (left);
70 delete [] new_node; /* No me interesa, voy a usar lo leio antes */
72 WriteKeys (node, node_header, node_keys);
73 WriteNodoHeader (node, &node_header);
74 WriteBlock (node, left);
75 DeleteKeys (node_keys);
78 /* Leo y actualizo la Raiz */
80 ReadNodoHeader (node, &node_header);
81 node_keys = std::list<BTreeData *>();
83 node_keys.push_back (new BTreeChildData (left));
84 node_keys.push_back (new BTreeData (kout, right));
86 node_header.level = level;
87 node_header.item_count = 1;
89 WriteKeys (node, node_header, node_keys);
90 WriteNodoHeader (node, &node_header);
93 DeleteKeys (node_keys);
98 Clave* BTree::AddKeyR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
100 uchar *node = ReadBlock (node_num);
101 BTreeNodeHeader node_header;
102 ReadNodoHeader (node, &node_header);
105 if (node_header.level == 0)
106 return AddKeyLeafR (k, node_num, left_child, right_child);
108 return AddKeyOtherR (k, node_num, left_child, right_child);
111 Clave* BTree::AddKeyLeafR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
114 std::list<BTreeData *> node_keys;
116 BTreeData *data = new BTreeLeafData (k->Clone ());
118 /* Leo el nodo raiz para empezar a agregar */
119 uchar *node = ReadBlock (node_num);
120 BTreeNodeHeader node_header;
121 ReadNodoHeader (node, &node_header);
123 if (node_header.free_space > data->Size ()) {
125 node_keys = ReadKeys (node, node_header);
126 std::list<BTreeData *>::iterator it = node_keys.begin ();
128 while (it != node_keys.end ()) {
130 if ((*data) < (*datait))
131 /* Me pase, lo agrego aca! */
135 node_keys.insert (it, data);
136 WriteKeys (node, node_header, node_keys);
137 WriteNodoHeader (node, &node_header);
138 WriteBlock (node, node_num);
139 DeleteKeys (node_keys);
142 PrintNode (node_num);
144 /* Split : Creo e inicializo el nuevo nodo */
145 std::list<BTreeData *> new_node_keys;
146 std::list<BTreeData *> old_node_keys;
147 BTreeNodeHeader new_node_header;
149 uchar *new_node = NewBlock (new_node_num);
150 ReadNodoHeader (new_node, &new_node_header);
151 new_node_header.level = node_header.level;
153 node_keys = ReadKeys (node, node_header);
154 new_node_keys = ReadKeys (new_node, new_node_header);
156 /* Agrego la clave en la lista que ya tengo de manera ordenada */
157 std::list<BTreeData *>::iterator it = node_keys.begin ();
158 std::list<BTreeData *>::iterator previt = node_keys.begin ();
160 while (it != node_keys.end ()) {
163 if ((*data) < (*datait))
164 /* Me pase, lo agrego aca! */
169 if (it != node_keys.end ())
170 node_keys.insert (it, data);
172 node_keys.push_back (data);
174 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
175 * y subir la clave del medio */
176 node_header.item_count = 0;
177 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
180 it = node_keys.begin ();
181 while (it != node_keys.end ()) {
184 total_size += datait->Size ();
186 /* Hack : Si me quedo con todas las claves, en el caso de ser
187 * del mismo tama#o se desbalancea. Hay que ver que efecto
188 * puede tener en el caso de claves de long. variable
190 if (it == node_keys.end ())
191 total_size -= datait->Size ();
194 it = node_keys.begin ();
196 while (used < total_size/2) {
197 BTreeData *d = (*it);
198 old_node_keys.push_back (d);
202 kout = (*it++)->GetKey (); // Esta se retorna al "padre" para que se la agregue
204 while (it != node_keys.end ()) {
205 BTreeData *d = (*it);
206 new_node_keys.push_back (d);
211 WriteKeys (node, node_header, old_node_keys);
212 WriteNodoHeader (node, &node_header);
213 WriteBlock (node, node_num);
214 WriteKeys (new_node, new_node_header, new_node_keys);
215 WriteNodoHeader (new_node, &new_node_header);
216 WriteBlock (new_node, new_node_num);
217 DeleteKeys (old_node_keys);
218 DeleteKeys (new_node_keys);
220 PrintNode (node_num);
221 PrintNode (new_node_num);
224 left_child = node_num;
225 right_child = new_node_num;
233 Clave* BTree::AddKeyOtherR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
236 std::list<BTreeData *> node_keys;
238 BTreeData *data = new BTreeLeafData (k->Clone ());
240 /* Leo el nodo raiz para empezar a agregar */
241 uchar *node = ReadBlock (node_num);
242 BTreeNodeHeader node_header;
243 ReadNodoHeader (node, &node_header);
245 node_keys = ReadKeys (node, node_header);
247 std::list<BTreeData *>::iterator it = node_keys.begin ();
248 std::list<BTreeData *>::iterator posterior;
249 std::list<BTreeData *>::iterator ultima;
251 /* Se supone que la primera es un hijo :) */
252 BTreeData *lchild = (*it++);
255 while (it != node_keys.end ()) {
256 if ((*data) < (*(*it)))
262 if (it == posterior) {
263 k = AddKeyR (k, lchild->GetChild (), left_child, right_child);
265 k = AddKeyR (k, (*ultima)->GetChild (), left_child, right_child);
267 DeleteKeys (node_keys);
270 if (data) delete data;
276 data = new BTreeData (k->Clone (), right_child);
278 if (node_header.free_space > data->Size ()) {
280 node_keys = ReadKeys (node, node_header);
281 std::list<BTreeData *>::iterator it = node_keys.begin ();
283 while (it != node_keys.end ()) {
285 if ((*data) < (*datait))
286 /* Me pase, lo agrego aca! */
290 node_keys.insert (it, data);
291 WriteKeys (node, node_header, node_keys);
292 WriteNodoHeader (node, &node_header);
293 WriteBlock (node, node_num);
294 DeleteKeys (node_keys);
297 PrintNode (node_num);
299 /* Split : Creo e inicializo el nuevo nodo */
300 std::list<BTreeData *> new_node_keys;
301 std::list<BTreeData *> old_node_keys;
302 BTreeNodeHeader new_node_header;
304 uchar *new_node = NewBlock (new_node_num);
305 ReadNodoHeader (new_node, &new_node_header);
306 new_node_header.level = node_header.level;
308 node_keys = ReadKeys (node, node_header);
309 new_node_keys = ReadKeys (new_node, new_node_header);
311 /* Agrego la clave en la lista que ya tengo de manera ordenada */
312 std::list<BTreeData *>::iterator it = node_keys.begin ();
313 std::list<BTreeData *>::iterator previt = node_keys.begin ();
317 while (it != node_keys.end ()) {
320 if ((*data) < (*datait))
321 /* Me pase, lo agrego aca! */
326 if (it != node_keys.end ())
327 node_keys.insert (it, data);
329 node_keys.push_back (data);
331 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
332 * y subir la clave del medio */
333 node_header.item_count = 0;
334 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
337 it = node_keys.begin ();
338 while (it != node_keys.end ()) {
341 total_size += datait->Size ();
343 /* Hack : Si me quedo con todas las claves, en el caso de ser
344 * del mismo tama#o se desbalancea. Hay que ver que efecto
345 * puede tener en el caso de claves de long. variable
347 if (it == node_keys.end ())
348 total_size -= datait->Size ();
351 it = node_keys.begin ();
353 while (used < total_size/2) {
354 BTreeData *d = (*it);
355 old_node_keys.push_back (d);
359 kout = (*it)->GetKey (); // Esta se retorna al "padre" para que se la agregue
361 new_node_keys.push_back ( new BTreeChildData ((*it)->GetChild ()));
363 while (it != node_keys.end ()) {
364 BTreeData *d = (*it);
365 new_node_keys.push_back (d);
370 WriteKeys (node, node_header, old_node_keys);
371 WriteNodoHeader (node, &node_header);
372 WriteBlock (node, node_num);
373 WriteKeys (new_node, new_node_header, new_node_keys);
374 WriteNodoHeader (new_node, &new_node_header);
375 WriteBlock (new_node, new_node_num);
376 DeleteKeys (old_node_keys);
377 DeleteKeys (new_node_keys);
379 PrintNode (node_num);
380 PrintNode (new_node_num);
383 left_child = node_num;
384 right_child = new_node_num;
392 void BTree::DelKey (const Clave &k)
395 std::cout << "========= Borrando " << s << " =================\n";
396 BTreeData *b = new BTreeLeafData (k.Clone ());
401 void BTree::DelKeyR (BTreeData *k, uint node_num, uint padre)
403 std::list<BTreeData *> node_keys;
404 BTreeNodeHeader node_header;
407 node = ReadBlock (node_num);
408 ReadNodoHeader (node, &node_header);
409 node_keys = ReadKeys (node, node_header);
411 std::list<BTreeData *>::iterator it = node_keys.begin ();
412 std::list<BTreeData *>::iterator ultima;
413 std::list<BTreeData *>::iterator posterior;
416 if (node_header.level != 0) {
421 while (it != node_keys.end ()) {
422 if ((*k) == (*(*it))) {
423 /* La encontre!, retorno */
424 if (node_header.level == 0) {
425 DelKeyFromLeaf (k->GetKey (), node_num, padre);
428 if (it == posterior) {
429 left = lchild->GetChild ();
430 right = (*it)->GetChild ();
432 left = (*ultima)->GetChild ();
433 right = (*it)->GetChild ();
435 std::cout << "Eliminar de Nodo con hijos : " << left << " y " << right << std::endl;
436 DelKeyFromNode (k->GetKey (), node_num, padre, left, right);
438 DeleteKeys (node_keys);
449 /* Si llego aca y estoy en nivel 0 (una hoja) quiere
450 * decir que no lo encontre
452 if (node_header.level == 0) {
453 std::cout << "*** Clave no encontrada ***\n";
457 /* TODO: Aca faltaria liberar memoria */
458 if (it == posterior) {
459 DelKeyR (k, lchild->GetChild (), node_num);
461 DelKeyR (k, (*ultima)->GetChild (), node_num);
465 void BTree::DelKeyFromLeaf (Clave *k, uint node_num, uint padre)
469 BTreeNodeHeader node_header;
470 std::list<BTreeData *> node_keys;
472 node = ReadBlock (node_num);
473 ReadNodoHeader (node, &node_header);
474 node_keys = ReadKeys (node, node_header);
476 data = new BTreeLeafData (k->Clone ());
478 std::list<BTreeData *>::iterator it;
479 it = node_keys.begin ();
480 while (it != node_keys.end ()) {
481 if ((*data) == (*(*it))) {
482 BTreeData *aborrar = (*it);
483 node_keys.erase (it);
492 WriteKeys (node, node_header, node_keys);
493 WriteNodoHeader (node, &node_header);
494 WriteBlock (node, node_num);
496 /* Veo si se cumple la condición de minimalidad */
497 uint min_free = (header.block_size-sizeof(BTreeNodeHeader))/2;
498 if ((node_header.free_space > min_free) && (node_num != 0)) {
499 /* Oops! Debo pedir prestada clave */
503 FindBrothers (node_num, padre, hi, hd);
505 if ((pedida = GetKey (hi, 1)) != NULL) {
506 std::string s = *pedida;
507 std::cout << "Clave Pedida : " << s << std::endl;
509 pedida = ReplaceKeyInFather (node_num, padre, pedida);
511 node_keys.insert (node_keys.begin (), new BTreeLeafData (pedida));
512 } else if ((pedida = GetKey (hd, 0)) != NULL) {
513 std::string s = *pedida;
514 std::cout << "Clave Pedida : " << s << std::endl;
516 pedida = ReplaceKeyInFather (node_num, padre, pedida);
518 node_keys.push_back (new BTreeLeafData (pedida));
520 std::cout << "NADIE ME PUEDE PRESTAR, FUNDIR NODOS\n";
524 std::cout << "Join con Hermano Izquierdo\n";
529 std::cout << "Join con Hermano Derecho\n";
535 JoinNodes (join1, join2, padre, tipoh);
537 DeleteKeys (node_keys);
542 WriteKeys (node, node_header, node_keys);
543 WriteNodoHeader (node, &node_header);
544 WriteBlock (node, node_num);
547 DeleteKeys (node_keys);
549 std::cout << "Borrado de una hoja listo\n";
552 void BTree::JoinNodes (uint node1, uint node2, uint padre, int tipohermano)
554 uchar *n1, *n2, *npadre;
555 BTreeNodeHeader nh1, nh2, nhp;
556 std::list<BTreeData *> nk1, nk2, nkpadre;
558 if (node1 == node2) {
559 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
562 if (node1 == padre) {
563 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
566 if (node2 == padre) {
567 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
576 n1 = ReadBlock (node1);
577 n2 = ReadBlock (node2);
578 npadre = ReadBlock (padre);
580 ReadNodoHeader (n1, &nh1);
581 ReadNodoHeader (n2, &nh2);
582 ReadNodoHeader (npadre, &nhp);
585 uint tmp = header.block_size - sizeof (BTreeNodeHeader);
586 uint l = tmp - nh1.free_space;
587 l += tmp - nh1.free_space;
590 std::cout << "Espacio ocupado despues de unir : " << l << " de " << tmp << std::endl;
592 nk1 = ReadKeys (n1, nh1);
593 nk2 = ReadKeys (n2, nh2);
594 nkpadre = ReadKeys (npadre, nhp);
596 /* Busco la clave del padre a juntar con los nodos */
597 std::list<BTreeData *>::iterator it = nkpadre.begin ();
598 std::list<BTreeData *>::iterator borrar_padre;
599 std::list<BTreeData *>::iterator sig;
600 std::list<BTreeData *>::iterator anterior = it;
603 BTreeData *lchild = (*it++);
605 if (lchild->GetChild () == node1) {
606 cpadre = (*it)->GetKey ();
609 while (it != nkpadre.end ()) {
610 if (tipohermano == 0) {
611 if ((*it)->GetChild () == node2)
614 if ((*it)->GetChild () == node1)
620 cpadre = (*it)->GetKey ();
623 if (it == nkpadre.end ()) {
624 std::cout << "PANIC : Me pase sin encontrar la clave!!\n";
630 std::list<BTreeData *> newkeys;
631 std::list<BTreeData *>::iterator i;
634 while (i != nk1.end ()) {
635 newkeys.push_back ( new BTreeLeafData ((*i)->GetKey ()->Clone ()));
638 //if (tipohermano == 0)
639 newkeys.push_back ( new BTreeLeafData (cpadre->Clone ()));
641 while (i != nk2.end ()) {
642 newkeys.push_back ( new BTreeLeafData ((*i)->GetKey ()->Clone ()));
646 std::cout << "Espacio ocupado por las nuevas claves : " << (newkeys.size()*4) << std::endl;
647 if ((newkeys.size()*4) > tmp) {
648 std::cout << "PANIC : El nodo fundido no entra !!!\n";
652 /* Para el padre, tener 2 items significa tener solo 1 clave, ya que
653 * el otro item es el LeftChild!
655 if ((padre == 0) && (nhp.item_count == 2)) {
656 /* Si junte 2 nodos, cuyo padre era la raiz, y esta tenia
657 * solo una clave, quiere decir que lo que me queda
658 * es de nuevo solo una raiz con todas las claves
661 WriteKeys (npadre, nhp, newkeys);
662 WriteNodoHeader (npadre, &nhp);
663 WriteBlock (npadre, padre);
665 /* TODO: Recuperar nodo1 y nodo2 */
667 WriteKeys (n1, nh1, newkeys);
668 WriteNodoHeader (n1, &nh1);
669 WriteBlock (n1, node1);
671 /* TODO : Recuperar node2 */
672 /* Actualizo punero al padre */
673 (*anterior)->SetChild (node1);
675 nkpadre.erase (borrar_padre);
676 WriteKeys (npadre, nhp, nkpadre);
677 WriteNodoHeader (npadre, &nhp);
678 WriteBlock (npadre, padre);
681 std::cout << " ----- Luego de Fundir -----\n";
684 std::cout << " ---------------------------\n";
688 DeleteKeys (nkpadre);
689 DeleteKeys (newkeys);
696 Clave *BTree::GetKey (uint node_num, char maxmin)
699 std::cout << "Nodo no me puede prestar ... es NULL\n";
704 BTreeNodeHeader node_header;
705 std::list<BTreeData *> node_keys;
707 node = ReadBlock (node_num);
708 ReadNodoHeader (node, &node_header);
709 node_keys = ReadKeys (node, node_header);
711 std::list<BTreeData *>::iterator it = node_keys.begin ();
713 if (node_header.level != 0) it++;
716 uint free = node_header.free_space; // + (*it)->Size ();
717 uint min_free = (header.block_size - sizeof (BTreeNodeHeader))/2;
718 if (free > min_free) {
719 std::cout << "No puedo prestar : Free = " << free << " Minimo = " << min_free << std::endl;
720 PrintNode (node_num);
721 WriteKeys (node, node_header, node_keys);
722 WriteNodoHeader (node, &node_header);
723 WriteBlock (node, node_num);
724 DeleteKeys (node_keys);
732 k = (*it)->GetKey ()->Clone ();
733 node_keys.erase (it);
735 it = node_keys.end ();
737 k = (*it)->GetKey ()->Clone ();
738 node_keys.erase (it);
741 WriteKeys (node, node_header, node_keys);
742 WriteNodoHeader (node, &node_header);
743 WriteBlock (node, node_num);
744 DeleteKeys (node_keys);
751 void BTree::FindBrothers (uint node_num, uint padre, uint &left, uint &right)
754 BTreeNodeHeader node_header;
755 std::list<BTreeData *> node_keys;
757 node = ReadBlock (padre);
758 ReadNodoHeader (node, &node_header);
759 node_keys = ReadKeys (node, node_header);
761 std::list<BTreeData *>::iterator it = node_keys.begin ();
762 std::list<BTreeData *>::iterator anterior = node_keys.begin ();
763 std::list<BTreeData *>::iterator siguiente;
765 BTreeData *lchild = (*it++);
767 if (lchild->GetChild () == node_num) {
768 /* Solo tengo hermano derecho */
769 std::cout << "Hermano Izquierdo : NO TENGO" << std::endl;
771 std::cout << "Hermano Derecho : " << (*it)->GetChild () << std::endl;
772 right = (*it)->GetChild ();
776 while (it != node_keys.end ()) {
777 if ((*it)->GetChild () == node_num)
784 std::cout << "Hermano Izquierdo : " << (*anterior)->GetChild () << std::endl;
785 left = (*anterior)->GetChild ();
786 if (siguiente != node_keys.end ()) {
787 right = (*siguiente)->GetChild ();
788 std::cout << "Hermano Derecho : " << (*siguiente)->GetChild () << std::endl;
791 std::cout << "Hermano Derecho : NO TENGO" << std::endl;
795 Clave *BTree::ReplaceKeyInFather (uint node_num, uint padre, Clave *k)
798 BTreeNodeHeader node_header;
799 std::list<BTreeData *> node_keys;
801 node = ReadBlock (padre);
802 ReadNodoHeader (node, &node_header);
803 node_keys = ReadKeys (node, node_header);
805 std::list<BTreeData *>::iterator it = node_keys.begin ();
806 std::list<BTreeData *>::iterator anterior = node_keys.begin ();
807 std::list<BTreeData *>::iterator siguiente;
809 BTreeData *lchild = (*it++);
811 if (lchild->GetChild () == node_num) {
812 Clave *ret = (*it)->GetKey ();
815 WriteKeys (node, node_header, node_keys);
816 WriteNodoHeader (node, &node_header);
817 WriteBlock (node, padre);
818 DeleteKeys (node_keys);
824 while (it != node_keys.end ()) {
825 if ((*it)->GetChild () == node_num)
831 Clave *ret = (*it)->GetKey ();
834 WriteKeys (node, node_header, node_keys);
835 WriteNodoHeader (node, &node_header);
836 WriteBlock (node, padre);
837 DeleteKeys (node_keys);
843 void BTree::DelKeyFromNode (Clave *k, uint node_num, uint padre, uint left, uint right)
847 BTreeNodeHeader node_header;
848 std::list<BTreeData *> node_keys;
850 node = ReadBlock (node_num);
851 ReadNodoHeader (node, &node_header);
852 node_keys = ReadKeys (node, node_header);
855 std::cout << "Busco para la derecha y luego todo a la izquierda\n";
857 BTreeNodeHeader node_hr;
858 std::list<BTreeData *> node_keyr;
860 /* Busco la clave inmediatamente superior en el arbol */
861 padre_hijo = node_num;
863 node_r = ReadBlock (right);
864 ReadNodoHeader (node_r, &node_hr);
865 if (node_hr.level != 0) {
867 node_keyr = ReadKeys (node_r, node_hr);
868 data_r = *(node_keyr.begin ());
870 right = data_r->GetChild ();
872 DeleteKeys (node_keyr);
875 } while (node_hr.level != 0);
877 std::cout << "Voy a reemplazar en el nodo " << right << std::endl;
879 /* Reemplazo la clave a borrar por la de la hoja */
880 node_keyr = ReadKeys (node_r, node_hr);
881 BTreeData *reemplazar = *(node_keyr.begin ());
883 std::string ss = *reemplazar;
884 std::cout << "Voy a reemplazar por : " << ss << std::endl;
886 BTreeData *data = new BTreeLeafData (k->Clone());
888 std::list<BTreeData *>::iterator it = node_keys.begin ();
889 while (it != node_keys.end ()) {
890 std::string ss1, ss2;
893 std::cout << ss1 << " == " << ss2 << std::endl;
894 if ((*data) == (*(*it))) {
899 if (it == node_keys.end ()) {
900 std::cout << "PANIC : No encontre la clave en el nodo!!!!\n";
901 std::string s = *data;
902 std::cout << s << std::endl;
903 PrintNode (node_num);
906 (*it)->SetKey (reemplazar->GetKey ());
907 reemplazar->SetKey (k->Clone ());
909 std::cout << "Tengo todo reemplazado ...\n";
911 /* Grabo los nodos */
912 WriteKeys (node, node_header, node_keys);
913 WriteNodoHeader (node, &node_header);
914 WriteBlock (node, node_num);
915 DeleteKeys (node_keys);
918 WriteKeys (node_r, node_hr, node_keyr);
919 WriteNodoHeader (node_r, &node_hr);
920 WriteBlock (node_r, right);
921 DeleteKeys (node_keyr);
924 std::cout << "Grabe todo en disco ...\n";
925 PrintNode (node_num);
927 /* Ahora debo eliminar la clave que puse en el nodo hoja */
928 std::cout << "Borro la clave desde la hoja!\n";
930 DelKeyFromLeaf (k, right, padre_hijo);
932 std::cout << "Listo, Listo!\n";
933 } else if (left != 0) {
934 std::cout << "PANIC : Deberia poder reemplazar en la derecha!!!!!\n";
937 std::cout << "PANIC : No tengo hijos para reemplazar!!!!\n";
942 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
944 memcpy (header, node, sizeof (BTreeNodeHeader));
947 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
949 memcpy (node, header, sizeof (BTreeNodeHeader));
952 uchar *BTree::ReadBlock (uint num)
954 /* Como el bloque 0 se usa para el header, el Nodo "num"
955 * está en el bloque "num+1"
959 uchar *out = new uchar[header.block_size];
961 fseek (fp, num*header.block_size, SEEK_SET);
962 fread (out, 1, header.block_size, fp);
967 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
969 std::list<BTreeData *> keys;
970 node += sizeof (BTreeNodeHeader);
971 uint count = node_header.item_count;
973 if (node_header.item_count == 0) return keys;
975 if (node_header.level != 0) {
976 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
977 BTreeChildData *d = new BTreeChildData (node);
983 for (uint i=0; i<count; i++) {
985 if (node_header.level == 0) {
986 data = new BTreeLeafData (node, key_type);
988 data = new BTreeData (node, key_type);
990 node += data->Size ();
991 keys.push_back (data);
998 void BTree::AbrevKey (std::list<BTreeData *> &lst)
1000 /* Claves Fijas No se abrevian */
1001 if (key_type == KEY_FIXED) return;
1003 BTreeData *primera = NULL;
1004 std::list<BTreeData *>::iterator it = lst.begin ();
1006 while (it != lst.end ()) {
1007 if ((*it)->Abrev (primera) == false)
1013 void BTree::DeAbrevKey (std::list<BTreeData *> &lst)
1015 /* Claves Fijas No se abrevian */
1016 if (key_type == KEY_FIXED) return;
1018 BTreeData *primera = NULL;
1019 std::list<BTreeData *>::iterator it = lst.begin ();
1021 while (it != lst.end ()) {
1022 if ((*it)->DesAbrev (primera) == false)
1028 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
1032 std::list<BTreeData *>::iterator it = keys.begin ();
1034 node += sizeof (BTreeNodeHeader);
1036 node_header.item_count = 0;
1037 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
1040 while (it != keys.end ()) {
1041 BTreeData *d = (*it);
1042 uchar *n = d->ToArray ();
1043 acumulado += d->Size ();
1044 //std::cout << "WriteKeys :: Acumulado = " << acumulado << std::endl;
1045 memcpy (node, n, d->Size ());
1048 node_header.free_space -= d->Size ();
1049 node_header.item_count++;
1056 void BTree::PrintNode (uint num)
1058 uchar *node = ReadBlock (num);
1059 BTreeNodeHeader node_header;
1060 ReadNodoHeader (node, &node_header);
1062 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
1063 std::list<BTreeData *>::iterator it = node_keys.begin ();
1065 std::cout << "Nodo : " << num << std::endl;
1066 std::cout << "Level : " << node_header.level << std::endl;
1067 std::cout << "Items : " << node_header.item_count << std::endl;
1068 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
1069 while (it != node_keys.end ()) {
1070 std::string s = *(*it);
1071 std::cout << s << " ";
1074 std::cout << std::endl;
1077 DeleteKeys (node_keys);
1080 uchar *BTree::NewBlock (uint &num)
1086 fseek (fp, 0, SEEK_END);
1087 filelen = ftell (fp);
1089 num = filelen/header.block_size - 1;
1091 node = new uchar[header.block_size];
1092 ReadNodoHeader (node, &nh);
1094 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
1096 WriteNodoHeader (node, &nh);
1097 WriteBlock (node, num);
1102 BTreeFindResult *BTree::FindKey (const Clave &k)
1104 return FindKeyR (&k, 0);
1107 BTreeFindResult *BTree::FindKeyR (const Clave *k, uint node_num)
1109 std::list<BTreeData *> node_keys;
1110 BTreeNodeHeader node_header;
1112 /* Leo el nodo raiz para empezar a agregar */
1113 uchar *node = ReadBlock (node_num);
1114 ReadNodoHeader (node, &node_header);
1115 node_keys = ReadKeys (node, node_header);
1117 std::list<BTreeData *>::iterator it = node_keys.begin ();
1118 std::list<BTreeData *>::iterator posterior;
1119 std::list<BTreeData *>::iterator ultima;
1121 /* Se supone que la primera es un hijo :) */
1123 if (node_header.level != 0) {
1129 if (node_header.level == 0)
1130 data = new BTreeLeafData (k->Clone ());
1132 data = new BTreeData (k->Clone (), 0);
1134 while (it != node_keys.end ()) {
1135 if ((*data) == (*(*it))) {
1136 /* La encontre!, retorno */
1139 DeleteKeys (node_keys);
1140 BTreeFindResult *result = new BTreeFindResult ();
1141 result->node = node_num;
1142 result->header = node_header;
1147 if ((*data) < (*(*it)))
1155 /* Si llego aca y estoy en nivel 0 (una hoja) quiere
1156 * decir que no lo encontré
1158 if (node_header.level == 0) {
1159 DeleteKeys (node_keys);
1164 /* TODO: Aca faltaria liberar memoria */
1165 BTreeFindResult *ret;
1166 if (it == posterior)
1167 ret = FindKeyR (k, lchild->GetChild ());
1169 ret = FindKeyR (k, (*ultima)->GetChild ());
1171 DeleteKeys (node_keys);
1176 void BTree::DeleteKeys (std::list<BTreeData *> &keys)
1178 std::list<BTreeData *>::iterator it = keys.begin ();
1180 while (it != keys.end ()) {
1181 BTreeData *d = (*it);