libmpdserver

Parser combinator library for MPD client commands

git clone https://git.8pit.net/libmpdserver.git

  1#include <ctype.h>
  2#include <err.h>
  3#include <stddef.h>
  4#include <stdlib.h>
  5#include <string.h>
  6
  7#include <sys/types.h>
  8
  9#include "fns.h"
 10
 11void *
 12xmalloc(size_t size)
 13{
 14	void *r;
 15
 16	if (!(r = malloc(size)))
 17		err(EXIT_FAILURE, "malloc failed");
 18
 19	return r;
 20}
 21
 22char *
 23xstrdup(char *s)
 24{
 25	char *r;
 26
 27	if (!(r = strdup(s)))
 28		err(EXIT_FAILURE, "strdup failed");
 29
 30	return r;
 31}
 32
 33void *
 34xrealloc(void *ptr, size_t size)
 35{
 36	void *r;
 37
 38	if (!(r = realloc(ptr, size)))
 39		err(EXIT_FAILURE, "realloc failed");
 40
 41	return r;
 42}
 43
 44char *
 45lowercase(char *str)
 46{
 47	size_t i;
 48
 49	for (i = 0; i < strlen(str); i++)
 50		str[i] = (char)tolower(str[i]);
 51
 52	return str;
 53}
 54
 55mpd_range_t *
 56mpd_new_range(size_t start, ssize_t end)
 57{
 58	mpd_range_t *range;
 59
 60	range = xmalloc(sizeof(*range));
 61	range->start = start;
 62	range->end = end;
 63
 64	return range;
 65}
 66
 67mpd_command_t *
 68mpd_new_command(char *name, size_t argc)
 69{
 70	mpd_command_t *cmd;
 71
 72	cmd = xmalloc(sizeof(*cmd));
 73	cmd->name = name; /* might be NULL */
 74	cmd->argc = argc;
 75
 76	if (argc > 0)
 77		cmd->argv = xmalloc(sizeof(mpd_argument_t *) * argc);
 78	else
 79		cmd->argv = NULL;
 80
 81	return cmd;
 82}
 83
 84static void
 85mpd_free_argument(mpd_argument_t *arg)
 86{
 87	if (arg->type == MPD_VAL_STR || arg->type == MPD_VAL_EXPR_STR)
 88		free(arg->v.sval);
 89	else if (arg->type == MPD_VAL_CMD)
 90		mpd_free_command(arg->v.cmdval);
 91	else if (arg->type == MPD_VAL_EXPR)
 92		mpd_free_expression(arg->v.eval);
 93	free(arg);
 94}
 95
 96void
 97mpd_free_command(mpd_command_t *cmd)
 98{
 99	size_t i;
100
101	if (cmd->name)
102		free(cmd->name);
103	for (i = 0; i < cmd->argc; i++)
104		mpd_free_argument(cmd->argv[i]);
105	if (cmd->argv)
106		free(cmd->argv);
107	free(cmd);
108}