home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / me34src.zip / me3 / util / sheap.c < prev    next >
C/C++ Source or Header  |  1995-01-14  |  2KB  |  107 lines

  1. /* 
  2.  * sheap.c : string heaps
  3.  * C Durland 3/93 Public Domain
  4.  * cc -g -o sheap sheap.c -DTEST
  5.  */
  6.  
  7. #include "const.h"
  8.  
  9. extern char *malloc(), *strcpy();
  10.  
  11. static int new_size = 1000;
  12.  
  13. int sheap_size(n)
  14. {
  15.   if (n > 100) new_size = n;
  16.   return new_size;
  17. }
  18.  
  19. typedef struct SHeap
  20. {
  21.   int size, max;
  22.   struct SHeap *next;
  23.   char text[1];
  24. } SHeap;
  25.  
  26. char *sheap_add(heap, text) SHeap **heap; char *text;
  27. {
  28.   char *t;
  29.   int len;
  30.   SHeap *ptr = *heap;
  31.  
  32.   if (ptr == NULL)
  33.   {
  34.     if (NULL == (ptr = (SHeap *)malloc(sizeof(SHeap) + new_size - 1)))
  35.     return NULL;
  36.     ptr->max  = new_size;
  37.     ptr->size = 0;
  38.     ptr->next = NULL;
  39.     
  40.     *heap = ptr;
  41.     return sheap_add(heap, text);
  42.   }
  43.  
  44.   len = strlen(text) + 1;
  45.   while (ptr)
  46.   {
  47.     if (ptr->max < ptr->size + len)    /* text won't fit in this heap */
  48.     {
  49.       ptr = ptr->next;
  50.       continue;
  51.     }
  52.     t = strcpy(ptr->text + ptr->size, text);
  53.     ptr->size += len;
  54.  
  55.     return t;
  56.   }
  57.  
  58.     /* text won't fit in an existing heap, make a new one */
  59. /*if (new_size < len) return NULL;    /* too big == too bad */
  60.   if (t = sheap_add(&ptr, text))    /* note that ptr == NULL */
  61.   {
  62.     ptr->next = *heap;
  63.     *heap = ptr;
  64.  
  65.     return t;
  66.   }
  67.  
  68.   return NULL;        /* couldn't do it */
  69. }
  70.  
  71. int sheap_reset(heap) SHeap *heap;
  72. {
  73.   for (; heap; heap = heap->next) heap->size = 0;
  74.  
  75.   return TRUE;
  76. }
  77.  
  78.  
  79. /* *********************** TEST **************************** */
  80. #ifdef TEST
  81.  
  82. SHeap *heap = NULL;    /* or void * or char * */
  83. char *list[200];
  84.  
  85. main(argc, argv) char **argv;
  86. {
  87.   char *ptr;
  88.   int i,j;
  89.  
  90.   if (argc == 1)
  91.   {
  92.     printf("sheap <string> <string> ....\n");
  93.     exit(1);
  94.   }
  95.   for (j = 0; --argc; j++)
  96.   {
  97.     if (!(list[j] = sheap_add(&heap, argv[j+1])))
  98.     {
  99.       printf("sheap_add() failed!\n");
  100.       exit(1);
  101.     }
  102.   }
  103.   for (i = 0; i < j; i++) printf("[%d] : %s\n", i, list[i]);
  104. }
  105.  
  106. #endif    /* TEST */
  107.