| 1 |
/* |
| 2 |
stringlists: creation of paired string lists for one-time consumption |
| 3 |
|
| 4 |
copyright 2015-2021 by the mpg123 project |
| 5 |
free software under the terms of the LGPL 2.1 |
| 6 |
see COPYING and AUTHORS files in distribution or http://mpg123.org |
| 7 |
initially written by Thomas Orgis |
| 8 |
|
| 9 |
Thomas did not want to introduce a list type complete with management |
| 10 |
functions just for returning driver module lists. |
| 11 |
*/ |
| 12 |
|
| 13 |
#include "../compat/compat.h" |
| 14 |
#include "out123.h" |
| 15 |
|
| 16 |
static char* always_strdup(const char *in) |
| 17 |
{ |
| 18 |
char *out = in ? INT123_compat_strdup(in) : malloc(1); |
| 19 |
if(!in && out) |
| 20 |
out[0] = 0; |
| 21 |
return out; |
| 22 |
} |
| 23 |
|
| 24 |
/* Construction helper for paired string lists. |
| 25 |
Returns 0 on success. */ |
| 26 |
// Also converts NULL to empty string for safer use later. |
| 27 |
int INT123_stringlists_add( char ***alist, char ***blist |
| 28 |
, const char *atext, const char *btext, int *count) |
| 29 |
{ |
| 30 |
char *atextcopy = NULL; |
| 31 |
char *btextcopy = NULL; |
| 32 |
char **morealist = NULL; |
| 33 |
char **moreblist = NULL; |
| 34 |
|
| 35 |
/* If one of these succeeded, the old memory is gone, so always overwrite |
| 36 |
the old pointer, worst case is wasted but not leaked memory in an |
| 37 |
out-of-memory situation. */ |
| 38 |
if((morealist = INT123_safe_realloc(*alist, sizeof(char*)*(*count+1)))) |
| 39 |
*alist = morealist; |
| 40 |
if((moreblist = INT123_safe_realloc(*blist, sizeof(char*)*(*count+1)))) |
| 41 |
*blist = moreblist; |
| 42 |
if(!morealist || !moreblist) |
| 43 |
return -1; |
| 44 |
|
| 45 |
if( |
| 46 |
(atextcopy = always_strdup(atext)) |
| 47 |
&& (btextcopy = always_strdup(btext)) |
| 48 |
) |
| 49 |
{ |
| 50 |
(*alist)[*count] = atextcopy; |
| 51 |
(*blist)[*count] = btextcopy; |
| 52 |
++*count; |
| 53 |
return 0; |
| 54 |
} |
| 55 |
else |
| 56 |
{ |
| 57 |
free(btextcopy); |
| 58 |
free(atextcopy); |
| 59 |
return -1; |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
void out123_stringlists_free(char **alist, char **blist, int count) |
| 64 |
{ |
| 65 |
if(alist) |
| 66 |
{ |
| 67 |
for(int i=0; i<count; ++i) |
| 68 |
free(alist[i]); |
| 69 |
free(alist); |
| 70 |
} |
| 71 |
if(blist) |
| 72 |
{ |
| 73 |
for(int i=0; i<count; ++i) |
| 74 |
free(blist[i]); |
| 75 |
free(blist); |
| 76 |
} |
| 77 |
} |