2 * Copyright 2006 Jon Loeliger
7 #include "interpolate.h"
11 * Convert a NUL-terminated string in buffer orig
12 * into the supplied buffer, result, whose length is reslen,
13 * performing substitutions on %-named sub-strings from
14 * the table, interps, with ninterps entries.
18 * { "%H", "example.org"},
23 * Returns 1 on a successful substitution pass that fits in result,
24 * Returns 0 on a failed or overflowing substitution pass.
27 int interpolate(char *result
, int reslen
,
29 const struct interp
*interps
, int ninterps
)
31 const char *src
= orig
;
35 int namelen
, valuelen
;
39 memset(result
, 0, reslen
);
41 while ((c
= *src
) && newlen
< reslen
- 1) {
43 /* Try to match an interpolation string. */
44 for (i
= 0; i
< ninterps
; i
++) {
45 name
= interps
[i
].name
;
46 namelen
= strlen(name
);
47 if (strncmp(src
, name
, namelen
) == 0) {
52 /* Check for valid interpolation. */
54 value
= interps
[i
].value
;
55 valuelen
= strlen(value
);
57 if (newlen
+ valuelen
< reslen
- 1) {
59 strncpy(dest
, value
, valuelen
);
64 /* Something's not fitting. */
69 /* Skip bogus interpolation. */
75 /* Straight copy one non-interpolation character. */
81 return newlen
< reslen
- 1;