home *** CD-ROM | disk | FTP | other *** search
/ Steganos Hacker Tools / SHT151.iso / programme / scanner / nmapNTsp1 / Win_2000.exe / nmapNT-src / charpool.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-06  |  1.9 KB  |  91 lines

  1. /* Character pool memory allocation */
  2. #include "charpool.h"
  3.  
  4. static char *charpool[16];
  5. static int currentcharpool;
  6. static int currentcharpoolsz;
  7. static char *nextchar;
  8. static int charpool_initialized = 0;
  9.  
  10. #define ALIGN_ON sizeof(char *)
  11.  
  12. static int cp_init(void) {
  13.   /* Create our char pool */
  14.   currentcharpool = 0;
  15.   currentcharpoolsz = 16384;
  16.   nextchar = charpool[0] = (char *) safe_malloc(currentcharpoolsz);
  17.   charpool_initialized = 1;
  18.   return 0;
  19. }
  20.  
  21. static inline void cp_grow(void) {
  22.   /* Doh!  We've got to make room */
  23.   if (++currentcharpool > 15) {
  24.     fatal("Character Pool is out of buckets!");
  25.   }
  26.   currentcharpoolsz <<= 1;
  27.  
  28.   nextchar = charpool[currentcharpool] = (char *)
  29.     safe_malloc(currentcharpoolsz);
  30. }
  31.  
  32. static inline void cp_align(void) {
  33.   int res;
  34.   if ((res = (nextchar - charpool[currentcharpool]) % ALIGN_ON)) {
  35.     nextchar += ALIGN_ON - res;
  36.   }
  37.   return;
  38. }
  39.  
  40. void *cp_alloc(int sz) {
  41.   char *p;
  42.   int modulus;
  43.  
  44.   if (!charpool_initialized) cp_init();
  45.  
  46.   if ((modulus = sz % ALIGN_ON))
  47.     sz += modulus;
  48.   
  49.   if ((nextchar - charpool[currentcharpool]) + sz <= currentcharpoolsz) {
  50.     p = nextchar;
  51.     nextchar += sz;
  52.     return p;
  53.   }
  54.   /* Doh!  We've got to make room */
  55.   cp_grow();
  56.  
  57.  return cp_alloc(sz);
  58.  
  59. }
  60.  
  61. char *cp_strdup(const char *src) {
  62. const char *p;
  63. char *q;
  64. /* end points to the first illegal char */
  65. char *end;
  66. int modulus;
  67.  
  68.  if (!charpool_initialized) 
  69.    cp_init();
  70.  
  71.  end = charpool[currentcharpool] + currentcharpoolsz;
  72.  q = nextchar;
  73.  p = src;
  74.  while((nextchar < end) && *p) {
  75.    *nextchar++ = *p++;
  76.  }
  77.  
  78.  if (nextchar < end) {
  79.    /* Goody, we have space */
  80.    *nextchar++ = '\0';
  81.    if ((modulus = (nextchar - q) % ALIGN_ON))
  82.      nextchar += ALIGN_ON - modulus;
  83.    return q;
  84.  }
  85.  
  86.  /* Doh!  We ran out -- need to allocate more */
  87.  cp_grow();
  88.  
  89.  return cp_strdup(src);
  90. }
  91.