1 #include <stdio.h>
   2 #include <stdlib.h>
   3 #include <libintl.h>
   4 #include "lst.h"
   5 #include "util.h"
   6 
   7 
   8 void
   9 lst_create(lst_t *plst)
  10 {
  11         plst->csz = 0;
  12         plst->tsz = 0;
  13         plst->buf = NULL;
  14 }
  15 
  16 int
  17 lst_is_empty(lst_t *plst)
  18 {
  19         return (plst->csz == 0);
  20 }
  21 
  22 void
  23 lst_insert_head(lst_t *plst, void *ndata)
  24 {
  25         int i;
  26         if (plst->csz == plst->tsz) {
  27                 plst->tsz = (plst->tsz == 0) ? 1 : plst->tsz * 2;
  28                 plst->buf = util_safe_realloc(plst->buf,
  29                     plst->tsz * sizeof (void *));
  30         }
  31 
  32         for (i = plst->csz; i > 0; i--)
  33                 plst->buf[i] = plst->buf[i - 1];
  34 
  35         plst->buf[0] = ndata;
  36         plst->csz++;
  37 }
  38 
  39 
  40 void
  41 lst_insert_tail(lst_t *plst, void *ndata)
  42 {
  43         if (plst->csz == plst->tsz) {
  44                 plst->tsz = (plst->tsz == 0) ? 1 : plst->tsz * 2;
  45                 plst->buf = util_safe_realloc(plst->buf,
  46                     plst->tsz * sizeof (void *));
  47         }
  48 
  49         plst->buf[plst->csz++] = ndata;
  50 }
  51 
  52 int
  53 lst_remove(lst_t *plst, void *rdata)
  54 {
  55         int i, idx = -1;
  56         for (i = 0; i < plst->csz; i++) {
  57                 if (plst->buf[i] == rdata) {
  58                         idx = i;
  59                         break;
  60                 }
  61         }
  62         if (idx >= 0) {
  63                 for (i = idx; i < plst->csz - 1; i++)
  64                         plst->buf[i] = plst->buf[i + 1];
  65 
  66                 if (--plst->csz == 0) {
  67                         plst->tsz = 0;
  68                         free(plst->buf);
  69                         plst->buf = NULL;
  70                 }
  71                 return (0);
  72         }
  73         return (-1);
  74 }
  75 
  76 void
  77 *lst_at(lst_t *plst, int idx)
  78 {
  79         if (idx < 0 || idx >= plst->csz) {
  80                 (void) fprintf(stderr, gettext(
  81                     "error accessing element outside lst\n"));
  82                 exit(1);
  83         }
  84         return (plst->buf[idx]);
  85 }
  86 
  87 void
  88 *lst_replace_at(lst_t *plst, int idx, void *ndata)
  89 {
  90         void *odata;
  91 
  92         if (idx < 0 || idx >= plst->csz) {
  93                 (void) fprintf(stderr, gettext(
  94                     "error accessing element outside lst\n"));
  95                 exit(1);
  96         }
  97         odata = plst->buf[idx];
  98         plst->buf[idx] = ndata;
  99         return (odata);
 100 }
 101 
 102 int
 103 lst_size(lst_t *plst)
 104 {
 105         return (plst->csz);
 106 }