Moving source files to src/
[privoxy.git] / src / list.c
1 const char list_rcs[] = "$Id: list.c,v 1.15 2002/03/26 22:29:55 swa Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/list.c,v $
5  *
6  * Purpose     :  Declares functions to handle lists.
7  *                Functions declared include:
8  *                   `destroy_list', `enlist' and `list_to_text'
9  *
10  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
11  *                Privoxy team. http://www.privoxy.org/
12  *
13  *                Based on the Internet Junkbuster originally written
14  *                by and Copyright (C) 1997 Anonymous Coders and
15  *                Junkbusters Corporation.  http://www.junkbusters.com
16  *
17  *                This program is free software; you can redistribute it
18  *                and/or modify it under the terms of the GNU General
19  *                Public License as published by the Free Software
20  *                Foundation; either version 2 of the License, or (at
21  *                your option) any later version.
22  *
23  *                This program is distributed in the hope that it will
24  *                be useful, but WITHOUT ANY WARRANTY; without even the
25  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
26  *                PARTICULAR PURPOSE.  See the GNU General Public
27  *                License for more details.
28  *
29  *                The GNU General Public License should be included with
30  *                this file.  If not, you can view it at
31  *                http://www.gnu.org/copyleft/gpl.html
32  *                or write to the Free Software Foundation, Inc., 59
33  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
34  *
35  * Revisions   :
36  *    $Log: list.c,v $
37  *    Revision 1.15  2002/03/26 22:29:55  swa
38  *    we have a new homepage!
39  *
40  *    Revision 1.14  2002/03/24 13:25:43  swa
41  *    name change related issues
42  *
43  *    Revision 1.13  2002/03/07 03:46:17  oes
44  *    Fixed compiler warnings
45  *
46  *    Revision 1.12  2001/10/25 03:40:48  david__schmidt
47  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
48  *    threads to call select() simultaneously.  So, it's time to do a real, live,
49  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
50  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
51  *
52  *    Revision 1.11  2001/10/23 21:21:03  jongfoster
53  *    New error handling - error codes are now jb_errs, not ints.
54  *    Changed the way map() handles out-of-memory, to dramatically
55  *    reduce the amount of error-checking clutter needed.
56  *
57  *    Revision 1.10  2001/09/16 17:30:24  jongfoster
58  *    Fixing a compiler warning.
59  *
60  *    Revision 1.9  2001/09/16 13:20:29  jongfoster
61  *    Rewrite of list library.  Now has seperate header and list_entry
62  *    structures.  Also added a large sprinking of assert()s to the list
63  *    code.
64  *
65  *    Revision 1.8  2001/08/07 14:00:20  oes
66  *    Fixed comment
67  *
68  *    Revision 1.7  2001/08/05 16:06:20  jongfoster
69  *    Modifiying "struct map" so that there are now separate header and
70  *    "map_entry" structures.  This means that functions which modify a
71  *    map no longer need to return a pointer to the modified map.
72  *    Also, it no longer reverses the order of the entries (which may be
73  *    important with some advanced template substitutions).
74  *
75  *    Revision 1.6  2001/07/31 14:44:51  oes
76  *    list_to_text() now appends empty line at end
77  *
78  *    Revision 1.5  2001/06/29 21:45:41  oes
79  *    Indentation, CRLF->LF, Tab-> Space
80  *
81  *    Revision 1.4  2001/06/29 13:30:22  oes
82  *    - Added Convenience function enlist_unique_header(),
83  *      which takes the Header name and value as separate
84  *      arguments and thus saves the pain of sprintf()ing
85  *      and determining the Header name length to enlist_unique
86  *    - Improved comments
87  *    - Removed logentry from cancelled commit
88  *
89  *    Revision 1.3  2001/06/03 19:12:24  oes
90  *    functions for new struct map, extended enlist_unique
91  *
92  *    Revision 1.2  2001/06/01 18:49:17  jongfoster
93  *    Replaced "list_share" with "list" - the tiny memory gain was not
94  *    worth the extra complexity.
95  *
96  *    Revision 1.1  2001/05/31 21:11:53  jongfoster
97  *    - Moved linked list support to new "list.c" file.
98  *      Structure definitions are still in project.h,
99  *      function prototypes are now in "list.h".
100  *    - Added support for "struct list_share", which is identical
101  *      to "struct list" except it saves memory by not duplicating
102  *      the strings.  Obviously, this only works if there is some
103  *      other way of managing the memory used by the strings.
104  *      (These list_share lists are used for lists which last
105  *      for only 1 request, and where all the list entries are
106  *      just coming directly from entries in the actionsfile.)
107  *      Note that you still need to destroy list_share lists
108  *      properly to free the nodes - it's only the strings
109  *      which are shared.
110  *
111  *
112  *********************************************************************/
113 \f
114
115 #include "config.h"
116
117 #ifndef _WIN32
118 /* FIXME: The following headers are not needed for Win32.  Are they
119  * needed on other platforms?
120  */
121 #include <stdio.h>
122 #include <sys/types.h>
123 #include <stdlib.h>
124 #include <ctype.h>
125 #endif
126 #include <string.h>
127
128 #if !defined(_WIN32) && !defined(__OS2__)
129 #include <unistd.h>
130 #endif
131
132 #include <assert.h>
133
134 #include "project.h"
135 #include "list.h"
136 #include "miscutil.h"
137
138 const char list_h_rcs[] = LIST_H_VERSION;
139
140
141 static int list_is_valid (const struct list *the_list);
142
143
144 /*********************************************************************
145  *
146  * Function    :  list_init
147  *
148  * Description :  Create a new, empty list in user-allocated memory.
149  *                Caller should allocate a "struct list" variable,
150  *                then pass it to this function.
151  *                (Implementation note:  Rather than calling this
152  *                function, you can also just memset the memory to
153  *                zero, e.g. if you have a larger structure you
154  *                want to initialize quickly.  However, that isn't
155  *                really good design.)
156  *
157  * Parameters  :
158  *          1  :  the_list = pointer to list
159  *
160  * Returns     :  N/A
161  *
162  *********************************************************************/
163 void init_list(struct list *the_list)
164 {
165    memset(the_list, '\0', sizeof(*the_list));
166 }
167
168
169 /*********************************************************************
170  *
171  * Function    :  destroy_list
172  *
173  * Description :  Destroy a string list (opposite of list_init).
174  *                On return, the memory used by the list entries has
175  *                been freed, but not the memory used by the_list
176  *                itself.  You should not re-use the_list without
177  *                calling list_init().
178  *
179  *                (Implementation note:  You *can* reuse the_list
180  *                without calling list_init(), but please don't.
181  *                If you want to remove all entries from a list
182  *                and still have a usable list, then use
183  *                list_remove_all().)
184  *
185  * Parameters  :
186  *          1  :  the_list = pointer to list
187  *
188  * Returns     :  N/A
189  *
190  *********************************************************************/
191 void destroy_list (struct list *the_list)
192 {
193    struct list_entry *cur_entry, *next_entry;
194
195    assert(the_list);
196
197    for (cur_entry = the_list->first; cur_entry ; cur_entry = next_entry)
198    {
199       next_entry = cur_entry->next;
200       freez(cur_entry->str);
201       free(cur_entry);
202    }
203
204    the_list->first = NULL;
205    the_list->last = NULL;
206 }
207
208
209 /*********************************************************************
210  *
211  * Function    :  list_is_valid
212  *
213  * Description :  Check that a string list is valid.  The intended
214  *                usage is "assert(list_is_valid(the_list))".
215  *                Currently this checks that "the_list->last"
216  *                is correct, and that the list dosn't contain
217  *                circular references.  It is likely to crash if
218  *                it's passed complete garbage.
219  *
220  * Parameters  :
221  *          1  :  the_list = pointer to list.  Must be non-null.
222  *
223  * Returns     :  1 if list is valid, 0 otherwise.
224  *
225  *********************************************************************/
226 static int list_is_valid (const struct list *the_list)
227 {
228    /*
229     * If you don't want this check, just change the line below
230     * from "#if 1" to "#if 0".
231     */
232 #if 1
233    const struct list_entry *cur_entry;
234    const struct list_entry *last_entry = NULL;
235    int length = 0;
236
237    assert(the_list);
238
239    for (cur_entry = the_list->first; cur_entry ; cur_entry = cur_entry->next)
240    {
241       last_entry = cur_entry;
242
243       if (cur_entry->str)
244       {
245          /*
246           * Just check that this string can be accessed - i.e. it's a valid
247           * pointer.
248           */
249          strlen(cur_entry->str);
250       }
251
252       /*
253        * Check for looping back to first
254        */
255       if ((length != 0) && (cur_entry == the_list->first))
256       {
257          return 0;
258       }
259
260       /*
261        * Arbitrarily limit length to prevent infinite loops.
262        */
263       if (++length > 1000)
264       {
265          return 0;
266       }
267
268       /*
269        * Check this isn't marked as the last entry, unless of course it's
270        * *really* the last entry.
271        */
272       if ((the_list->last == cur_entry) && (cur_entry->next != NULL))
273       {
274          /* This is the last entry, but there's data after it !!?? */
275          return 0;
276       }
277    }
278
279    return (the_list->last == last_entry);
280 #else
281    return 1;
282 #endif
283 }
284
285 /*********************************************************************
286  *
287  * Function    :  enlist
288  *
289  * Description :  Append a string into a specified string list.
290  *
291  * Parameters  :
292  *          1  :  the_list = pointer to list
293  *          2  :  str = string to add to the list (maybe NULL)
294  *
295  * Returns     :  JB_ERR_OK on success
296  *                JB_ERR_MEMORY on out-of-memory error.
297  *                On error, the_list will be unchanged.
298  *
299  *********************************************************************/
300 jb_err enlist(struct list *the_list, const char *str)
301 {
302    struct list_entry *cur;
303
304    assert(the_list);
305    assert(list_is_valid(the_list));
306
307    if (NULL == (cur = (struct list_entry *)zalloc(sizeof(*cur))))
308    {
309       return JB_ERR_MEMORY;
310    }
311
312    if (str)
313    {
314       if (NULL == (cur->str = strdup(str)))
315       {
316          free(cur);
317          return JB_ERR_MEMORY;
318       }
319    }
320    /* else { cur->str = NULL; }  - implied by zalloc */
321
322    /* cur->next = NULL;  - implied by zalloc */
323
324    if (the_list->last)
325    {
326       the_list->last->next = cur;
327       the_list->last = cur;
328    }
329    else
330    {
331       the_list->first = cur;
332       the_list->last = cur;
333    }
334
335    assert(list_is_valid(the_list));
336    return JB_ERR_OK;
337 }
338
339
340 /*********************************************************************
341  *
342  * Function    :  enlist_first
343  *
344  * Description :  Append a string as first element into a specified
345  *                string list.
346  *
347  * Parameters  :
348  *          1  :  the_list = pointer to list
349  *          2  :  str = string to add to the list (maybe NULL)
350  *
351  * Returns     :  JB_ERR_OK on success
352  *                JB_ERR_MEMORY on out-of-memory error.
353  *                On error, the_list will be unchanged.
354  *
355  *********************************************************************/
356 jb_err enlist_first(struct list *the_list, const char *str)
357 {
358    struct list_entry *cur;
359
360    assert(the_list);
361    assert(list_is_valid(the_list));
362
363    if (NULL == (cur = (struct list_entry *)zalloc(sizeof(*cur))))
364    {
365       return JB_ERR_MEMORY;
366    }
367
368    if (str)
369    {
370       if (NULL == (cur->str = strdup(str)))
371       {
372          free(cur);
373          return JB_ERR_MEMORY;
374       }
375    }
376    /* else { cur->str = NULL; }  - implied by zalloc */
377
378    cur->next = the_list->first;
379
380    the_list->first = cur;
381    if (the_list->last == NULL)
382    {
383       the_list->last = cur;
384    }
385
386    assert(list_is_valid(the_list));
387    return JB_ERR_OK;
388 }
389
390
391 /*********************************************************************
392  *
393  * Function    :  enlist_unique
394  *
395  * Description :  Append a string into a specified string list,
396  *                if & only if it's not there already.
397  *                If the num_significant_chars argument is nonzero,
398  *                only compare up to the nth character.
399  *
400  * Parameters  :
401  *          1  :  the_list = pointer to list
402  *          2  :  str = string to add to the list
403  *          3  :  num_significant_chars = number of chars to use
404  *                for uniqueness test, or 0 to require an exact match.
405  *
406  * Returns     :  JB_ERR_OK on success
407  *                JB_ERR_MEMORY on out-of-memory error.
408  *                On error, the_list will be unchanged.
409  *                "Success" does not indicate whether or not the
410  *                item was already in the list.
411  *
412  *********************************************************************/
413 jb_err enlist_unique(struct list *the_list, const char *str,
414                      size_t num_significant_chars)
415 {
416    struct list_entry *cur_entry;
417
418    assert(the_list);
419    assert(list_is_valid(the_list));
420    assert(str);
421    assert(num_significant_chars >= 0);
422    assert(num_significant_chars <= strlen(str));
423
424    if (num_significant_chars > 0)
425    {
426       for (cur_entry = the_list->first; cur_entry != NULL; cur_entry = cur_entry->next)
427       {
428          if ( (cur_entry->str != NULL)
429            && (0 == strncmp(str, cur_entry->str, num_significant_chars)))
430          {
431             /* Already there */
432             return JB_ERR_OK;
433          }
434       }
435    }
436    else
437    {
438       /* Test whole string */
439       for (cur_entry = the_list->first; cur_entry != NULL; cur_entry = cur_entry->next)
440       {
441          if ( (cur_entry->str != NULL) && (0 == strcmp(str, cur_entry->str)))
442          {
443             /* Already there */
444             return JB_ERR_OK;
445          }
446       }
447    }
448
449    return enlist(the_list, str);
450 }
451
452
453 /*********************************************************************
454  *
455  * Function    :  enlist_unique_header
456  *
457  * Description :  Make a HTTP header from the two strings name and value,
458  *                and append the result into a specified string list,
459  *                if & only if there isn't already a header with that name.
460  *
461  * Parameters  :
462  *          1  :  the_list = pointer to list
463  *          2  :  name = HTTP header name (e.g. "Content-type")
464  *          3  :  value = HTTP header value (e.g. "text/html")
465  *
466  * Returns     :  JB_ERR_OK on success
467  *                JB_ERR_MEMORY on out-of-memory error.
468  *                On error, the_list will be unchanged.
469  *                "Success" does not indicate whether or not the
470  *                header was already in the list.
471  *
472  *********************************************************************/
473 jb_err enlist_unique_header(struct list *the_list, const char *name,
474                             const char *value)
475 {
476    size_t length;
477    jb_err result;
478    char *str;
479
480    assert(the_list);
481    assert(list_is_valid(the_list));
482    assert(name);
483    assert(value);
484
485    length = strlen(name) + 2;
486    if (NULL == (str = (char *)malloc(length + strlen(value) + 1)))
487    {
488       return JB_ERR_MEMORY;
489    }
490    strcpy(str, name);
491    str[length - 2] = ':';
492    str[length - 1] = ' ';
493    strcpy(str + length, value);
494
495    result = enlist_unique(the_list, str, length);
496
497    free(str);
498
499    assert(list_is_valid(the_list));
500
501    return result;
502
503 }
504
505
506 /*********************************************************************
507  *
508  * Function    :  list_remove_all
509  *
510  * Description :  Remove all entries from a list.  On return, the_list
511  *                is a valid, empty list.  Note that this is similar
512  *                to destroy_list(), but the difference is that this
513  *                function guarantees that the list structure is still
514  *                valid after the call.
515  *
516  * Parameters  :
517  *          1  :  the_list = pointer to list
518  *
519  * Returns     :  N/A
520  *
521  *********************************************************************/
522 void list_remove_all(struct list *the_list)
523 {
524    struct list_entry *cur_entry;
525    struct list_entry *next_entry;
526
527    assert(the_list);
528    assert(list_is_valid(the_list));
529
530    for (cur_entry = the_list->first; cur_entry ; cur_entry = next_entry)
531    {
532       next_entry = cur_entry->next;
533       freez(cur_entry->str);
534       free(cur_entry);
535    }
536
537    the_list->first = the_list->last = NULL;
538
539    assert(list_is_valid(the_list));
540 }
541
542
543 /*********************************************************************
544  *
545  * Function    :  list_to_text
546  *
547  * Description :  "Flatten" a string list into 1 long \r\n delimited string,
548  *                adding an empty line at the end.  NULL entries are ignored.
549  *                This function does not change the_list.
550  *
551  * Parameters  :
552  *          1  :  the_list = pointer to list
553  *
554  * Returns     :  NULL on malloc error, else new long string.
555  *                Caller must free() it.
556  *
557  *********************************************************************/
558 char *list_to_text(const struct list *the_list)
559 {
560    struct list_entry *cur_entry;
561    char *ret = NULL;
562    char *s;
563    size_t size = 2;
564
565    assert(the_list);
566    assert(list_is_valid(the_list));
567
568    for (cur_entry = the_list->first; cur_entry ; cur_entry = cur_entry->next)
569    {
570       if (cur_entry->str)
571       {
572          size += strlen(cur_entry->str) + 2;
573       }
574    }
575
576    if ((ret = (char *)malloc(size + 1)) == NULL)
577    {
578       return NULL;
579    }
580
581    ret[size] = '\0';
582
583    s = ret;
584
585    for (cur_entry = the_list->first; cur_entry ; cur_entry = cur_entry->next)
586    {
587       if (cur_entry->str)
588       {
589          strcpy(s, cur_entry->str);
590          s += strlen(s);
591          *s++ = '\r'; *s++ = '\n';
592       }
593    }
594    *s++ = '\r'; *s++ = '\n';
595
596    return ret;
597 }
598
599
600 /*********************************************************************
601  *
602  * Function    :  list_remove_item
603  *
604  * Description :  Remove a string from a specified string list.
605  *
606  * Parameters  :
607  *          1  :  the_list = pointer to list
608  *          2  :  str = string to remove from the list - non-NULL
609  *
610  * Returns     :  Number of times it was removed.
611  *
612  *********************************************************************/
613 int list_remove_item(struct list *the_list, const char *str)
614 {
615    struct list_entry *prev = NULL;
616    struct list_entry *cur;
617    struct list_entry *next;
618    int count = 0;
619
620    assert(the_list);
621    assert(list_is_valid(the_list));
622    assert(str);
623
624    cur = the_list->first;
625
626    while (cur != NULL)
627    {
628       next = cur->next;
629
630       if ((cur->str != NULL) && (0 == strcmp(str, cur->str)))
631       {
632          count++;
633
634          if (prev != NULL)
635          {
636             prev->next = next;
637          }
638          else
639          {
640             the_list->first = next;
641          }
642          free((char *)cur->str);
643          free(cur);
644       }
645       else
646       {
647          prev = cur;
648       }
649       cur = next;
650    }
651
652    the_list->last = prev;
653
654    assert(list_is_valid(the_list));
655
656    return count;
657 }
658
659
660 /*********************************************************************
661  *
662  * Function    :  list_remove_list
663  *
664  * Description :  Remove all strings in one list from another list.
665  *                This is currently a brute-force algorithm
666  *                (it compares every pair of strings).
667  *
668  * Parameters  :
669  *          1  :  dest = list to change
670  *          2  :  src = list of strings to remove
671  *
672  * Returns     :  Total number of strings removed.
673  *
674  *********************************************************************/
675 int list_remove_list(struct list *dest, const struct list *src)
676 {
677    struct list_entry *cur;
678    int count = 0;
679
680    assert(src);
681    assert(dest);
682    assert(list_is_valid(src));
683    assert(list_is_valid(dest));
684
685    for (cur = src->first; cur != NULL; cur = cur->next)
686    {
687       if (cur->str != NULL)
688       {
689          count += list_remove_item(dest, cur->str);
690       }
691    }
692
693    assert(list_is_valid(src));
694    assert(list_is_valid(dest));
695
696    return count;
697 }
698
699
700 /*********************************************************************
701  *
702  * Function    :  list_duplicate
703  *
704  * Description :  Copy a string list
705  *
706  * Parameters  :
707  *          1  :  dest = Destination list.  Must be a valid list.
708  *                       All existing entries will be removed.
709  *          1  :  src = pointer to source list for copy.
710  *
711  * Returns     :  JB_ERR_OK on success
712  *                JB_ERR_MEMORY on out-of-memory error.
713  *                On error, dest will be empty.
714  *
715  *********************************************************************/
716 jb_err list_duplicate(struct list *dest, const struct list *src)
717 {
718    struct list_entry * cur_src;
719    struct list_entry * cur_dest;
720
721    assert(src);
722    assert(dest);
723    assert(list_is_valid(src));
724    assert(list_is_valid(dest));
725
726    list_remove_all(dest);
727
728    /* Need to process first entry specially so we can set dest->first */
729    cur_src = src->first;
730    if (cur_src)
731    {
732       cur_dest = dest->first = (struct list_entry *)zalloc(sizeof(*cur_dest));
733       if (cur_dest == NULL)
734       {
735          destroy_list(dest);
736
737          assert(list_is_valid(src));
738          assert(list_is_valid(dest));
739
740          return JB_ERR_MEMORY;
741       }
742
743       if (cur_src->str)
744       {
745          cur_dest->str = strdup(cur_src->str);
746          if (cur_dest->str == NULL)
747          {
748             destroy_list(dest);
749
750             assert(list_is_valid(src));
751             assert(list_is_valid(dest));
752
753             return JB_ERR_MEMORY;
754          }
755       }
756       /* else { cur_dest->str = NULL; }  - implied by zalloc */
757
758       /* Now process the rest */
759       for (cur_src = cur_src->next; cur_src; cur_src = cur_src->next)
760       {
761          cur_dest = cur_dest->next = (struct list_entry *)zalloc(sizeof(*cur_dest));
762          if (cur_dest == NULL)
763          {
764             destroy_list(dest);
765
766             assert(list_is_valid(src));
767             assert(list_is_valid(dest));
768
769             return JB_ERR_MEMORY;
770          }
771          if (cur_src->str)
772          {
773             cur_dest->str = strdup(cur_src->str);
774             if (cur_dest->str == NULL)
775             {
776                destroy_list(dest);
777
778                assert(list_is_valid(src));
779                assert(list_is_valid(dest));
780
781                return JB_ERR_MEMORY;
782             }
783          }
784          /* else { cur_dest->str = NULL; }  - implied by zalloc */
785       }
786
787       dest->last = cur_dest;
788    }
789
790    assert(list_is_valid(src));
791    assert(list_is_valid(dest));
792
793    return JB_ERR_OK;
794 }
795
796
797 /*********************************************************************
798  *
799  * Function    :  list_append_list_unique
800  *
801  * Description :  Append a string list to another list.
802  *                Duplicate items are not added.
803  *
804  * Parameters  :
805  *          1  :  dest = pointer to destination list for merge.
806  *          2  :  src = pointer to source for merge.
807  *
808  * Returns     :  JB_ERR_OK on success
809  *                JB_ERR_MEMORY on out-of-memory error.
810  *                On error, some (but not all) of src might have
811  *                been copied into dest.
812  *
813  *********************************************************************/
814 jb_err list_append_list_unique(struct list *dest, const struct list *src)
815 {
816    struct list_entry * cur;
817
818    assert(src);
819    assert(dest);
820    assert(list_is_valid(src));
821    assert(list_is_valid(dest));
822
823    for (cur = src->first; cur; cur = cur->next)
824    {
825       if (cur->str)
826       {
827          if (enlist_unique(dest, cur->str, 0))
828          {
829             assert(list_is_valid(src));
830             assert(list_is_valid(dest));
831
832             return JB_ERR_MEMORY;
833          }
834       }
835    }
836
837    assert(list_is_valid(src));
838    assert(list_is_valid(dest));
839
840    return JB_ERR_OK;
841 }
842
843
844 /*********************************************************************
845  *
846  * Function    :  list_is_empty
847  *
848  * Description :  Test whether a list is empty.  Does not change the list.
849  *
850  * Parameters  :
851  *          1  :  the_list = pointer to list to test.
852  *
853  * Returns     :  Nonzero iff the list contains no entries.
854  *
855  *********************************************************************/
856 int list_is_empty(const struct list *the_list)
857 {
858    assert(the_list);
859    assert(list_is_valid(the_list));
860
861    return (the_list->first == NULL);
862 }
863
864
865 /*********************************************************************
866  *
867  * Function    :  new_map
868  *
869  * Description :  Create a new, empty map.
870  *
871  * Parameters  :  N/A
872  *
873  * Returns     :  A new, empty map, or NULL if out of memory.
874  *
875  *********************************************************************/
876 struct map *new_map(void)
877 {
878    return (struct map *) zalloc(sizeof(struct map));
879 }
880
881
882 /*********************************************************************
883  *
884  * Function    :  free_map
885  *
886  * Description :  Free the memory occupied by a map and its
887  *                depandant strings
888  *
889  * Parameters  :
890  *          1  :  the_map = map to be freed.  May be NULL.
891  *
892  * Returns     :  N/A
893  *
894  *********************************************************************/
895 void free_map(struct map *the_map)
896 {
897    struct map_entry *cur_entry;
898    struct map_entry *next_entry;
899
900    if (the_map == NULL)
901    {
902       return;
903    }
904
905    for (cur_entry = the_map->first; cur_entry != NULL; cur_entry = next_entry)
906    {
907       freez(cur_entry->name);
908       freez(cur_entry->value);
909
910       next_entry = cur_entry->next;
911       free(cur_entry);
912    }
913
914    the_map->first = the_map->last = NULL;
915
916    free(the_map);
917 }
918
919
920 /*********************************************************************
921  *
922  * Function    :  map
923  *
924  * Description :  Add a mapping from given name to given value to a
925  *                given map.
926  *
927  *                Note: Since all strings will be free()d in free_map()
928  *                      later, set the copy flags for constants or
929  *                      strings that will be independantly free()d.
930  *
931  *                Note2: This function allows NULL parameters - it
932  *                       returns JB_ERR_MEMORY in that case.
933  *
934  *                Note3: If this function returns JB_ERR_MEMORY,
935  *                       it will free(name) unless you specify
936  *                       name_needs_copying, and similarly it will
937  *                       free(value) unless you specify
938  *                       value_needs_copying.
939  *
940  *                Due to Note2 and Note3 above, the following code
941  *                is legal, and will never crash or leak memory even
942  *                if the system runs out of memory:
943  *
944  *                    err = map(mymap, "xyz", 1, html_encode(somestring), 0);
945  *
946  *                err will be set to JB_ERR_MEMORY if either call runs
947  *                out-of-memory.  Without these features, you would
948  *                need to check the return value of html_encode in the
949  *                above example for NULL, which (at least) doubles the
950  *                amount of error-checking code needed.
951  *
952  * Parameters  :
953  *          1  :  the_map = map to add to
954  *          2  :  name = name to add
955  *          3  :  name_needs_copying = flag set if a copy of name should be used
956  *          4  :  value = value to add
957  *          5  :  value_needs_copying = flag set if a copy of value should be used
958  *
959  * Returns     :  JB_ERR_OK on success
960  *                JB_ERR_MEMORY on out-of-memory error.
961  *
962  *********************************************************************/
963 jb_err map(struct map *the_map,
964            const char *name, int name_needs_copying,
965            const char *value, int value_needs_copying)
966 {
967    struct map_entry *new_entry;
968
969    assert(the_map);
970
971    if ( (NULL == value)
972      || (NULL == name)
973      || (NULL == (new_entry = zalloc(sizeof(*new_entry)))) )
974    {
975       if ((name != NULL) && (!name_needs_copying))
976       {
977           free((char *)name);
978       }
979       if ((value != NULL) && (!value_needs_copying))
980       {
981           free((char *)value);
982       }
983       return JB_ERR_MEMORY;
984    }
985
986    if (name_needs_copying)
987    {
988       if (NULL == (name = strdup(name)))
989       {
990          free(new_entry);
991          if (!value_needs_copying)
992          {
993              free((char *)value);
994          }
995          return JB_ERR_MEMORY;
996       }
997    }
998
999    if (value_needs_copying)
1000    {
1001       if (NULL == (value = strdup(value)))
1002       {
1003          free((char *)name);
1004          free(new_entry);
1005          return JB_ERR_MEMORY;
1006       }
1007    }
1008
1009    new_entry->name = name;
1010    new_entry->value = value;
1011    /* new_entry->next = NULL;  - implied by zalloc */
1012
1013    if (the_map->last)
1014    {
1015       the_map->last->next = new_entry;
1016       the_map->last = new_entry;
1017    }
1018    else
1019    {
1020       the_map->first = new_entry;
1021       the_map->last = new_entry;
1022    }
1023
1024    return JB_ERR_OK;
1025 }
1026
1027
1028 /*********************************************************************
1029  *
1030  * Function    :  lookup
1031  *
1032  * Description :  Look up an item with a given name in a map, and
1033  *                return its value
1034  *
1035  * Parameters  :
1036  *          1  :  the_map = map to look in
1037  *          2  :  name = name parameter to look for
1038  *
1039  * Returns     :  the value if found, else the empty string.
1040  *                Return value is alloced as part of the map, so
1041  *                it is freed when the map is destroyed.  Caller
1042  *                must not free or modify it.
1043  *
1044  *********************************************************************/
1045 const char *lookup(const struct map *the_map, const char *name)
1046 {
1047    const struct map_entry *cur_entry;
1048
1049    assert(the_map);
1050    assert(name);
1051
1052    for (cur_entry = the_map->first; cur_entry != NULL; cur_entry = cur_entry->next)
1053    {
1054       if (!strcmp(name, cur_entry->name))
1055       {
1056          return cur_entry->value;
1057       }
1058    }
1059    return "";
1060 }
1061
1062
1063 /*
1064   Local Variables:
1065   tab-width: 3
1066   end:
1067 */