Fix a few 'gcc -fanalyzer' warnings.
[pwmd.git] / src / util-slist.c
blobe6e68dbec55f47f167ba9f294f4c30af1344e23a
1 /*
2 Copyright (C) 2012-2023 Ben Kibbey <bjk@luxsci.net>
4 This file is part of pwmd.
6 Pwmd is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License version 2 as
8 published by the Free Software Foundation.
10 Pwmd is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
18 #ifdef HAVE_CONFIG_H
19 #include <config.h>
20 #endif
22 #include <stdio.h>
23 #include "util-slist.h"
24 #include "mem.h"
26 unsigned
27 slist_length (struct slist_s *list)
29 struct slist_s *cur;
30 unsigned n = 0;
32 for (cur = list; cur; cur = cur->next)
33 n++;
35 return n;
38 void *
39 slist_nth_data (struct slist_s *list, unsigned n)
41 struct slist_s *cur;
42 unsigned i;
44 for (i = 0, cur = list; cur; cur = cur->next, i++)
46 if (i == n)
47 return cur->data;
50 return NULL;
53 struct slist_s *
54 slist_append (struct slist_s *list, void *data)
56 struct slist_s *cur;
58 if (!list)
60 cur = xcalloc (1, sizeof (struct slist_s));
61 cur->data = data;
62 return cur;
65 for (cur = list; cur; cur = cur->next)
67 if (!cur->next)
68 break;
71 cur->next = xcalloc (1, sizeof (struct slist_s));
72 cur->next->data = data;
73 return list;
76 static struct slist_s *
77 free_once (struct slist_s *cur)
79 struct slist_s *next = cur ? cur->next : NULL;
81 xfree (cur);
82 return next;
85 void
86 slist_free (struct slist_s *list)
88 while (list)
89 list = free_once (list);
92 struct slist_s *
93 slist_remove (struct slist_s *list, void *data)
95 struct slist_s *prev, *cur;
97 for (cur = prev = list; cur; prev = cur, cur = cur->next)
99 if (cur->data == data)
101 struct slist_s *next = free_once (cur);
103 if (cur != list)
104 prev->next = next;
105 else
106 list = next;
107 break;
111 return list;