2 * Copyright 2006 Jon Loeliger
7 #include "git-compat-util.h"
8 #include "interpolate.h"
11 void interp_set_entry(struct interp
*table
, int slot
, const char *value
)
13 char *oldval
= table
[slot
].value
;
20 newval
= xstrdup(value
);
22 table
[slot
].value
= newval
;
26 void interp_clear_table(struct interp
*table
, int ninterps
)
30 for (i
= 0; i
< ninterps
; i
++) {
31 interp_set_entry(table
, i
, NULL
);
37 * Convert a NUL-terminated string in buffer orig
38 * into the supplied buffer, result, whose length is reslen,
39 * performing substitutions on %-named sub-strings from
40 * the table, interps, with ninterps entries.
44 * { "%H", "example.org"},
49 * Returns 1 on a successful substitution pass that fits in result,
50 * Returns 0 on a failed or overflowing substitution pass.
53 int interpolate(char *result
, int reslen
,
55 const struct interp
*interps
, int ninterps
)
57 const char *src
= orig
;
61 int namelen
, valuelen
;
65 memset(result
, 0, reslen
);
67 while ((c
= *src
) && newlen
< reslen
- 1) {
69 /* Try to match an interpolation string. */
70 for (i
= 0; i
< ninterps
; i
++) {
71 name
= interps
[i
].name
;
72 namelen
= strlen(name
);
73 if (strncmp(src
, name
, namelen
) == 0) {
78 /* Check for valid interpolation. */
80 value
= interps
[i
].value
;
81 valuelen
= strlen(value
);
83 if (newlen
+ valuelen
< reslen
- 1) {
85 strncpy(dest
, value
, valuelen
);
90 /* Something's not fitting. */
95 /* Skip bogus interpolation. */
101 /* Straight copy one non-interpolation character. */
107 return newlen
< reslen
- 1;