Debug swcsa
[SXSI/TextCollection.git] / BlockArray.h
1 #ifndef _BLOCK_ARRAY_H_
2 #define _BLOCK_ARRAY_H_
3 #include "Tools.h"
4 #include <iostream>
5 #include <stdexcept>
6
7 class BlockArray
8 {
9 private:
10     ulong* data;
11     ulong n;
12     ulong index;
13     ulong blockLength;
14 public:
15     BlockArray(ulong len, ulong blockLen) {
16        n = len;
17        blockLength = blockLen;
18        data = new ulong[n*blockLength/W +1];
19        for (ulong i = 0; i < n*blockLength/W +1; ++i)
20            data[i] = 0;
21     }
22     ~BlockArray() {
23        delete [] data;
24     }
25
26     BlockArray& operator[](ulong i)  {
27        index = i;
28        return *this;
29     }  
30
31     void operator=(const ulong x) {
32        Tools::SetField(data,blockLength,index,x);
33     }  
34
35     BlockArray& operator=(const BlockArray& ba) {
36        if (this == &ba) return *this;
37        ulong value = Tools::GetField(ba.data, ba.blockLength, ba.index);
38        Tools::SetField(data,blockLength,index,value);
39        return *this;
40     }  
41         
42     operator ulong() {
43        return Tools::GetField(data,blockLength,index);
44     }
45     
46     ulong spaceInBits() {
47         return n*blockLength+W; // plus 4 ulong's
48     }
49
50     /**
51      * Saving data fields:
52      *     ulong n;
53      *     ulong blockLength;
54      *     ulong* data;
55      */
56     void Save(FILE *file) const
57     {
58         if (std::fwrite(&(this->n), sizeof(ulong), 1, file) != 1)
59             throw std::runtime_error("BlockArray::Save(): file write error (n).");
60         if (std::fwrite(&(this->blockLength), sizeof(ulong), 1, file) != 1)
61             throw std::runtime_error("BlockArray::Save(): file write error (blockLength).");
62     
63         if (std::fwrite(this->data, sizeof(ulong), n*blockLength/W+1, file) != n*blockLength/W+1)
64             throw std::runtime_error("BlockArray::Save(): file write error (data).");
65     }
66
67     /**
68      * Load from file
69      */
70     BlockArray(FILE *file)
71     {
72         if (std::fread(&(this->n), sizeof(ulong), 1, file) != 1)
73             throw std::runtime_error("BlockArray::Load(): file read error (n).");
74         if (std::fread(&(this->blockLength), sizeof(ulong), 1, file) != 1)
75             throw std::runtime_error("BlockArray::Load(): file read error (blockLength).");
76
77         data = new ulong[n*blockLength/W+1];
78         if (std::fread(this->data, sizeof(ulong), n*blockLength/W+1, file) != n*blockLength/W+1)
79             throw std::runtime_error("BlockArray::Load(): file read error (data).");
80     }
81 };
82
83 #endif
84