Skip to content

Instantly share code, notes, and snippets.

@jaz303
Created June 12, 2020 07:28
Show Gist options
  • Save jaz303/9e7ba38fa074a09c8720443e9ad1f7a6 to your computer and use it in GitHub Desktop.
Save jaz303/9e7ba38fa074a09c8720443e9ad1f7a6 to your computer and use it in GitHub Desktop.
#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