Debug swcsa
[SXSI/TextCollection.git] / Tools.cpp
1 /*
2  * Collection of basic tools and defines
3  */
4
5 #include "Tools.h"
6 #include <cstdio>
7
8
9 time_t Tools::startTime;
10
11 void Tools::StartTimer()
12 {
13     startTime = time(NULL);
14 }
15
16 double Tools::GetTime()
17 {
18     time_t stopTime = time(NULL);
19     return difftime( stopTime, startTime );
20 }
21
22 uchar * Tools::GetRandomString(unsigned min, unsigned max, unsigned &alphabetSize)
23 {
24     unsigned len = std::rand() % (max - min) + min;
25     alphabetSize = std::rand() % 26 + 1;
26     uchar* temp = new uchar[len + 2];
27     for (unsigned i = 0; i < len; i++)
28         temp[i] = 97 + std::rand() % alphabetSize;
29     temp[len] = 0u ;temp[len+1] = '\0';
30     return temp;
31 }
32
33
34 void Tools::PrintBitSequence(ulong *A, ulong len)
35 {
36     for(ulong i = 0; i < len; i++)
37         if (GetField(A, 1, i))
38             std::cout << "1";
39         else
40             std::cout << "0";
41     std::cout << "\n";
42 }
43
44 unsigned Tools::FloorLog2(ulong i)
45 {
46     unsigned b = 0;
47     if (i == 0)
48         return 0;
49     while (i)
50     { 
51         b++; 
52         i >>= 1; 
53     }
54     return b - 1;
55 }
56
57 unsigned Tools::CeilLog2(ulong i)
58 {
59     unsigned j = FloorLog2(i);
60     if ((ulong)(1lu << j) != i)
61         return j + 1;
62         
63     return j;
64 }
65
66 uchar * Tools::GetFileContents(char *filename, ulong maxSize)
67 {
68     std::ifstream::pos_type posSize;
69     std::ifstream file ((char *)filename, std::ios::in|std::ios::binary|std::ios::ate);
70     if (file.is_open())
71     {
72         posSize = file.tellg();
73         ulong size = posSize;
74         if (maxSize != 0 && size > maxSize)
75             size = maxSize;
76         char *memblock = new char [size + 1];
77         file.seekg (0, std::ios::beg);
78         file.read (memblock, size);
79         memblock[size] = '\0';
80         file.close();
81         return (uchar *)memblock;
82     }
83     else
84         return 0;
85 }
86
87 unsigned Tools::bits (ulong n)
88
89    { unsigned b = 0;
90      while (n)
91     { b++; n >>= 1; }
92      return b;
93    }
94
95