Add a utility for string substitution, rename apname to service_name

This commit is contained in:
Mike Brady
2016-05-21 13:05:15 +01:00
parent 16b6f5d711
commit 46fac92f6c
2 changed files with 34 additions and 1 deletions
+30
View File
@@ -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;
}
+4 -1
View File
@@ -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, ...);