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)
53 std::list<Clave *> node_keys;
55 /* Leo el nodo raiz para empezar a agregar */
56 uchar *root = ReadBlock (0);
57 BTreeNodeHeader root_header;
58 ReadNodoHeader (root, &root_header);
60 node_keys = ReadKeys (root, root_header);
61 std::cout << node_keys.size () << std::endl;
63 if (root_header.free_space >= k.Size ()) {
64 std::cout << "Hay lugar para meter la clave" << std::endl;
65 /* TODO : Insertar ordenado */
66 node_keys.push_back (k.Clone ());
68 std::cout << "__NO__ hay lugar para meter la clave" << std::endl;
72 WriteKeys (root, root_header, node_keys);
73 WriteNodoHeader (root, &root_header);
79 void BTree::DelKey (const Clave &k) {}
81 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
83 memcpy (header, node, sizeof (BTreeNodeHeader));
86 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
88 memcpy (node, header, sizeof (BTreeNodeHeader));
91 uchar *BTree::ReadBlock (uint num)
93 uchar *out = new uchar[header.block_size];
95 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
96 fread (out, 1, header.block_size, fp);
101 std::list<Clave *> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
103 std::list<Clave *> keys;
104 node += sizeof (BTreeNodeHeader);
106 for (uint i=0; i<node_header.item_count; i++) {
107 /* TODO : El tipo de clave deberia ser usado
108 * dependiendo de algun dato en el header del
111 ClaveFija *k = new ClaveFija (node);
119 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<Clave *> &keys)
121 std::list<Clave *>::iterator it = keys.begin ();
123 node += sizeof (BTreeNodeHeader);
125 while (it != keys.end ()) {
127 memcpy (node, c->ToArray(), c->Size ());
132 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */