summaryrefslogtreecommitdiff
path: root/interpolate.c
blob: 4570c123dce811bab8a89efe4c3b4a9a977e6c5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * Copyright 2006 Jon Loeliger
 */

#include <string.h>

#include "interpolate.h"


/*
 * Convert a NUL-terminated string in buffer orig
 * into the supplied buffer, result, whose length is reslen,
 * performing substitutions on %-named sub-strings from
 * the table, interps, with ninterps entries.
 *
 * Example interps:
 *    {
 *        { "%H", "example.org"},
 *        { "%port", "123"},
 *        { "%%", "%"},
 *    }
 *
 * Returns 1 on a successful substitution pass that fits in result,
 * Returns 0 on a failed or overflowing substitution pass.
 */

int interpolate(char *result, int reslen,
		const char *orig,
		const struct interp *interps, int ninterps)
{
	const char *src = orig;
	char *dest = result;
	int newlen = 0;
	char *name, *value;
	int namelen, valuelen;
	int i;
	char c;

        memset(result, 0, reslen);

	while ((c = *src) && newlen < reslen - 1) {
		if (c == '%') {
			/* Try to match an interpolation string. */
			for (i = 0; i < ninterps; i++) {
				name = interps[i].name;
				namelen = strlen(name);
				if (strncmp(src, name, namelen) == 0) {
					break;
				}
			}

			/* Check for valid interpolation. */
			if (i < ninterps) {
				value = interps[i].value;
				valuelen = strlen(value);

				if (newlen + valuelen < reslen - 1) {
					/* Substitute. */
					strncpy(dest, value, valuelen);
					newlen += valuelen;
					dest += valuelen;
					src += namelen;
				} else {
					/* Something's not fitting. */
					return 0;
				}

			} else {
				/* Skip bogus interpolation. */
				*dest++ = *src++;
				newlen++;
			}

		} else {
			/* Straight copy one non-interpolation character. */
			*dest++ = *src++;
			newlen++;
		}
	}

	return newlen < reslen - 1;
}