4 BTree::BTree (const std::string &name, unsigned int block_size, bool create_new_file)
9 fp = fopen (name.c_str(), "wb+");
11 /* TODO : mandar una exception ? */
15 /* Nombre de archivo */
18 /* Inicializo el header */
19 header.block_size = block_size;
22 /* Creo el primer bloque vacio */
23 node = new uchar[block_size];
24 ReadNodoHeader (node, &nh);
26 nh.free_space = block_size - sizeof (BTreeNodeHeader);
28 WriteNodoHeader (node, &nh);
39 void BTree::WriteFileHeader ()
41 fseek (fp, 0L, SEEK_SET);
42 fwrite (&header, 1, sizeof (BTreeFileHeader), fp);
45 void BTree::WriteBlock (uchar *block, uint num)
47 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
48 fwrite (block, 1, header.block_size, fp);
51 void BTree::AddKey (const Clave &k)
54 Clave *kout = AddKeyR (&k, 0, left, right);
58 /* Debo dejar la raiz en el nodo 0, por lo que paso el nodo
59 * que esta usando el hijo izquierdo a un nuevo nodo */
60 std::list<BTreeData *> node_keys;
61 BTreeNodeHeader node_header;
62 uchar *node = ReadBlock (left);
63 ReadNodoHeader (node, &node_header);
64 node_keys = ReadKeys (node, node_header);
65 level = node_header.level + 1;
67 uchar *new_node = NewBlock (left);
68 delete [] new_node; /* No me interesa, voy a usar lo leio antes */
70 WriteKeys (node, node_header, node_keys);
71 WriteNodoHeader (node, &node_header);
72 WriteBlock (node, left);
75 /* Leo y actualizo la Raiz */
77 ReadNodoHeader (node, &node_header);
78 node_keys = std::list<BTreeData *>();
80 node_keys.push_back (new BTreeChildData (left));
81 node_keys.push_back (new BTreeData (kout, right));
83 node_header.level = level;
84 node_header.item_count = 1;
86 WriteKeys (node, node_header, node_keys);
87 WriteNodoHeader (node, &node_header);
93 Clave* BTree::AddKeyR (const Clave *k, uint node_num, uint &left_child, uint &right_child)
96 std::list<BTreeData *> node_keys;
98 BTreeData *data = new BTreeLeafData (k->Clone ());
100 /* Leo el nodo raiz para empezar a agregar */
101 uchar *node = ReadBlock (node_num);
102 BTreeNodeHeader node_header;
103 ReadNodoHeader (node, &node_header);
105 if (node_header.level != 0) {
106 /* No estoy en una hoja, asi que tengo que buscar
107 * para donde moverme para agregar la clave
110 node_keys = ReadKeys (node, node_header);
111 std::list<BTreeData *>::iterator it = node_keys.begin ();
113 /* Se supone que la primera es un hijo :) */
114 //BTreeData *left_child = (*it);
115 PrintNode (node_num);
116 std::cout << "TODO!!" << std::endl;
121 /* Estoy en una hoja, veo si lo puedo agregar */
123 if (node_header.free_space > data->Size ()) {
124 /* TODO : Insertar ordenado */
126 node_keys = ReadKeys (node, node_header);
127 std::list<BTreeData *>::iterator it = node_keys.begin ();
129 while (it != node_keys.end ()) {
131 if ((*data) < (*datait))
132 /* Me pase, lo agrego aca! */
136 node_keys.insert (it, data);
137 WriteKeys (node, node_header, node_keys);
138 WriteNodoHeader (node, &node_header);
139 WriteBlock (node, node_num);
141 PrintNode (node_num);
143 std::cout << "=============== SPLIT ================" << std::endl;
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);
152 node_keys = ReadKeys (node, node_header);
153 new_node_keys = ReadKeys (new_node, new_node_header);
155 /* Agrego la clave en la lista que ya tengo de manera ordenada */
156 std::list<BTreeData *>::iterator it = node_keys.begin ();
158 while (it != node_keys.end ()) {
161 if ((*data) < (*datait))
162 /* Me pase, lo agrego aca! */
166 if (it != node_keys.end ())
167 node_keys.insert (it, data);
169 node_keys.push_back (data);
171 /* Tengo que guardar claves hasta ocupar nodo size/2 en cada nodo
172 * y subir la clave del medio */
173 node_header.item_count = 0;
174 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
177 it = node_keys.begin ();
178 while (it != node_keys.end ()) {
181 total_size += datait->Size ();
183 /* Hack : Si me quedo con todas las claves, en el caso de ser
184 * del mismo tama#o se desbalancea. Hay que ver que efecto
185 * puede tener en el caso de claves de long. variable
187 if (it == node_keys.end ())
188 total_size -= datait->Size ();
191 it = node_keys.begin ();
193 while (used < total_size/2) {
194 BTreeData *d = (*it);
195 old_node_keys.push_back (d);
199 kout = (*it++)->getClave (); // Esta se retorna al "padre" para que se la agregue
200 while (it != node_keys.end ()) {
201 BTreeData *d = (*it);
202 new_node_keys.push_back (d);
207 WriteKeys (node, node_header, old_node_keys);
208 WriteNodoHeader (node, &node_header);
209 WriteBlock (node, node_num);
210 WriteKeys (new_node, new_node_header, new_node_keys);
211 WriteNodoHeader (new_node, &new_node_header);
212 WriteBlock (new_node, new_node_num);
214 PrintNode (node_num);
215 PrintNode (new_node_num);
218 left_child = node_num;
219 right_child = new_node_num;
227 void BTree::DelKey (const Clave &k) {}
229 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
231 memcpy (header, node, sizeof (BTreeNodeHeader));
234 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
236 memcpy (node, header, sizeof (BTreeNodeHeader));
239 uchar *BTree::ReadBlock (uint num)
241 uchar *out = new uchar[header.block_size];
243 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
244 fread (out, 1, header.block_size, fp);
249 std::list<BTreeData *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
251 std::list<BTreeData *> keys;
252 node += sizeof (BTreeNodeHeader);
254 if (node_header.item_count == 0) return keys;
256 if (node_header.level != 0) {
257 /* Si no es una hoja, lo primero que tengo es un BTreeChildData */
258 BTreeChildData *d = new BTreeChildData (node);
263 for (uint i=0; i<node_header.item_count; i++) {
264 /* TODO : El tipo de clave deberia ser usado
265 * dependiendo de algun dato en el header del
268 /* TODO : Detectar si estoy en una hoja */
270 if (node_header.level == 0) {
271 data = new BTreeLeafData (node);
273 data = new BTreeData (node);
275 node += data->Size ();
276 keys.push_back (data);
282 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData *> &keys)
284 std::list<BTreeData *>::iterator it = keys.begin ();
286 node += sizeof (BTreeNodeHeader);
288 node_header.item_count = 0;
289 node_header.free_space = header.block_size - sizeof (BTreeNodeHeader);
291 while (it != keys.end ()) {
292 BTreeData *d = (*it);
293 memcpy (node, d->ToArray(), d->Size ());
295 node_header.free_space -= d->Size ();
296 node_header.item_count++;
300 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */
303 void BTree::PrintNode (uint num)
305 uchar *node = ReadBlock (num);
306 BTreeNodeHeader node_header;
307 ReadNodoHeader (node, &node_header);
309 std::list<BTreeData *> node_keys = ReadKeys (node, node_header);
310 std::list<BTreeData *>::iterator it = node_keys.begin ();
312 std::cout << "Nodo : " << num << std::endl;
313 std::cout << "Level : " << node_header.level << std::endl;
314 std::cout << "Items : " << node_header.item_count << std::endl;
315 std::cout << "Free : " << node_header.free_space << " (" << (header.block_size - sizeof (BTreeNodeHeader)) << ")" << std::endl;
316 while (it != node_keys.end ()) {
317 std::string s = *(*it);
318 std::cout << s << " ";
321 std::cout << std::endl;
326 uchar *BTree::NewBlock (uint &num)
332 fseek (fp, 0, SEEK_END);
333 filelen = ftell (fp);
335 num = (filelen - sizeof (BTreeFileHeader))/header.block_size;
337 node = new uchar[header.block_size];
338 ReadNodoHeader (node, &nh);
340 nh.free_space = header.block_size - sizeof (BTreeNodeHeader);
342 WriteNodoHeader (node, &nh);
343 WriteBlock (node, 0);