From 46fac92f6c2877cc043023c886d61b7b9d314df5 Mon Sep 17 00:00:00 2001 From: Mike Brady Date: Sat, 21 May 2016 13:05:15 +0100 Subject: [PATCH] Add a utility for string substitution, rename apname to service_name --- common.c | 30 ++++++++++++++++++++++++++++++ common.h | 5 ++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/common.c b/common.c index 6ca577e9..f8a8e2a4 100644 --- a/common.c +++ b/common.c @@ -537,3 +537,33 @@ ssize_t non_blocking_write(int fd, const void *buf, size_t count) { // return write(fd,buf,count); } +/* from http://coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring#comment-722 */ + +char *str_replace ( const char *string, const char *substr, const char *replacement ){ + char *tok = NULL; + char *newstr = NULL; + char *oldstr = NULL; + char *head = NULL; + + /* if either substr or replacement is NULL, duplicate string a let caller handle it */ + if ( substr == NULL || replacement == NULL ) return strdup (string); + newstr = strdup (string); + head = newstr; + while ( (tok = strstr ( head, substr ))){ + oldstr = newstr; + newstr = malloc ( strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 ); + /*failed to alloc mem, free old string and return NULL */ + if ( newstr == NULL ){ + free (oldstr); + return NULL; + } + memcpy ( newstr, oldstr, tok - oldstr ); + memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) ); + memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) ); + memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 ); + /* move back head right after the last replacement */ + head = newstr + (tok - oldstr) + strlen( replacement ); + free (oldstr); + } + return newstr; +} diff --git a/common.h b/common.h index 6e5331d5..dc44af4c 100644 --- a/common.h +++ b/common.h @@ -51,7 +51,7 @@ enum playback_mode_type { typedef struct { config_t *cfg; char *password; - char *apname; + char *service_name; // the name for the shairport service, e.g. "Shairport Sync Version %v running on host %h" #ifdef CONFIG_METADATA int metadata_enabled; char *metadata_pipename; @@ -110,6 +110,9 @@ void set_requested_connection_state_to_output(int v); ssize_t non_blocking_write(int fd, const void *buf, size_t count); // used in a few places +/* from http://coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring#comment-722 */ +char *str_replace ( const char *string, const char *substr, const char *replacement ); + int debuglev; void die(char *format, ...); void warn(char *format, ...);