aboutsummaryrefslogtreecommitdiff
path: root/src/librc-strlist.c
blob: 126ec78e73a7e095f2b01a1a65435170e58e8c1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
   librc-strlist.h
   String list functions for using char ** arrays

   Copyright 2007 Gentoo Foundation
   Based on a previous implementation by Martin Schlemmer
   Released under the GPLv2
   */

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include "rc.h"
#include "rc-misc.h"

char **rc_strlist_add (char **list, const char *item)
{
  char **newlist;
  int i = 0;

  if (! item)
    return (list);

  while (list && list[i])
    i++;

  newlist = rc_xrealloc (list, sizeof (char *) * (i + 2));
  newlist[i] = rc_xstrdup (item);
  newlist[i + 1] = NULL;

  return (newlist);
}

static char **_rc_strlist_addsort (char **list, const char *item,
				   int (*sortfunc) (const char *s1,
						    const char *s2))
{
  char **newlist;
  int i = 0;
  char *tmp1;
  char *tmp2;

  if (! item)
    return (list);

  while (list && list[i])
    i++;

  newlist = rc_xrealloc (list, sizeof (char *) * (i + 2));

  if (! i)
    newlist[i] = NULL;
  newlist[i + 1] = NULL;

  i = 0;
  while (newlist[i] && sortfunc (newlist[i], item) < 0)
    i++;

  tmp1 = newlist[i];
  newlist[i] = rc_xstrdup (item);
  do
    {
      i++;
      tmp2 = newlist[i];
      newlist[i] = tmp1;
      tmp1 = tmp2;
    } while (tmp1);

  return (newlist);
}

char **rc_strlist_addsort (char **list, const char *item)
{
  return (_rc_strlist_addsort (list, item, strcoll));
}

char **rc_strlist_addsortc (char **list, const char *item)
{
  return (_rc_strlist_addsort (list, item, strcmp));
}

char **rc_strlist_delete (char **list, const char *item)
{
  int i = 0;

  if (!list || ! item)
    return (list);

  while (list[i])
    if (! strcmp (list[i], item))
      {
	free (list[i]);
	do
	  {
	    list[i] = list[i + 1];
	    i++;
	  } while (list[i]);
      }

  return (list);
}

void rc_strlist_reverse (char **list)
{
  char *item;
  int i = 0;
  int j = 0;

  if (! list)
    return;

  while (list[j])
    j++;
  j--;

  while (i < j && list[i] && list[j])
    {
      item = list[i];
      list[i] = list[j];
      list[j] = item;
      i++;
      j--;
    }
}

void rc_strlist_free (char **list)
{
  int i = 0;

  if (! list)
    return;

  while (list[i])
    {
      free (list[i]);
      list[i++] = NULL;
    }

  free (list);
}