rework lists
[rmail.git] / src / utils / list.c
blob6b08f3fc2d5f2c945cd9cede33c0ce3aff4dbcb7
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
6 #include "list.h"
8 /*#define DEBUG*/
10 void list_print(struct mail_list *lst)
12 size_t n;
14 if (!lst)
15 return;
17 for (n = 0; n < lst->n; n++) {
18 fprintf(stderr, "[%u] ", n);
19 print_mail_header(&lst->list[n].hdr);
23 /**
24 * Allocate a list via malloc of n_elem elements
26 * @param[in|out] n_elem number of elements in the list
27 * @param[in] limit max number of elements
29 * @retval Pointer to the new allocated list or NULL on error
31 struct mail_list *list_create(size_t n_elem, size_t limit)
33 struct mail_list *lst;
35 if (n_elem == 0)
36 return NULL;
38 if (n_elem > limit)
39 n_elem = limit;
41 lst = malloc(sizeof(struct mail_list) + n_elem * sizeof(struct mail_entry));
42 if (!lst) {
43 fprintf(stderr, "%s - MALLOC: %s", __func__, strerror(errno));
44 return NULL;
47 #ifdef DEBUG
48 fprintf(stderr, "%s - MALLOC: item %lu [%lu]\n", __func__,
49 (unsigned long) n_elem,
50 (unsigned long) (sizeof(struct mail_list) + n_elem * sizeof(struct mail_entry)));
51 #endif
53 lst->n = n_elem;
54 lst->nfree = 0;
56 return lst;
59 void list_free(struct mail_list *lst)
61 if (lst) {
62 free(lst);
63 lst = NULL;
64 #ifdef DEBUG
65 fprintf(stderr, "%s - FREE: list\n", __func__);
66 #endif
70 int list_add_entry(struct mail_list *lst, struct mail_entry *entry)
72 size_t n = 0;
74 if (lst->nfree < LIST_LIMIT) {
75 n = lst->nfree;
76 /* Update List */
77 memcpy(&lst->list[n], entry, sizeof(struct mail_entry));
79 /* Update 1st free slot index */
80 lst->nfree += 1;
81 return 0;
84 /* No free slot */
85 return -1;