ap

Queue manager meant to be used as an audio player
git clone git://jacobedwards.org/ap
Log | Files | Refs | README | LICENSE

arg.c (1624B)


      1 /*
      2  * Copyright 2021, 2022 Jacob R. Edwards
      3  *
      4  * ap -- audio player
      5  *
      6  * This program is free software: you can redistribute it and/or modify
      7  * it under the terms of the GNU General Public License as published by
      8  * the Free Software Foundation, either version 3 of the License, or
      9  * (at your option) any later version.
     10  *
     11  * This program is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     14  * GNU General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU General Public License
     17  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
     18  */
     19 
     20 #include <string.h>
     21 #include <stdlib.h>
     22 
     23 unsigned int
     24 arglen(char **args)
     25 {
     26 	unsigned int i;
     27 
     28 	if (args == NULL)
     29 		return 0;
     30 	for (i = 0; args[i] != NULL; ++i)
     31 		;
     32 	return i;
     33 }
     34 
     35 char **
     36 argdup(char **args, unsigned int len)
     37 {
     38 	char **nargs;
     39 	unsigned int i;
     40 
     41 	if (!len)
     42 		len = arglen(args);
     43 	nargs = calloc(len + 1, sizeof(*args));
     44 	if (nargs == NULL)
     45 		return NULL;
     46 
     47 	for (i = 0; args[i] && i < len; ++i) {
     48 		nargs[i] = strdup(args[i]);
     49 		if (nargs[i] == NULL)
     50 			break;
     51 	}
     52 
     53 	if (!args[i] || i == len)
     54 		return nargs;
     55 
     56 	for (i = 0; nargs[i] != NULL; ++i)
     57 		free(nargs[i]);
     58 	free(nargs);
     59 	return NULL;
     60 }
     61 
     62 void
     63 argfree(char **args)
     64 {
     65 	unsigned int len, i;
     66 
     67 	len = arglen(args);
     68 	for (i = 0; i < len; ++i)
     69 		free(args[i]);
     70 	free(args);
     71 }
     72 
     73 char **
     74 argsub(char ***p, char **args, unsigned int len)
     75 {
     76 	args = argdup(args, len);
     77 	if (args == NULL)
     78 		return NULL;
     79 	argfree(*p);
     80 	*p = args;
     81 	return args;
     82 }