2 * Copyright 2006 Jon Loeliger
5 #include "git-compat-util.h"
6 #include "interpolate.h"
9 void interp_set_entry(struct interp
*table
, int slot
, const char *value
)
11 char *oldval
= table
[slot
].value
;
17 newval
= xstrdup(value
);
19 table
[slot
].value
= newval
;
23 void interp_clear_table(struct interp
*table
, int ninterps
)
27 for (i
= 0; i
< ninterps
; i
++) {
28 interp_set_entry(table
, i
, NULL
);
34 * Convert a NUL-terminated string in buffer orig
35 * into the supplied buffer, result, whose length is reslen,
36 * performing substitutions on %-named sub-strings from
37 * the table, interps, with ninterps entries.
41 * { "%H", "example.org"},
46 * Returns the length of the substituted string (not including the final \0).
47 * Like with snprintf, if the result is >= reslen, then it overflowed.
50 unsigned long interpolate(char *result
, unsigned long reslen
,
52 const struct interp
*interps
, int ninterps
)
54 const char *src
= orig
;
56 unsigned long newlen
= 0;
57 const char *name
, *value
;
58 unsigned long namelen
, valuelen
;
64 /* Try to match an interpolation string. */
65 for (i
= 0; i
< ninterps
; i
++) {
66 name
= interps
[i
].name
;
67 namelen
= strlen(name
);
68 if (strncmp(src
, name
, namelen
) == 0)
72 /* Check for valid interpolation. */
74 value
= interps
[i
].value
;
80 valuelen
= strlen(value
);
81 if (newlen
+ valuelen
< reslen
) {
83 memcpy(dest
, value
, valuelen
);
91 /* Straight copy one non-interpolation character. */
92 if (newlen
+ 1 < reslen
)
98 /* XXX: the previous loop always keep room for the ending NUL,
99 we just need to check if there was room for a NUL in the first place */