ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/gclib/GBase.h
Revision: 179
Committed: Thu Feb 16 16:23:45 2012 UTC (7 years, 1 month ago) by gpertea
File size: 13176 byte(s)
Log Message:
moved bit handling inlines from GBase to GBitVec

Line File contents
1 #ifndef G_BASE_DEFINED
2 #define G_BASE_DEFINED
3 #ifndef _POSIX_SOURCE
4 //mostly for MinGW
5 #define _POSIX_SOURCE
6 #endif
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10 #include <string.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <math.h>
14 #include <limits.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <stdint.h>
18
19 #if defined __WIN32__ || defined WIN32 || defined _WIN32 || defined _WIN32_
20 #ifndef __WIN32__
21 #define __WIN32__
22 #endif
23 #include <windows.h>
24 #include <io.h>
25 #define CHPATHSEP '\\'
26 #undef off_t
27 #define off_t int64_t
28 #ifndef popen
29 #define popen _popen
30 #endif
31 #ifdef _fseeki64
32 #define fseeko(stream, offset, origin) _fseeki64(stream, offset, origin)
33 #else
34 /*
35 #define _DEFINE_WIN32_FSEEKO
36 int fseeko(FILE *stream, off_t offset, int whence);
37 */
38 #define fseeko fseek
39 #endif
40 #ifdef _ftelli64
41 #define ftello(stream) _ftelli64(stream)
42 #else
43 /*
44 #define _DEFINE_WIN32_FTELLO
45 off_t ftello(FILE *stream);
46 */
47 #define ftello ftell
48 #endif
49 #else
50 #define CHPATHSEP '/'
51 #include <unistd.h>
52 #endif
53
54 #ifndef fseeko
55 #define fseeko fseek
56 #endif
57 #ifndef ftello
58 #define ftello ftell
59 #endif
60
61 #ifdef DEBUG
62 #undef NDEBUG
63 #endif
64
65 typedef int32_t int32;
66 typedef uint32_t uint32;
67 typedef int16_t int16;
68 typedef uint16_t uint16;
69
70 typedef unsigned char uchar;
71 typedef unsigned char byte;
72
73 #ifndef MAXUINT
74 #define MAXUINT ((unsigned int)-1)
75 #endif
76
77 #ifndef MAXINT
78 #define MAXINT INT_MAX
79 #endif
80
81 #ifndef MAX_UINT
82 #define MAX_UINT ((unsigned int)-1)
83 #endif
84
85 #ifndef MAX_INT
86 #define MAX_INT INT_MAX
87 #endif
88
89 typedef int64_t int64;
90 typedef uint64_t uint64;
91
92 /****************************************************************************/
93
94 #ifndef EXIT_FAILURE
95 #define EXIT_FAILURE 1
96 #endif
97
98 #ifndef EXIT_SUCCESS
99 #define EXIT_SUCCESS 0
100 #endif
101
102 /****************************************************************************/
103 #define ERR_ALLOC "Error allocating memory.\n"
104
105 //-------------------
106
107 // Debug helpers
108 #ifndef NDEBUG
109 #define GASSERT(exp) ((exp)?((void)0):(void)GAssert(#exp,__FILE__,__LINE__))
110 #ifdef TRACE
111 #define GTRACE(exp) (GMessage exp)
112 #else
113 #define GTRACE(exp) ((void)0)
114 #endif
115 #else
116 #define GASSERT(exp) ((void)0)
117 #define GTRACE(exp) ((void)0)
118 #endif
119
120 #define GERROR(exp) (GError exp)
121 /********************************** Macros ***********************************/
122 // Abolute value
123 #define GABS(val) (((val)>=0)?(val):-(val))
124
125 // Min and Max
126 #define GMAX(a,b) (((a)>(b))?(a):(b))
127 #define GMIN(a,b) (((a)>(b))?(b):(a))
128
129 // Min of three
130 #define GMIN3(x,y,z) ((x)<(y)?GMIN(x,z):GMIN(y,z))
131
132 // Max of three
133 #define GMAX3(x,y,z) ((x)>(y)?GMAX(x,z):GMAX(y,z))
134
135 // Return minimum and maximum of a, b
136 #define GMINMAX(lo,hi,a,b) ((a)<(b)?((lo)=(a),(hi)=(b)):((lo)=(b),(hi)=(a)))
137
138 // Clamp value x to range [lo..hi]
139 #define GCLAMP(lo,x,hi) ((x)<(lo)?(lo):((x)>(hi)?(hi):(x)))
140
141 typedef void* pointer;
142 typedef unsigned int uint;
143
144 typedef int GCompareProc(const pointer item1, const pointer item2);
145 typedef void GFreeProc(pointer item); //usually just delete,
146 //but may also support structures with embedded dynamic members
147
148 #define GMALLOC(ptr,size) if (!GMalloc((pointer*)(&ptr),size)) \
149 GError(ERR_ALLOC)
150 #define GCALLOC(ptr,size) if (!GCalloc((pointer*)(&ptr),size)) \
151 GError(ERR_ALLOC)
152 #define GREALLOC(ptr,size) if (!GRealloc((pointer*)(&ptr),size)) \
153 GError(ERR_ALLOC)
154 #define GFREE(ptr) GFree((pointer*)(&ptr))
155
156 inline char* strMin(char *arg1, char *arg2) {
157 return (strcmp(arg1, arg2) < 0)? arg1 : arg2;
158 }
159
160 inline char* strMax(char *arg1, char *arg2) {
161 return (strcmp(arg2, arg1) < 0)? arg1 : arg2;
162 }
163
164 inline int iround(double x) {
165 return (int)floor(x + 0.5);
166 }
167
168 /****************************************************************************/
169
170 inline int Gintcmp(int a, int b) {
171 //return (a>b)? 1 : ((a==b)?0:-1);
172 return a-b;
173 }
174
175 int Gstrcmp(const char* a, const char* b, int n=-1);
176 //same as strcmp but doesn't crash on NULL pointers
177
178 int Gstricmp(const char* a, const char* b, int n=-1);
179
180 //basic swap template function
181 template<class T> void Gswap(T& lhs, T& rhs) {
182 //register T tmp=lhs;
183 T tmp=lhs; //requires copy operator
184 lhs=rhs;
185 rhs=tmp;
186 }
187
188
189 /**************** Memory management ***************************/
190
191 bool GMalloc(pointer* ptr, unsigned long size); // Allocate memory
192 bool GCalloc(pointer* ptr, unsigned long size); // Allocate and initialize memory
193 bool GRealloc(pointer* ptr,unsigned long size); // Resize memory
194 void GFree(pointer* ptr); // Free memory, resets ptr to NULL
195
196
197 int saprintf(char **retp, const char *fmt, ...);
198
199 void GError(const char* format,...); // Error routine (aborts program)
200 void GMessage(const char* format,...);// Log message to stderr
201 // Assert failed routine:- usually not called directly but through GASSERT
202 void GAssert(const char* expression, const char* filename, unsigned int lineno);
203
204 // ****************** string manipulation *************************
205 char *Gstrdup(const char* str);
206 //duplicate a string by allocating a copy for it and returning it
207 char* Gstrdup(const char* sfrom, const char* sto);
208 //same as GStrdup, but with an early termination (e.g. on delimiter)
209
210 char* Gsubstr(const char* str, char* from, char* to=NULL);
211 //extracts a substring, allocating it, including boundaries (from/to)
212
213 int strsplit(char* str, char** fields, int maxfields, const char* delim);
214 int strsplit(char* str, char** fields, int maxfields, const char delim);
215 int strsplit(char* str, char** fields, int maxfields); //splits by tab or space
216
217 char* replaceStr(char* &str, char* newvalue);
218
219 //conversion: to Lower/Upper case
220 // creating a new string:
221 char* upCase(const char* str);
222 char* loCase(const char* str);
223 // changing string in place:
224 char* strlower(char * str);
225 char* strupper(char * str);
226
227 //strstr but for memory zones: scans a memory region
228 //for a substring:
229 void* Gmemscan(void *mem, unsigned int len,
230 void *part, unsigned int partlen);
231
232 // test if a char is in a string:
233 bool chrInStr(char c, const char* str);
234
235 char* rstrchr(char* str, char ch);
236 /* returns a pointer to the rightmost
237 occurence of ch in str - like rindex for platforms missing it*/
238
239 char* strchrs(const char* s, const char* chrs);
240 //strchr but with a set of chars instead of only one
241
242 char* rstrfind(const char* str, const char *substr);
243 // like rindex() but for strings; right side version of strstr()
244
245 char* reverseChars(char* str, int slen=0); //in place reversal of string
246
247 char* rstrstr(const char* rstart, const char *lend, const char* substr);
248 /*the reversed, rightside equivalent of strstr: starts searching
249 from right end (rstart), going back to left end (lend) and returns
250 a pointer to the last (right) matching character in str */
251
252 char* strifind(const char* str, const char* substr);
253 // the case insensitive version of strstr -- finding a string within a strin
254
255
256 //Determines if a string begins with a given prefix
257 //(returns false when any of the params is NULL,
258 // but true when prefix is '' (empty string)!)
259 bool startsWith(const char* s, const char* prefix);
260
261 bool endsWith(const char* s, const char* suffix);
262 //Note: returns true if suffix is empty string, but false if it's NULL
263
264
265 // ELF hash function for strings
266 int strhash(const char* str);
267
268
269
270 //---- generic base GSeg : genomic segment (interval) --
271 // coordinates are considered 1-based (so 0 is invalid)
272 class GSeg {
273 public:
274 uint start; //start<end always!
275 uint end;
276 GSeg(uint s=0,uint e=0) {
277 if (s>e) { start=e;end=s; }
278 else { start=s;end=e; }
279 }
280 //check for overlap with other segment
281 uint len() { return end-start+1; }
282 bool overlap(GSeg* d) {
283 //return start<d->start ? (d->start<=end) : (start<=d->end);
284 return (start<=d->end && end>=d->start);
285 }
286
287 bool overlap(GSeg& d) {
288 //return start<d.start ? (d.start<=end) : (start<=d.end);
289 return (start<=d.end && end>=d.start);
290 }
291
292 bool overlap(GSeg& d, int fuzz) {
293 //return start<d.start ? (d.start<=end+fuzz) : (start<=d.end+fuzz);
294 return (start<=d.end+fuzz && end+fuzz>=d.start);
295 }
296
297 bool overlap(uint s, uint e) {
298 if (s>e) { Gswap(s,e); }
299 //return start<s ? (s<=end) : (start<=e);
300 return (start<=e && end>=s);
301 }
302
303 //return the length of overlap between two segments
304 int overlapLen(GSeg* r) {
305 if (start<r->start) {
306 if (r->start>end) return 0;
307 return (r->end>end) ? end-r->start+1 : r->end-r->start+1;
308 }
309 else { //r->start<=start
310 if (start>r->end) return 0;
311 return (r->end<end)? r->end-start+1 : end-start+1;
312 }
313 }
314 int overlapLen(uint rstart, uint rend) {
315 if (rstart>rend) { Gswap(rstart,rend); }
316 if (start<rstart) {
317 if (rstart>end) return 0;
318 return (rend>end) ? end-rstart+1 : rend-rstart+1;
319 }
320 else { //rstart<=start
321 if (start>rend) return 0;
322 return (rend<end)? rend-start+1 : end-start+1;
323 }
324 }
325
326 //fuzzy coordinate matching:
327 bool coordMatch(GSeg* s, uint fuzz=0) {
328 if (fuzz==0) return (start==s->start && end==s->end);
329 uint sd = (start>s->start) ? start-s->start : s->start-start;
330 uint ed = (end>s->end) ? end-s->end : s->end-end;
331 return (sd<=fuzz && ed<=fuzz);
332 }
333 //comparison operators required for sorting
334 bool operator==(GSeg& d){
335 return (start==d.start && end==d.end);
336 }
337 bool operator<(GSeg& d){
338 return (start==d.start)?(end<d.end):(start<d.start);
339 }
340 };
341
342
343
344 //--------------------------------------------------------
345 // ************** simple line reading class for text files
346
347 //GLineReader -- text line reading/buffering class
348 class GLineReader {
349 bool closeFile;
350 int len;
351 int allocated;
352 char* buf;
353 bool isEOF;
354 FILE* file;
355 off_t filepos; //current position
356 bool pushed; //pushed back
357 int lcount; //line counter (read lines)
358 public:
359 char* chars() { return buf; }
360 char* line() { return buf; }
361 int readcount() { return lcount; } //number of lines read
362 void setFile(FILE* stream) { file=stream; }
363 int length() { return len; }
364 int size() { return len; } //same as size();
365 bool isEof() {return isEOF; }
366 bool eof() { return isEOF; }
367 off_t getfpos() { return filepos; }
368 off_t getFpos() { return filepos; }
369 char* nextLine() { return getLine(); }
370 char* getLine() { if (pushed) { pushed=false; return buf; }
371 else return getLine(file); }
372 char* getLine(FILE* stream) {
373 if (pushed) { pushed=false; return buf; }
374 else return getLine(stream, filepos); }
375 char* getLine(FILE* stream, off_t& f_pos); //read a line from a stream and update
376 // the given file position
377 void pushBack() { if (lcount>0) pushed=true; } // "undo" the last getLine request
378 // so the next call will in fact return the same line
379 GLineReader(const char* fname) {
380 FILE* f=fopen(fname, "rb");
381 if (f==NULL) GError("Error opening file '%s'!\n",fname);
382 closeFile=true;
383 init(f);
384 }
385 GLineReader(FILE* stream=NULL, off_t fpos=0) {
386 closeFile=false;
387 init(stream,fpos);
388 }
389 void init(FILE* stream, off_t fpos=0) {
390 len=0;
391 isEOF=false;
392 allocated=1024;
393 GMALLOC(buf,allocated);
394 lcount=0;
395 buf[0]=0;
396 file=stream;
397 filepos=fpos;
398 pushed=false;
399 }
400 ~GLineReader() {
401 GFREE(buf);
402 if (closeFile) fclose(file);
403 }
404 };
405
406
407 /* extended fgets() - to read one full line from a file and
408 update the file position correctly !
409 buf will be reallocated as necessary, to fit the whole line
410 */
411 char* fgetline(char* & buf, int& buflen, FILE* stream, off_t* f_pos=NULL, int* linelen=NULL);
412
413
414 //print int/values nicely formatted in 3-digit groups
415 char* commaprint(uint64 n);
416
417 /*********************** File management functions *********************/
418
419 // removes the last part (file or directory name) of a full path
420 // WARNING: this is a destructive operation for the given string!
421 void delFileName(char* filepath);
422
423 // returns a pointer to the last file or directory name in a full path
424 const char* getFileName(const char* filepath);
425 // returns a pointer to the file "extension" part in a filename
426 const char* getFileExt(const char* filepath);
427
428
429 int fileExists(const char* fname);
430 //returns 0 if file entry doesn't exist
431 // 1 if it's a directory
432 // 2 if it's a regular file
433 // 3 otherwise (?)
434
435 int64 fileSize(const char* fpath);
436
437 //write a formatted fasta record, fasta formatted
438 void writeFasta(FILE *fw, const char* seqid, const char* descr,
439 const char* seq, int linelen=60, int seqlen=0);
440
441 //parses the next number found in a string at the current position
442 //until a non-digit (and not a '.', 'e','E','-','+') is encountered;
443 //updates the char* pointer to be after the last digit parsed
444 bool parseNumber(char* &p, double& v);
445 bool parseDouble(char* &p, double& v); //just an alias for parseNumber
446
447 bool parseInt(char* &p, int& i);
448 bool parseUInt(char* &p, uint& i);
449 bool parseHex(char* &p, uint& i);
450
451 #endif /* G_BASE_DEFINED */