ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/gclib/GBase.h
Revision: 258
Committed: Tue Jun 26 22:29:50 2012 UTC (6 years, 10 months ago) by gpertea
File size: 13328 byte(s)
Log Message:
commented out saprintf(), not used

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