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.Clone (), 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++)->getClave (); // 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)->getClave (); // 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->getClave (), 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->getClave (), 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 node_keys.erase (it);
490 /* TODO : que pasa cuando el nodo se queda vacio o con
493 WriteKeys (node, node_header, node_keys);
494 WriteNodoHeader (node, &node_header);
495 WriteBlock (node, node_num);
497 /* Veo si se cumple la condición de minimalidad */
498 uint min_free = (header.block_size-sizeof(BTreeNodeHeader))/2;
499 if ((node_header.free_space > min_free) && (node_num != 0)) {
500 /* Oops! Debo pedir prestada clave */
504 FindBrothers (node_num, padre, hi, hd);
506 if ((pedida = GetKey (hi, 1)) != NULL) {
507 std::string s = *pedida;
508 std::cout << "Clave Pedida : " << s << std::endl;
510 pedida = ReplaceKeyInFather (node_num, padre, pedida);
512 node_keys.insert (node_keys.begin (), new BTreeLeafData (pedida));
513 } else if ((pedida = GetKey (hd, 0)) != NULL) {
514 std::string s = *pedida;
515 std::cout << "Clave Pedida : " << s << std::endl;
517 pedida = ReplaceKeyInFather (node_num, padre, pedida);
519 node_keys.push_back (new BTreeLeafData (pedida));
521 std::cout << "NADIE ME PUEDE PRESTAR, FUNDIR NODOS\n";
525 std::cout << "Join con Hermano Izquierdo\n";
530 std::cout << "Join con Hermano Derecho\n";
536 JoinNodes (join1, join2, padre, tipoh);
538 DeleteKeys (node_keys);
543 WriteKeys (node, node_header, node_keys);
544 WriteNodoHeader (node, &node_header);
545 WriteBlock (node, node_num);
548 DeleteKeys (node_keys);
550 std::cout << "Borrado de una hoja listo\n";
553 void BTree::JoinNodes (uint node1, uint node2, uint padre, int tipohermano)
555 uchar *n1, *n2, *npadre;
556 BTreeNodeHeader nh1, nh2, nhp;
557 std::list<BTreeData *> nk1, nk2, nkpadre;
559 if (node1 == node2) {
560 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
563 if (node1 == padre) {
564 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
567 if (node2 == padre) {
568 std::cout << "PANIC : No puedo juntar el mismo nodo con si mismo!!\n";
577 n1 = ReadBlock (node1);
578 n2 = ReadBlock (node2);
579 npadre = ReadBlock (padre);
581 ReadNodoHeader (n1, &nh1);
582 ReadNodoHeader (n2, &nh2);
583 ReadNodoHeader (npadre, &nhp);
586 uint tmp = header.block_size - sizeof (BTreeNodeHeader);
587 uint l = tmp - nh1.free_space;
588 l += tmp - nh1.free_space;
591 std::cout << "Espacio ocupado despues de unir : " << l << " de " << tmp << std::endl;
593 nk1 = ReadKeys (n1, nh1);
594 nk2 = ReadKeys (n2, nh2);
595 nkpadre = ReadKeys (npadre, nhp);
597 /* Busco la clave del padre a juntar con los nodos */
598 std::list<BTreeData *>::iterator it = nkpadre.begin ();
599 std::list<BTreeData *>::iterator borrar_padre;
600 std::list<BTreeData *>::iterator sig;
601 std::list<BTreeData *>::iterator anterior = it;
604 BTreeData *lchild = (*it++);
606 if (lchild->getChild () == node1) {
607 cpadre = (*it)->getClave ();
610 while (it != nkpadre.end ()) {
611 if (tipohermano == 0) {
612 if ((*it)->getChild () == node2)
615 if ((*it)->getChild () == node1)
621 cpadre = (*it)->getClave ();
624 if (it == nkpadre.end ()) {
625 std::cout << "PANIC : Me pase sin encontrar la clave!!\n";
631 std::list<BTreeData *> newkeys;
632 std::list<BTreeData *>::iterator i;
635 while (i != nk1.end ()) {
636 newkeys.push_back ( new BTreeLeafData ((*i)->getClave ()->Clone ()));
639 //if (tipohermano == 0)
640 newkeys.push_back ( new BTreeLeafData (cpadre->Clone ()));
642 while (i != nk2.end ()) {
643 newkeys.push_back ( new BTreeLeafData ((*i)->getClave ()->Clone ()));
647 std::cout << "Espacio ocupado por las nuevas claves : " << (newkeys.size()*4) << std::endl;
648 if ((newkeys.size()*4) > tmp) {
649 std::cout << "PANIC : El nodo fundido no entra !!!\n";
653 /* Para el padre, tener 2 items significa tener solo 1 clave, ya que
654 * el otro item es el LeftChild!
656 if ((padre == 0) && (nhp.item_count == 2)) {
657 /* Si junte 2 nodos, cuyo padre era la raiz, y esta tenia
658 * solo una clave, quiere decir que lo que me queda
659 * es de nuevo solo una raiz con todas las claves
662 WriteKeys (npadre, nhp, newkeys);
663 WriteNodoHeader (npadre, &nhp);
664 WriteBlock (npadre, padre);
666 /* TODO: Recuperar nodo1 y nodo2 */
668 WriteKeys (n1, nh1, newkeys);
669 WriteNodoHeader (n1, &nh1);
670 WriteBlock (n1, node1);
672 /* TODO : Recuperar node2 */
673 /* Actualizo punero al padre */
674 (*anterior)->setChild (node1);
676 nkpadre.erase (borrar_padre);
677 WriteKeys (npadre, nhp, nkpadre);
678 WriteNodoHeader (npadre, &nhp);
679 WriteBlock (npadre, padre);
682 std::cout << " ----- Luego de Fundir -----\n";
685 std::cout << " ---------------------------\n";
689 DeleteKeys (nkpadre);
690 DeleteKeys (newkeys);
697 Clave *BTree::GetKey (uint node_num, char maxmin)
700 std::cout << "Nodo no me puede prestar ... es NULL\n";
705 BTreeNodeHeader node_header;
706 std::list<BTreeData *> node_keys;
708 node = ReadBlock (node_num);
709 ReadNodoHeader (node, &node_header);
710 node_keys = ReadKeys (node, node_header);
712 std::list<BTreeData *>::iterator it = node_keys.begin ();
714 if (node_header.level != 0) it++;
717 uint free = node_header.free_space; // + (*it)->Size ();
718 uint min_free = (header.block_size - sizeof (BTreeNodeHeader))/2;
719 if (free > min_free) {
720 std::cout << "No puedo prestar : Free = " << free << " Minimo = " << min_free << std::endl;
721 PrintNode (node_num);
722 WriteKeys (node, node_header, node_keys);
723 WriteNodoHeader (node, &node_header);
724 WriteBlock (node, node_num);
725 DeleteKeys (node_keys);
733 k = (*it)->getClave ()->Clone ();
734 node_keys.erase (it);
736 it = node_keys.end ();
738 k = (*it)->getClave ()->Clone ();
739 node_keys.erase (it);
742 WriteKeys (node, node_header, node_keys);
743 WriteNodoHeader (node, &node_header);
744 WriteBlock (node, node_num);
745 DeleteKeys (node_keys);
752 void BTree::FindBrothers (uint node_num, uint padre, uint &left, uint &right)
755 BTreeNodeHeader node_header;
756 std::list<BTreeData *> node_keys;
758 node = ReadBlock (padre);
759 ReadNodoHeader (node, &node_header);
760 node_keys = ReadKeys (node, node_header);
762 std::list<BTreeData *>::iterator it = node_keys.begin ();
763 std::list<BTreeData *>::iterator anterior = node_keys.begin ();
764 std::list<BTreeData *>::iterator siguiente;
766 BTreeData *lchild = (*it++);
768 if (lchild->getChild () == node_num) {
769 /* Solo tengo hermano derecho */
770 std::cout << "Hermano Izquierdo : NO TENGO" << std::endl;
772 std::cout << "Hermano Derecho : " << (*it)->getChild () << std::endl;
773 right = (*it)->getChild ();
777 while (it != node_keys.end ()) {
778 if ((*it)->getChild () == node_num)
785 std::cout << "Hermano Izquierdo : " << (*anterior)->getChild () << std::endl;
786 left = (*anterior)->getChild ();
787 if (siguiente != node_keys.end ()) {
788 right = (*siguiente)->getChild ();
789 std::cout << "Hermano Derecho : " << (*siguiente)->getChild () << std::endl;
792 std::cout << "Hermano Derecho : NO TENGO" << std::endl;
796 Clave *BTree::ReplaceKeyInFather (uint node_num, uint padre, Clave *k)
799 BTreeNodeHeader node_header;
800 std::list<BTreeData *> node_keys;
802 node = ReadBlock (padre);
803 ReadNodoHeader (node, &node_header);
804 node_keys = ReadKeys (node, node_header);
806 std::list<BTreeData *>::iterator it = node_keys.begin ();
807 std::list<BTreeData *>::iterator anterior = node_keys.begin ();
808 std::list<BTreeData *>::iterator siguiente;
810 BTreeData *lchild = (*it++);
812 if (lchild->getChild () == node_num) {
813 Clave *ret = (*it)->getClave ();
816 WriteKeys (node, node_header, node_keys);
817 WriteNodoHeader (node, &node_header);
818 WriteBlock (node, padre);
819 DeleteKeys (node_keys);
825 while (it != node_keys.end ()) {
826 if ((*it)->getChild () == node_num)
832 Clave *ret = (*it)->getClave ();
835 WriteKeys (node, node_header, node_keys);
836 WriteNodoHeader (node, &node_header);
837 WriteBlock (node, padre);
838 DeleteKeys (node_keys);
844 void BTree::DelKeyFromNode (Clave *k, uint node_num, uint padre, uint left, uint right)
848 BTreeNodeHeader node_header;
849 std::list<BTreeData *> node_keys;
851 node = ReadBlock (node_num);
852 ReadNodoHeader (node, &node_header);
853 node_keys = ReadKeys (node, node_header);
856 std::cout << "Busco para la derecha y luego todo a la izquierda\n";
858 BTreeNodeHeader node_hr;
859 std::list<BTreeData *> node_keyr;
861 /* Busco la clave inmediatamente superior en el arbol */
862 padre_hijo = node_num;
864 node_r = ReadBlock (right);
865 ReadNodoHeader (node_r, &node_hr);
866 if (node_hr.level != 0) {
868 node_keyr = ReadKeys (node_r, node_hr);
869 data_r = *(node_keyr.begin ());
871 right = data_r->getChild ();
873 DeleteKeys (node_keyr);
876 } while (node_hr.level != 0);
878 std::cout << "Voy a reemplazar en el nodo " << right << std::endl;
880 /* Reemplazo la clave a borrar por la de la hoja */
881 node_keyr = ReadKeys (node_r, node_hr);
882 BTreeData *reemplazar = *(node_keyr.begin ());
884 std::string ss = *reemplazar;
885 std::cout << "Voy a reemplazar por : " << ss << std::endl;
887 BTreeData *data = new BTreeLeafData (k->Clone());
889 std::list<BTreeData *>::iterator it = node_keys.begin ();
890 while (it != node_keys.end ()) {
891 std::string ss1, ss2;
894 std::cout << ss1 << " == " << ss2 << std::endl;
895 if ((*data) == (*(*it))) {
900 if (it == node_keys.end ()) {
901 std::cout << "PANIC : No encontre la clave en el nodo!!!!\n";
902 std::string s = *data;
903 std::cout << s << std::endl;
904 PrintNode (node_num);
907 (*it)->setClave (reemplazar->getClave ());
908 reemplazar->setClave (k->Clone ());
910 std::cout << "Tengo todo reemplazado ...\n";
912 /* Grabo los nodos */
913 WriteKeys (node, node_header, node_keys);
914 WriteNodoHeader (node, &node_header);
915 WriteBlock (node, node_num);
916 DeleteKeys (node_keys);
919 WriteKeys (node_r, node_hr, node_keyr);
920 WriteNodoHeader (node_r, &node_hr);
921 WriteBlock (node_r, right);
922 DeleteKeys (node_keyr);
925 std::cout << "Grabe todo en disco ...\n";
926 PrintNode (node_num);
928 /* Ahora debo eliminar la clave que puse en el nodo hoja */
929 std::cout << "Borro la clave desde la hoja!\n";
931 DelKeyFromLeaf (k, right, padre_hijo);
933 std::cout << "Listo, Listo!\n";
934 } else if (left != 0) {
935 std::cout << "PANIC : Deberia poder reemplazar en la derecha!!!!!\n";
938 std::cout << "PANIC : No tengo hijos para reemplazar!!!!\n";
943 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
945 memcpy (header, node, sizeof (BTreeNodeHeader));
948 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
950 memcpy (node, header, sizeof (BTreeNodeHeader));
953 uchar *BTree::ReadBlock (uint num)
955 /* Como el bloque 0 se usa para el header, el Nodo "num"
956 * está en el bloque "num+1"
960 uchar *out = new uchar[header.block_size];
962 fseek (fp, num*header.block_size, SEEK_SET);
963 fread (out, 1, header.block_size, fp);
968 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
970 std::list<BTreeData *> keys;
971 node += sizeof (BTreeNodeHeader);
972 uint count = node_header.item_count;
974 if (node_header.item_count == 0) return keys;
976 if (node_header.level != 0) {
977 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
978 BTreeChildData *d = new BTreeChildData (node);
984 for (uint i=0; i<count; i++) {
985 /* TODO : El tipo de clave deberia ser usado
986 * dependiendo de algun dato en el header del
989 /* TODO : Detectar si estoy en una hoja */
991 if (node_header.level == 0) {
992 data = new BTreeLeafData (node, key_type);
994 data = new BTreeData (node, key_type);
996 node += data->Size ();
997 keys.push_back (data);
1004 void BTree::AbrevKey (std::list<BTreeData *> &lst)
1006 /* Claves Fijas No se abrevian */
1007 if (key_type == KEY_FIXED) return;
1009 BTreeData *primera = NULL;
1010 std::list<BTreeData *>::iterator it = lst.begin ();
1012 while (it != lst.end ()) {
1013 if ((*it)->Abrev (primera) == false)
1019 void BTree::DeAbrevKey (std::list<BTreeData *> &lst)
1021 /* Claves Fijas No se abrevian */
1022 if (key_type == KEY_FIXED) return;
1024 BTreeData *primera = NULL;
1025 std::list<BTreeData *>::iterator it = lst.begin ();
1027 while (it != lst.end ()) {
1028 if ((*it)->DesAbrev (primera) == false)
1034 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
1038 std::list<BTreeData *>::iterator it = keys.begin ();
1040 node += sizeof (BTreeNodeHeader);
1042 node_header.item_count = 0;
1043 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
1046 while (it != keys.end ()) {
1047 BTreeData *d = (*it);
1048 uchar *n = d->ToArray ();
1049 acumulado += d->Size ();
1050 //std::cout << "WriteKeys :: Acumulado = " << acumulado << std::endl;
1051 memcpy (node, n, d->Size ());
1054 node_header.free_space -= d->Size ();
1055 node_header.item_count++;
1062 void BTree::PrintNode (uint num)
1064 uchar *node = ReadBlock (num);
1065 BTreeNodeHeader node_header;
1066 ReadNodoHeader (node, &node_header);
1068 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
1069 std::list<BTreeData *>::iterator it = node_keys.begin ();
1071 std::cout << "Nodo : " << num << std::endl;
1072 std::cout << "Level : " << node_header.level << std::endl;
1073 std::cout << "Items : " << node_header.item_count << std::endl;
1074 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
1075 while (it != node_keys.end ()) {
1076 std::string s = *(*it);
1077 std::cout << s << " ";
1080 std::cout << std::endl;
1083 DeleteKeys (node_keys);
1086 uchar *BTree::NewBlock (uint &num)
1092 fseek (fp, 0, SEEK_END);
1093 filelen = ftell (fp);
1095 num = filelen/header.block_size - 1;
1097 node = new uchar[header.block_size];
1098 ReadNodoHeader (node, &nh);
1100 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
1102 WriteNodoHeader (node, &nh);
1103 WriteBlock (node, num);
1108 BTreeFindResult *BTree::FindKey (const Clave &k)
1110 return FindKeyR (&k, 0);
1113 BTreeFindResult *BTree::FindKeyR (const Clave *k, uint node_num)
1115 std::list<BTreeData *> node_keys;
1116 BTreeNodeHeader node_header;
1118 /* Leo el nodo raiz para empezar a agregar */
1119 uchar *node = ReadBlock (node_num);
1120 ReadNodoHeader (node, &node_header);
1121 node_keys = ReadKeys (node, node_header);
1123 std::list<BTreeData *>::iterator it = node_keys.begin ();
1124 std::list<BTreeData *>::iterator posterior;
1125 std::list<BTreeData *>::iterator ultima;
1127 /* Se supone que la primera es un hijo :) */
1129 if (node_header.level != 0) {
1135 if (node_header.level == 0)
1136 data = new BTreeLeafData (k->Clone ());
1138 data = new BTreeData (k->Clone (), 0);
1140 while (it != node_keys.end ()) {
1141 if ((*data) == (*(*it))) {
1142 /* La encontre!, retorno */
1144 DeleteKeys (node_keys);
1145 BTreeFindResult *result = new BTreeFindResult ();
1146 result->node = node_num;
1147 result->header = node_header;
1151 if ((*data) < (*(*it)))
1157 /* Si llego aca y estoy en nivel 0 (una hoja) quiere
1158 * decir que no lo encontré
1160 if (node_header.level == 0) {
1165 /* TODO: Aca faltaria liberar memoria */
1166 if (it == posterior)
1167 return FindKeyR (k, lchild->getChild ());
1169 return FindKeyR (k, (*ultima)->getChild ());
1172 void BTree::DeleteKeys (std::list<BTreeData *> &keys)
1174 std::list<BTreeData *>::iterator it = keys.begin ();
1176 while (it != keys.end ()) {
1177 BTreeData *d = (*it);