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)
56 Clave* BTree::AddKeyR (const Clave *k, uint node_num)
59 std::list<BTreeData> node_keys;
61 /* Leo el nodo raiz para empezar a agregar */
62 uchar *node = ReadBlock (node_num);
63 BTreeNodeHeader node_header;
64 ReadNodoHeader (node, &node_header);
66 node_keys = ReadKeys (node, node_header);
68 if (node_header.free_space >= k->Size ()) {
69 /* TODO : Insertar ordenado */
70 //node_keys.push_back (BTreek->Clone ());
76 WriteKeys (node, node_header, node_keys);
77 WriteNodoHeader (node, &node_header);
78 WriteBlock (node, node_num);
85 void BTree::DelKey (const Clave &k) {}
87 void BTree::ReadNodoHeader (uchar *node, BTreeNodeHeader *header)
89 memcpy (header, node, sizeof (BTreeNodeHeader));
92 void BTree::WriteNodoHeader (uchar *node, BTreeNodeHeader *header)
94 memcpy (node, header, sizeof (BTreeNodeHeader));
97 uchar *BTree::ReadBlock (uint num)
99 uchar *out = new uchar[header.block_size];
101 fseek (fp, num*header.block_size + sizeof (BTreeFileHeader), SEEK_SET);
102 fread (out, 1, header.block_size, fp);
107 std::list<BTreeData> BTree::ReadKeys (uchar *node, BTreeNodeHeader &node_header)
109 std::list<BTreeData> keys;
110 node += sizeof (BTreeNodeHeader);
112 for (uint i=0; i<node_header.item_count; i++) {
113 /* TODO : El tipo de clave deberia ser usado
114 * dependiendo de algun dato en el header del
117 /* TODO : Detectar si estoy en una hoja */
118 BTreeData data(node);
119 node += data.Size ();
120 keys.push_back (data);
126 void BTree::WriteKeys (uchar *node, BTreeNodeHeader &node_header, std::list<BTreeData> &keys)
128 std::list<BTreeData>::iterator it = keys.begin ();
130 node += sizeof (BTreeNodeHeader);
132 while (it != keys.end ()) {
134 memcpy (node, d.ToArray(), d.Size ());
139 /* TODO : incrementar node_header.item_count aca o fuera de este metodo? */