Created
June 12, 2020 07:28
-
-
Save jaz303/9e7ba38fa074a09c8720443e9ad1f7a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
static int do_sub(const char *key, size_t key_len, char *buffer, size_t buffer_len) { | |
if (strncmp("HWVERSION", key, key_len) == 0) { | |
return snprintf(buffer, buffer_len, "%d.%d.%d", 1, 2, 3); | |
} else if (strncmp("xyzzy", key, key_len) == 0) { | |
return snprintf(buffer, buffer_len, "%s", "quux"); | |
} else { | |
return 0; | |
} | |
} | |
// needs error handling | |
void substitute(const char *tpl, char *buffer, size_t buffer_len) { | |
const char *vstart; | |
char *wp = buffer; | |
char *end = wp + buffer_len; | |
int state = 0; | |
while (*tpl) { | |
switch (state) { | |
case 0: | |
if (*tpl == '%') { | |
vstart = tpl+1; | |
state = 1; | |
} else { | |
*wp++ = *tpl; | |
} | |
break; | |
case 1: | |
if (*tpl == '%') { | |
int cap = end - wp; | |
int written = do_sub(vstart, tpl - vstart, wp, end - wp); | |
if (written >= cap) { | |
// TODO: handle error | |
} | |
wp += written; | |
state = 0; | |
} | |
break; | |
} | |
tpl++; | |
} | |
*wp++ = 0; | |
} | |
int main(int argc, char *argv[]) { | |
const char *tpl = "http://myapi.com/%HWVERSION%/blah/%xyzzy%/%ERROR%"; | |
char buffer[128]; | |
substitute(tpl, buffer, 128); | |
puts(buffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment