inc/common.h

Go to the documentation of this file.
00001 /* Common.h - functions that are commonly used.  Includes 
00002  * routines for managing singly linked lists, some basic
00003  * string manipulation stuff, and other stuff of the
00004  * short but useful nature. 
00005  *
00006  * This file is copyright 2002-2005 Jim Kent, but license is hereby
00007  * granted for all use - public, private or commercial. */
00008 
00009 #ifndef COMMON_H        /* Wrapper to avoid including this twice. */
00010 #define COMMON_H
00011 
00012 /* Some stuff to support large files in Linux. */
00013 #ifndef _LARGEFILE_SOURCE
00014 #define _LARGEFILE_SOURCE 1
00015 #endif
00016 
00017 #ifndef _GNU_SOURCE
00018 #define _GNU_SOURCE
00019 #endif
00020 
00021 #ifndef _FILE_OFFSET_BITS
00022 #define _FILE_OFFSET_BITS 64
00023 #endif
00024 
00025 /* Some stuff for safer pthreads. */
00026 #ifndef _REENTRANT
00027 #define _REENTRANT
00028 #endif
00029 
00030 #include <stdio.h>
00031 #include <stdlib.h>
00032 #include <stdarg.h>
00033 #include <string.h>
00034 #include <ctype.h>
00035 #include <sys/types.h>
00036 #include <sys/stat.h>
00037 #include <strings.h>
00038 #include <fcntl.h>
00039 #include <assert.h>
00040 #include <setjmp.h>
00041 #include <time.h>
00042 #include <math.h>
00043 #include <errno.h>
00044 #include <unistd.h>
00045 #include <libgen.h>
00046 
00047 #if defined(MACHTYPE_ppc)
00048 #include <sys/wait.h>
00049 #endif
00050 
00051 #if defined(__APPLE__)
00052 #if defined(__i686__)
00053 /* The i686 apple math library defines warn. */
00054 #define warn jkWarn
00055 #endif
00056 #endif
00057 
00058 #ifdef __CYGWIN32__
00059 #include <mingw/math.h>
00060 #endif
00061 
00062 #ifndef NAN
00063 #define NAN (0.0 / 0.0)
00064 #endif
00065 
00066 #ifndef WIFEXITED
00067 #define WIFEXITED(stat)  (((*((int *) &(stat))) & 0xff) == 0)
00068 #endif
00069 
00070 #ifndef WEXITSTATUS
00071 #define WEXITSTATUS(stat) (short)(((*((int *) &(stat))) >> 8) & 0xffff)
00072 #endif
00073 
00074 #ifndef WIFSIGNALED
00075 #define WIFSIGNALED(stat) (((*((int *) &(stat)))) && ((*((int *) &(stat))) == ((*((int *) &(stat))) &0x00ff)))
00076 #endif
00077 
00078 #ifndef WTERMSIG
00079 #define WTERMSIG(stat)    ((*((int *) &(stat))) & 0x7f)
00080 #endif
00081 
00082 #ifndef WIFSTOPPED
00083 #define WIFSTOPPED(stat)  (((*((int *) &(stat))) & 0xff) == 0177)
00084 #endif
00085 
00086 #ifndef WSTOPSIG
00087 #define WSTOPSIG(stat)    (((*((int *) &(stat))) >> 8) & 0xff)
00088 #endif
00089 
00090 #ifndef HUGE
00091 #define HUGE MAXFLOAT
00092 #endif
00093 
00094 
00095 /* Let's pretend C has a boolean type. */
00096 #define TRUE 1
00097 #define FALSE 0
00098 #define boolean int
00099 #ifndef __cplusplus
00100 #ifndef bool
00101 #define bool char
00102 #endif
00103 #endif
00104 
00105 /* Some other type synonyms */
00106 #define UBYTE unsigned char   /* Wants to be unsigned 8 bits. */
00107 #define BYTE signed char      /* Wants to be signed 8 bits. */
00108 #define UWORD unsigned short  /* Wants to be unsigned 16 bits. */
00109 #define WORD short            /* Wants to be signed 16 bits. */
00110 #define bits64 unsigned long long  /* Wants to be unsigned 64 bits. */
00111 #define bits32 unsigned       /* Wants to be unsigned 32 bits. */
00112 #define bits16 unsigned short /* Wants to be unsigned 16 bits. */
00113 #define bits8 unsigned char   /* Wants to be unsigned 8 bits. */
00114 #define signed32 int          /* Wants to be signed 32 bits. */
00115 #define bits8 unsigned char   /* Wants to be unsigned 8 bits. */
00116 
00117 #define BIGNUM 0x3fffffff       /* A really big number */
00118 
00119 #define LIMIT_2or8GB (2147483647 * ((sizeof(size_t)/4)*(sizeof(size_t)/4)))
00120 /*      == 2 Gb for 32 bit machines, 8 Gb for 64 bit machines */
00121 #define LIMIT_2or6GB (2147483647 + (2147483647 * ((sizeof(size_t)/4)-1)) + \
00122         (2147483647 * ((sizeof(size_t)/4)-1)))
00123 /*      == 2 Gb for 32 bit machines, 6 Gb for 64 bit machines */
00124 
00125 /* Default size of directory path string buffers */
00126 #define PATH_LEN 512
00127 
00128 /* inline functions: To declare a function inline, place the entire function
00129  * in a header file and prefix it with the INLINE macro.  If used with a
00130  * compiler that doesn't support inline, change the INLINE marco to be simply
00131  * `static'.
00132  */
00133 #ifndef INLINE
00134 #define INLINE static inline
00135 #endif
00136 
00137 /* stdargs compatibility: in a unix universe a long time ago, types of va_list
00138  * were passed by value.  It was assume one could do things like:
00139  *
00140  *     va_start(args);
00141  *     vfprintf(fh1, fmt, args);
00142  *     vfprintf(fh2, fmt, args);
00143  *     va_end(args);
00144  *
00145  * and life would good.  However this is not true on some modern systems (for
00146  * instance gcc/glibc on x86_64), where va_args can be a pointer to some type
00147  * of object).  The second call to vfprintf() would then crash, since the
00148  * first call modified the object that va_args was pointing to. C99 adds a
00149  * va_copy macro that to address this issue.  Many non-C99 system include this
00150  * macro, sometimes called __va_copy.  Here we ensure that va_copy is defined.
00151  * If if doesn't exist, we try to define it in terms of __va_copy.  If that is
00152  * not available, we make the assumption that va_list can be copied by value
00153  * and create our own.  Our implementation is the same as used on Solaris.
00154  */
00155 #if defined(__va_copy) && !defined(va_copy)
00156 #   define va_copy __va_copy
00157 #endif
00158 #if !defined(va_copy)
00159 #   define va_copy(to, from) ((to) = (from))
00160 #endif
00161 
00162 /* Cast a pointer to a long long. Use to printf format points as long-longs
00163  * in a 32/64bit portable manner.  Format should use %llx for the result.
00164  * Needed because casting a pointer to a different sized number cause a
00165  * warning with gcc */
00166 #define ptrToLL(p) ((long long)((size_t)p))
00167 
00168 /* How big is this array? */
00169 #define ArraySize(a) (sizeof(a)/sizeof((a)[0]))
00170 
00171 #define uglyf printf  /* debugging printf */
00172 #define uglyAbort errAbort /* debugging error abort. */
00173 #define uglyOut stdout /* debugging fprintf target. */
00174 
00175 void *needMem(size_t size);
00176 /* Need mem calls abort if the memory allocation fails. The memory
00177  * is initialized to zero. */
00178 
00179 void *needLargeMem(size_t size);
00180 /* This calls abort if the memory allocation fails. The memory is
00181  * not initialized to zero. */
00182 
00183 void *needLargeZeroedMem(size_t size);
00184 /* Request a large block of memory and zero it. */
00185 
00186 void *needLargeMemResize(void* vp, size_t size);
00187 /* Adjust memory size on a block, possibly relocating it.  If vp is NULL,
00188  * a new memory block is allocated.  Memory not initted. */
00189 
00190 void *needLargeZeroedMemResize(void* vp, size_t oldSize, size_t newSize);
00191 /* Adjust memory size on a block, possibly relocating it.  If vp is NULL, a
00192  * new memory block is allocated.  If block is grown, new memory is zeroed. */
00193 
00194 void *needHugeMem(size_t size);
00195 /* No checking on size.  Memory not initted to 0. */
00196 
00197 void *needHugeZeroedMem(size_t size);
00198 /* Request a large block of memory and zero it. */
00199 
00200 void *needHugeMemResize(void* vp, size_t size);
00201 /* Adjust memory size on a block, possibly relocating it.  If vp is NULL,
00202  * a new memory block is allocated.  No checking on size.  Memory not
00203  * initted. */
00204 
00205 void *needHugeZeroedMemResize(void* vp, size_t oldSize, size_t newSize);
00206 /* Adjust memory size on a block, possibly relocating it.  If vp is NULL, a
00207  * new memory block is allocated.  No checking on size.  If block is grown,
00208  * new memory is zeroed. */
00209 
00210 void *needMoreMem(void *old, size_t copySize, size_t newSize);
00211 /* Allocate a new buffer, copy old buffer to it, free old buffer. */
00212 
00213 void *cloneMem(void *pt, size_t size);
00214 /* Allocate a new buffer of given size, and copy pt to it. */
00215 
00216 #define CloneVar(pt) cloneMem(pt, sizeof((pt)[0]))
00217 /* Allocate copy of a structure. */
00218 
00219 void *wantMem(size_t size);
00220 /* Want mem just calls malloc - no zeroing of memory, no
00221  * aborting if request fails. */
00222 
00223 void freeMem(void *pt);
00224 /* Free memory will check for null before freeing. */
00225 
00226 void freez(void *ppt);
00227 /* Pass address of pointer.  Will free pointer and set it 
00228  * to NULL. Typical use:
00229  *     s = needMem(1024);
00230  *          ...
00231  *     freez(&s); */
00232 
00233 #define AllocVar(pt) (pt = needMem(sizeof(*pt)))
00234 /* Shortcut to allocating a single variable on the heap and
00235  * assigning pointer to it. */
00236 
00237 #define AllocArray(pt, size) (pt = needLargeZeroedMem(sizeof(*pt) * (size)))
00238 
00239 #define AllocA(type) needMem(sizeof(type))
00240 /* Shortcut to allocating a variable on heap of a specific type. */
00241 
00242 #define AllocN(type,count) ((type*)needLargeZeroedMem(sizeof(type) * (count)))
00243 /* Shortcut to allocating an array on the heap of a specific type. */
00244 
00245 #define ExpandArray(array, oldCount, newCount) \
00246   (array = needMoreMem((array), (oldCount)*sizeof((array)[0]), (newCount)*sizeof((array)[0])))
00247 /* Expand size of dynamically allocated array. */
00248 
00249 #define CopyArray(source, dest,count) memcpy(dest,source,(count)*sizeof(dest[0]))
00250 /* Copy count elements of array from source to dest. */
00251 
00252 #define CloneArray(a, count) cloneMem(a, (count)*sizeof(a[0]))
00253 /* Make new dynamic array initialized with  count elements of a */
00254 
00255 void errAbort(char *format, ...)
00256 /* Abort function, with optional (printf formatted) error message. */
00257 #if defined(__GNUC__) && defined(JK_WARN)
00258 __attribute__((format(printf, 1, 2)))
00259 #endif
00260 ;
00261 
00262 void errnoAbort(char *format, ...)
00263 /* Prints error message from UNIX errno first, then does errAbort. */
00264 #if defined(__GNUC__) && defined(JK_WARN)
00265 __attribute__((format(printf, 1, 2)))
00266 #endif
00267 ;
00268 
00269 #define internalErr()  errAbort("Internal error %s %d", __FILE__, __LINE__)
00270 /* Generic internal error message */
00271 
00272 void warn(char *format, ...)
00273 /* Issue a warning message. */
00274 #if defined(__GNUC__) && defined(JK_WARN)
00275 __attribute__((format(printf, 1, 2)))
00276 #endif
00277 ;
00278 
00279 void verbose(int verbosity, char *format, ...)
00280 /* Write printf formatted message to log (which by
00281  * default is stdout) if global verbose variable
00282  * is set to verbosity or higher.  Default level is 1. */
00283 #if defined(__GNUC__) && defined(JK_WARN)
00284 __attribute__((format(printf, 2, 3)))
00285 #endif
00286     ;
00287 
00288 void verboseDot();
00289 /* Write I'm alive dot (at verbosity level 1) */
00290 
00291 int verboseLevel();
00292 /* Get verbosity level. */
00293 
00294 void verboseSetLevel(int verbosity);
00295 /* Set verbosity level in log.  0 for no logging,
00296  * higher number for increasing verbosity. */
00297 
00298 void zeroBytes(void *vpt, int count);     
00299 /* fill a specified area of memory with zeroes */
00300 
00301 #define ZeroVar(v) zeroBytes(v, sizeof(*v))
00302 
00303 void reverseBytes(char *bytes, long length);
00304 /* Reverse the order of the bytes. */
00305 
00306 void reverseInts(int *a, int length);
00307 /* Reverse the order of the integer array. */
00308 
00309 void reverseUnsigned(unsigned *a, int length);
00310 /* Reverse the order of the unsigned array. */
00311 
00312 void reverseDoubles(double *a, int length);
00313 /* Reverse the order of the double array. */
00314 
00315 void reverseStrings(char **a, int length);
00316 /* Reverse the order of the char* array. */
00317 
00318 void swapBytes(char *a, char *b, int length);
00319 /* Swap buffers a and b. */
00320 
00321 /* Some things to manage simple lists - structures that begin
00322  * with a pointer to the next element in the list. */
00323 struct slList
00324     {
00325     struct slList *next;
00326     };
00327 
00328 int slCount(void *list); 
00329 /* Return # of elements in list.  */
00330 
00331 void *slElementFromIx(void *list, int ix);
00332 /* Return the ix'th element in list.  Returns NULL
00333  * if no such element. */
00334 
00335 int slIxFromElement(void *list, void *el);
00336 /* Return index of el in list.  Returns -1 if not on list. */
00337 
00338 void slSafeAddHead(void *listPt, void *node); 
00339 /* Add new node to start of list.
00340  * Usage:
00341  *    slSafeAddHead(&list, node);
00342  * where list and nodes are both pointers to structure
00343  * that begin with a next pointer. 
00344  */
00345 
00346 /* Add new node to start of list, this macro is faster
00347  * than slSafeAddHead, but has standard macro restriction
00348  * on what can be safely passed as arguments. */
00349 #define slAddHead(listPt, node) \
00350     ((node)->next = *(listPt), *(listPt) = (node))
00351 
00352 void slAddTail(void *listPt, void *node);
00353 /* Add new node to tail of list.
00354  * Usage:
00355  *    slAddTail(&list, node);
00356  * where list and nodes are both pointers to structure
00357  * that begin with a next pointer. This is sometimes
00358  * convenient but relatively slow.  For longer lists
00359  * it's better to slAddHead, and slReverse when done. 
00360  */
00361 
00362 void *slPopHead(void *listPt);
00363 /* Return head of list and remove it from list. (Fast) */
00364 
00365 void *slPopTail(void *listPt);
00366 /* Return tail of list and remove it from list. (Not so fast) */
00367 
00368 void *slCat(void *a, void *b);
00369 /* Return concatenation of lists a and b.
00370  * Example Usage:
00371  *   struct slName *a = getNames("a");
00372  *   struct slName *b = getNames("b");
00373  *   struct slName *ab = slCat(a,b)
00374  * After this it is no longer safe to use a or b. 
00375  */
00376 
00377 void *slLastEl(void *list);
00378 /* Returns last element in list or NULL if none. */
00379 
00380 void slReverse(void *listPt);
00381 /* Reverse order of a list.
00382  * Usage:
00383  *    slReverse(&list);
00384  */
00385 
00386 typedef int CmpFunction(const void *elem1, const void *elem2);
00387 
00388 void slSort(void *pList, CmpFunction *compare);
00389 /* Sort a singly linked list with Qsort and a temporary array. 
00390  * The arguments to the compare function in real, non-void, life
00391  * are pointers to pointers. */
00392 
00393 void slUniqify(void *pList, CmpFunction *compare, void (*free)());
00394 /* Return sorted list with duplicates removed. 
00395  * Compare should be same type of function as slSort's compare (taking
00396  * pointers to pointers to elements.  Free should take a simple
00397  * pointer to dispose of duplicate element, and can be NULL. */
00398 
00399 boolean slRemoveEl(void *vpList, void *vToRemove);
00400 /* Remove element from doubly linked list.  Usage:
00401  *    slRemove(&list, el);  
00402  * Returns TRUE if element in list.  */
00403 
00404 void slFreeList(void *listPt);
00405 /* Free all elements in list and set list pointer to null. 
00406  * Usage:
00407  *    slFreeList(&list);
00408  */
00409 
00410 struct slInt
00411 /* List of integers. */
00412     {
00413     struct slInt *next; /* Next in list. */
00414     int val;            /* Integer value. */
00415     };
00416 
00417 struct slInt *slIntNew(int x);
00418 #define newSlInt slIntNew
00419 /* Return a new double. */
00420 
00421 int slIntCmp(const void *va, const void *vb);
00422 /* Compare two slInts. */
00423 
00424 int slIntCmpRev(const void *va, const void *vb);
00425 /* Compare two slInts in reverse direction. */
00426 
00427 void doubleSort(int count, double *array);
00428 /* Sort an array of doubles. */
00429 
00430 double doubleMedian(int count, double *array);
00431 /* Return median value in array.  This will sort
00432  * the array as a side effect. */
00433 
00434 struct slDouble
00435 /* List of double-precision numbers. */
00436     {
00437     struct slDouble *next;      /* Next in list. */
00438     double val;                 /* Double-precision value. */
00439     };
00440 
00441 struct slDouble *slDoubleNew(double x);
00442 #define newSlDouble slDoubleNew
00443 /* Return a new int. */
00444 
00445 int slDoubleCmp(const void *va, const void *vb);
00446 /* Compare two slDoubles. */
00447 
00448 double slDoubleMedian(struct slDouble *list);
00449 /* Return median value on list. */
00450 
00451 void intSort(int count, int *array);
00452 /* Sort an array of ints. */
00453 
00454 int intMedian(int count, int *array);
00455 /* Return median value in array.  This will sort
00456  * the array as a side effect. */
00457 
00458 struct slName
00459 /* List of names. The name array is allocated to accommodate full name
00460  */
00461     {
00462     struct slName *next;        /* Next in list. */
00463     char name[1];               /* Allocated at run time to length of string. */
00464     };
00465 
00466 struct slName *newSlName(char *name);
00467 
00468 #define slNameNew newSlName
00469 /* Return a new slName. */
00470 
00471 #define slNameFree freez
00472 /* Free a single slName */
00473 
00474 #define slNameFreeList slFreeList
00475 /* Free a list of slNames */
00476 
00477 struct slName *slNameNewN(char *name, int size);
00478 /* Return new slName of given size. */
00479 
00480 int slNameCmpCase(const void *va, const void *vb);
00481 /* Compare two slNames, ignore case. */
00482 
00483 int slNameCmp(const void *va, const void *vb);
00484 /* Compare two slNames. */
00485 
00486 void slNameSortCase(struct slName **pList);
00487 /* Sort slName list, ignore case. */
00488 
00489 void slNameSort(struct slName **pList);
00490 /* Sort slName list. */
00491 
00492 boolean slNameInList(struct slName *list, char *string);
00493 /* Return true if string is in name list */
00494 
00495 void *slNameFind(void *list, char *string);
00496 /* Return first element of slName list (or any other list starting
00497  * with next/name fields) that matches string. */
00498 
00499 int slNameFindIx(struct slName *list, char *string);
00500 /* Return index of first element of slName list (or any other 
00501  * list starting with next/name fields) that matches string.
00502  * ... Return -1 if not found. */
00503 
00504 char *slNameStore(struct slName **pList, char *string);
00505 /* Put string into list if it's not there already.  
00506  * Return the version of string stored in list. */
00507 
00508 struct slName *slNameAddHead(struct slName **pList, char *name);
00509 /* Add name to start of list and return it. */
00510 
00511 struct slName *slNameAddTail(struct slName **pList, char *name);
00512 /* Add name to end of list (not efficient for long lists),
00513  * and return it. */
00514 
00515 struct slName *slNameCloneList(struct slName *list);
00516 /* Return clone of list. */
00517 
00518 struct slName *slNameListFromString(char *s, char delimiter);
00519 /* Return list of slNames gotten from parsing delimited string.
00520  * The final delimiter is optional. a,b,c  and a,b,c, are equivalent
00521  * for comma-delimited lists. */
00522 
00523 #define slNameListFromComma(s) slNameListFromString(s, ',')
00524 /* Parse out comma-separated list. */
00525 
00526 struct slName *slNameLoadReal(char *fileName);
00527 /* load file lines that are not blank or start with a '#' into a slName
00528  * list */
00529 
00530 struct slRef
00531 /* Singly linked list of generic references. */
00532     {
00533     struct slRef *next; /* Next in list. */
00534     void *val;          /* A reference to something. */
00535     };
00536 
00537 struct slRef *slRefNew(void *val);
00538 /* Create new slRef element. */
00539 
00540 struct slRef *refOnList(struct slRef *refList, void *val);
00541 /* Return ref if val is already on list, otherwise NULL. */
00542 
00543 void refAdd(struct slRef **pRefList, void *val);
00544 /* Add reference to list. */
00545 
00546 void refAddUnique(struct slRef **pRefList, void *val);
00547 /* Add reference to list if not already on list. */
00548 
00549 struct slRef *refListFromSlList(void *list);
00550 /* Make a reference list that mirrors a singly-linked list. */
00551 
00552 struct slPair
00553 /* A name/value pair. */
00554     {
00555     struct slPair *next;        /* Next in list. */
00556     char *name;                 /* Name of item. */
00557     void *val;                  /* Pointer to item data. */
00558     };
00559 
00560 struct slPair *slPairNew(char *name, void *val);
00561 /* Allocate new name/value pair. */
00562 
00563 void slPairAdd(struct slPair **pList, char *name, void *val);
00564 /* Add new slPair to head of list. */
00565 
00566 void slPairFree(struct slPair **pEl);
00567 /* Free up struct and name.  (Don't free up values.) */
00568 
00569 void slPairFreeList(struct slPair **pList);
00570 /* Free up list.  (Don't free up values.) */
00571 
00572 void slPairFreeVals(struct slPair *list);
00573 /* Free up all values on list. */
00574 
00575 void slPairFreeValsAndList(struct slPair **pList);
00576 /* Free up all values on list and list itself */
00577 
00578 struct slPair *slPairFind(struct slPair *list, char *name);
00579 /* Return list element of given name, or NULL if not found. */
00580 
00581 void *slPairFindVal(struct slPair *list, char *name);
00582 /* Return value associated with name in list, or NULL if not found. */
00583 
00584 
00585 void gentleFree(void *pt);
00586 /* check pointer for NULL before freeing. 
00587  * (Actually plain old freeMem does that these days.) */
00588 
00589 /*******  Some stuff for processing strings. *******/
00590 
00591 char *cloneStringZ(char *s, int size);
00592 /* Make a zero terminated copy of string in memory */
00593 
00594 char *cloneString(char *s);
00595 /* Make copy of string in dynamic memory */
00596 
00597 char *cloneLongString(char *s);
00598 /* Make clone of long string. */
00599 
00600 int differentWord(char *s1, char *s2);
00601 /* strcmp ignoring case - returns zero if strings are
00602  * the same (ignoring case) otherwise returns difference
00603  * between first non-matching characters. */
00604 
00605 #define sameWord(a,b) (!differentWord(a,b))
00606 /* Return TRUE if two strings are same ignoring case */
00607 
00608 #define differentString(a,b) (strcmp(a,b))
00609 /* Returns FALSE if two strings same. */
00610 
00611 int differentStringNullOk(char *a, char *b);
00612 /* Returns 0 if two strings (either of which may be NULL)
00613  * are the same.  Otherwise it returns a positive or negative
00614  * number depending on the alphabetical order of the two
00615  * strings.
00616  * This is basically a strcmp that can handle NULLs in
00617  * the input.  If used in a sort the NULLs will end
00618  * up before any of the cases with data.   */
00619 
00620 #define sameOk(a,b) (differentStringNullOk(a,b) == 0)
00621 /* returns TRUE if two strings same, NULLs OK */
00622 
00623 #define sameString(a,b) (strcmp(a,b)==0)
00624 /* Returns TRUE if two strings same. */
00625 
00626 #define sameStringN(a,b,c) (strncmp(a,b,c)==0)
00627 /* Returns TRUE if two strings start with the same c characters. */
00628 
00629 #define isEmpty(string) (string == NULL || string[0] == 0)
00630 #define isNotEmpty(string) (! isEmpty(string))
00631 
00632 boolean startsWith(char *start,char *string);
00633 /* Returns TRUE if string begins with start. */
00634 
00635 boolean startsWithWord(char *firstWord, char *line);
00636 /* Return TRUE if first white-space-delimited word in line
00637  * is same as firstWord.  Comparison is case sensitive. */
00638 
00639 #define stringIn(needle, haystack) strstr(haystack, needle)
00640 /* Returns position of needle in haystack or NULL if it's not there. */
00641 /*        char *stringIn(char *needle, char *haystack);      */
00642 
00643 char *rStringIn(char *needle, char *haystack);
00644 /* Return last position of needle in haystack, or NULL if it's not there. */
00645 
00646 char *stringBetween(char *start, char *end, char *haystack);
00647 /* Return string between start and end strings, or NULL if
00648  * none found.  The first such instance is returned. 
00649  * String must be freed by caller. */
00650 
00651 boolean endsWith(char *string, char *end);
00652 /* Returns TRUE if string ends with end. */
00653 
00654 char lastChar(char *s);
00655 /* Return last character in string. */
00656 
00657 boolean wildMatch(char *wildCard, char *string);
00658 /* does a case insensitive wild card match with a string.
00659  * * matches any string or no character.
00660  * ? matches any single character.
00661  * anything else etc must match the character exactly. */
00662 
00663 char *memMatch(char *needle, int nLen, char *haystack, int hLen);
00664 /* Returns first place where needle (of nLen chars) matches
00665  * haystack (of hLen chars) */
00666 
00667 void toUpperN(char *s, int n);
00668 /* Convert a section of memory to upper case. */
00669 
00670 void toLowerN(char *s, int n);
00671 /* Convert a section of memory to lower case. */
00672 
00673 void toggleCase(char *s, int size);
00674 /* toggle upper and lower case chars in string. */
00675 
00676 void touppers(char *s);
00677 /* Convert entire string to upper case. */
00678 
00679 void tolowers(char *s);
00680 /* Convert entire string to lower case */
00681 
00682 char *replaceChars(char *string, char *oldStr, char *newStr);
00683 /*
00684   Replaces the old with the new.
00685  The old and new string need not be of equal size
00686  Can take any length string.
00687  Return value needs to be freeMem'd.
00688 */
00689 
00690 void subChar(char *s, char oldChar, char newChar);
00691 /* Substitute newChar for oldChar throughout string s. */
00692 
00693 void stripChar(char *s, char c);
00694 /* Remove all occurences of c from s. */
00695 
00696 void stripString(char *s, char *strip);
00697 /* Remove all occurences of strip from s. */
00698 
00699 int countChars(char *s, char c);
00700 /* Return number of characters c in string s. */
00701 
00702 int countCharsN(char *s, char c, int size);
00703 /* Return number of characters c in string s of given size. */
00704 
00705 int countLeadingChars(char *s, char c);
00706 /* Count number of characters c at start of string. */
00707 
00708 int countSame(char *a, char *b);
00709 /* Count number of characters that from start in a,b that are same. */
00710 
00711 int chopString(char *in, char *sep, char *outArray[], int outSize);
00712 /* int chopString(in, sep, outArray, outSize); */
00713 /* This chops up the input string (cannabilizing it)
00714  * into an array of zero terminated strings in
00715  * outArray.  It returns the number of strings. 
00716  * If you pass in NULL for outArray, it will just
00717  * return the number of strings that it *would*
00718  * chop. */
00719 
00720 extern char crLfChopper[];
00721 extern char whiteSpaceChopper[];
00722 /* Some handy predefined separators. */
00723 
00724 int chopByWhite(char *in, char *outArray[], int outSize);
00725 /* Like chopString, but specialized for white space separators. */
00726 
00727 #define chopLine(line, words) chopByWhite(line, words, ArraySize(words))
00728 /* Chop line by white space. */
00729 
00730 int chopByChar(char *in, char chopper, char *outArray[], int outSize);
00731 /* Chop based on a single character. */
00732 
00733 #define chopTabs(string, words) chopByChar(string, '\t', words, ArraySize(words))
00734 /* Chop string by tabs. */
00735 
00736 #define chopCommas(string, words) chopByChar(string, ',', words, ArraySize(words))
00737 /* Chop string by commas. */
00738 
00739 
00740 char *skipLeadingSpaces(char *s);
00741 /* Return first non-white space */
00742 
00743 char *skipToSpaces(char *s);
00744 /* Return first white space. */
00745 
00746 void eraseTrailingSpaces(char *s);
00747 /* Replace trailing white space with zeroes. */
00748 
00749 void eraseWhiteSpace(char *s);
00750 /* Remove white space from a string */
00751 
00752 char *trimSpaces(char *s);
00753 /* Remove leading and trailing white space. */
00754 
00755 void spaceOut(FILE *f, int count);
00756 /* Put out some spaces to file. */
00757 
00758 void starOut(FILE *f, int count);
00759 /* Put out some asterisks to file. */
00760 
00761 boolean hasWhiteSpace(char *s);
00762 /* Return TRUE if there is white space in string. */
00763 
00764 char *firstWordInLine(char *line);
00765 /* Returns first word in line if any (white space separated).
00766  * Puts 0 in place of white space after word. */
00767 
00768 char *lastWordInLine(char *line);
00769 /* Returns last word in line if any (white space separated).
00770  * Returns NULL if string is empty.  Removes any terminating white space
00771  * from line. */
00772 
00773 char *nextWord(char **pLine);
00774 /* Return next word in *pLine and advance *pLine to next
00775  * word. Returns NULL when no more words. */
00776 
00777 char *nextTabWord(char **pLine);
00778 /* Return next tab-separated word. */
00779 
00780 int stringArrayIx(char *string, char *array[], int arraySize);
00781 /* Return index of string in array or -1 if not there. */
00782 
00783 int ptArrayIx(void *pt, void *array, int arraySize);
00784 /* Return index of pt in array or -1 if not there. */
00785 
00786 #define stringIx(string, array) stringArrayIx( (string), (array), ArraySize(array))
00787 
00788 /* Some stuff that is left out of GNU .h files!? */
00789 #ifndef SEEK_SET
00790 #define SEEK_SET 0
00791 #endif
00792 
00793 #ifndef SEEK_CUR
00794 #define SEEK_CUR 1
00795 #endif
00796 
00797 #ifndef SEEK_END
00798 #define SEEK_END 2
00799 #endif
00800 
00801 void splitPath(char *path, char dir[256], char name[128], char extension[64]);
00802 /* Split a full path into components.  The dir component will include the
00803  * trailing / if any.  The extension component will include the starting
00804  * . if any.   Pass in NULL for dir, name, or extension if you don't care about
00805  * that part. */
00806 
00807 char *addSuffix(char *head, char *suffix);
00808 /* Return a needMem'd string containing "headsuffix". Should be free'd
00809  when finished. */
00810 
00811 void chopSuffix(char *s);
00812 /* Remove suffix (last . in string and beyond) if any. */
00813 
00814 void chopSuffixAt(char *s, char c);
00815 /* Remove end of string from last occurrence of char c. 
00816  * chopSuffixAt(s, '.') is equivalent to regular chopSuffix. */
00817 
00818 char *chopPrefix(char *s);
00819 /* This will replace the first '.' in a string with
00820  * 0, and return the character after this.  If there
00821  * is no '.' in the string this will just return the
00822  * unchanged s passed in. */
00823 
00824 char *chopPrefixAt(char *s, char c);
00825 /* Like chopPrefix, but can chop on any character, not just '.' */
00826 
00827 FILE *mustOpen(char *fileName, char *mode);
00828 /* Open a file - or squawk and die. */
00829 
00830 void mustWrite(FILE *file, void *buf, size_t size);
00831 /* Write to file or squawk and die. */
00832 
00833 #define writeOne(file, var) mustWrite((file), &(var), sizeof(var))
00834 /* Write out one variable to file. */
00835 
00836 void mustRead(FILE *file, void *buf, size_t size);
00837 /* Read from a file or squawk and die. */
00838 
00839 #define mustReadOne(file, var) mustRead((file), &(var), sizeof(var))
00840 /* Read one variable from file or die. */
00841 
00842 #define readOne(file, var) (fread(&(var), sizeof(var), 1, (file)) == 1)
00843 /* Read one variable from file. Returns FALSE if can't do it. */
00844 
00845 void writeString(FILE *f, char *s);
00846 /* Write a 255 or less character string to a file.
00847  * This will write the length of the string in the first
00848  * byte then the string itself. */
00849 
00850 char *readString(FILE *f);
00851 /* Read a string (written with writeString) into
00852  * memory.  freeMem the result when done. Returns
00853  * NULL at EOF. */
00854 
00855 char *mustReadString(FILE *f);
00856 /* Read a string.  Squawk and die at EOF or if any problem. */
00857 
00858 boolean fastReadString(FILE *f, char buf[256]);
00859 /* Read a string into buffer, which must be long enough
00860  * to hold it.  String is in 'writeString' format. 
00861  * Returns FALSE at EOF. */
00862 
00863 void writeBits64(FILE *f, bits64 x);
00864 /* Write out 64 bit number in manner that is portable across architectures */
00865 
00866 bits64 readBits64(FILE *f);
00867 /* Write out 64 bit number in manner that is portable across architectures */
00868 
00869 void carefulClose(FILE **pFile);
00870 /* Close file if open and null out handle to it. */
00871 
00872 boolean carefulCloseWarn(FILE **pFile);
00873 /* Close file if open and null out handle to it. 
00874  * Return FALSE and print a warning message if there
00875  * is a problem.*/
00876 
00877 char *firstWordInFile(char *fileName, char *wordBuf, int wordBufSize);
00878 /* Read the first word in file into wordBuf. */
00879 
00880 
00881 int roundingScale(int a, int p, int q);
00882 /* returns rounded a*p/q */
00883 
00884 int intAbs(int a);
00885 /* Return integer absolute value */
00886 
00887 #define logBase2(x)(log(x)/log(2))
00888 /* return log base two of number */
00889 
00890 #define round(a) ((int)((a)+0.5))
00891 /* Round floating point val to nearest integer. */
00892 
00893 #define roundll(a) ((long long)((a)+0.5))
00894 /* Round floating point val to nearest long long. */
00895 
00896 #ifndef min
00897 #define min(a,b) ( (a) < (b) ? (a) : (b) )
00898 /* Return min of a and b. */
00899 #endif
00900 
00901 #ifndef max
00902 #define max(a,b) ( (a) > (b) ? (a) : (b) )
00903 /* Return max of a and b. */
00904 #endif
00905 
00906 int  rangeIntersection(int start1, int end1, int start2, int end2);
00907 /* Return amount of bases two ranges intersect over, 0 or negative if no
00908  * intersection. */
00909 
00910 int  positiveRangeIntersection(int start1, int end1, int start2, int end2);
00911 /* Return amount of bases two ranges intersect over, 0 if no
00912  * intersection. */
00913 
00914 bits32 byteSwap32(bits32 a);
00915 /* Swap from intel to sparc order of a 32 bit quantity. */
00916 
00917 void removeReturns(char* dest, char* src);
00918 /* Removes the '\r' character from a string.
00919  * the source and destination strings can be the same, 
00920  * if there are no threads */
00921                 
00922 int intExp(char *text);
00923 /* Convert text to integer expression and evaluate. 
00924  * Throws if it finds a non-number. */
00925 
00926 double doubleExp(char *text);
00927 /* Convert text to floating point expression and
00928  * evaluate. */
00929 
00930 char* readLine(FILE* fh);
00931 /* Read a line of any size into dynamic memory, return null on EOF */
00932 
00933 off_t fileSize(char *fileName);
00934 /* The size of a file. */
00935 
00936 boolean fileExists(char *fileName);
00937 /* Does a file exist? */
00938 
00939 /*
00940  Friendly name for strstrNoCase
00941 */
00942 char *containsStringNoCase(char *haystack, char *needle);
00943 
00944 char *strstrNoCase(char *haystack, char *needle);
00945 /* A case-insensitive strstr */
00946 
00947 int vasafef(char* buffer, int bufSize, char *format, va_list args);
00948 /* Format string to buffer, vsprintf style, only with buffer overflow
00949  * checking.  The resulting string is always terminated with zero byte. */
00950 
00951 int safef(char* buffer, int bufSize, char *format, ...)
00952 /* Format string to buffer, vsprintf style, only with buffer overflow
00953  * checking.  The resulting string is always terminated with zero byte. */
00954 #ifdef __GNUC__
00955 __attribute__((format(printf, 3, 4)))
00956 #endif
00957 ;
00958 
00959 void safecpy(char *buf, size_t bufSize, const char *src);
00960 /* copy a string to a buffer, with bounds checking.*/
00961 
00962 void safencpy(char *buf, size_t bufSize, const char *src, size_t n);
00963 /* copy n characters from a string to a buffer, with bounds checking.
00964  * Unlike strncpy, always null terminates the result */
00965 
00966 void safecat(char *buf, size_t bufSize, const char *src);
00967 /* Append  a string to a buffer, with bounds checking.*/
00968 
00969 void safencat(char *buf, size_t bufSize, const char *src, size_t n);
00970 /* append n characters from a string to a buffer, with bounds checking. */
00971 
00972 char *naForNull(char *s);
00973 /* Return 'n/a' if s is NULL, otherwise s. */
00974 
00975 char *naForEmpty(char *s);
00976 /* Return n/a if s is "" or NULL, otherwise s. */
00977 
00978 char *emptyForNull(char *s);
00979 /* Return "" if s is NULL, otherwise s. */
00980 
00981 char *nullIfAllSpace(char *s);
00982 /* Return NULL if s is all spaces, otherwise s. */
00983 
00984 char *trueFalseString(boolean b);
00985 /* Return "true" or "false" */
00986 
00987 void uglyTime(char *label, ...);
00988 /* Print label and how long it's been since last call.  Call with 
00989  * a NULL label to initialize. */
00990 
00991 /*      In case the development environment does not supply INFINITY    */
00992 #if !defined(INFINITY)
00993 #define INFINITY (1.0/0.0)
00994 #endif 
00995 
00996 void makeDirs(char* path);
00997 /* make a directory, including parent directories */
00998 
00999 char *skipNumeric(char *s);
01000 /* Return first char of s that's not a digit */
01001 
01002 char *skipToNumeric(char *s);
01003 /* skip up to where numeric digits appear */
01004 
01005 char *splitOffNonNumeric(char *s);
01006 /* Split off non-numeric part, e.g. mm of mm8. Result should be freed when done */
01007 
01008 char *splitOffNumber(char *db);
01009 /* Split off number part, e.g. 8 of mm8. Result should be freed when done */
01010 
01011 #endif /* COMMON_H */

Generated on Tue Dec 25 18:39:29 2007 for blat by  doxygen 1.5.2