Fix the %Q printf extension to behave as expected

This commit is contained in:
phk 2006-03-02 08:53:45 +00:00
parent d250185c5c
commit 0ef226b65a

View File

@ -50,31 +50,23 @@ int
__printf_render_quote(struct __printf_io *io, const struct printf_info *pi __unused, const void *const *arg) __printf_render_quote(struct __printf_io *io, const struct printf_info *pi __unused, const void *const *arg)
{ {
const char *str, *p, *t, *o; const char *str, *p, *t, *o;
char *q, *r; char r[5];
int i, ret; int i, ret;
str = *((const char *const *)arg[0]); str = *((const char *const *)arg[0]);
if (str == NULL) if (str == NULL)
return (__printf_out(io, pi, "\"(null)\"", 8)); return (__printf_out(io, pi, "\"(null)\"", 8));
i = 0;
if (*str == '\0') if (*str == '\0')
i++; return (__printf_out(io, pi, "\"\"", 2));
else if (*str == '#')
i++; for (i = 0, p = str; *p; p++)
else { if (isspace(*p) || *p == '\\' || *p == '"')
for (p = str; *p; p++) i++;
if (isspace(*p) || *p == '\\' || *p == '"')
i++;
}
if (!i) if (!i)
return (__printf_out(io, pi, str, strlen(str))); return (__printf_out(io, pi, str, strlen(str)));
q = malloc(strlen(str) * 5);
assert(q != NULL);
r = q;
ret = __printf_out(io, pi, "\"", 1); ret = __printf_out(io, pi, "\"", 1);
t = str; for (t = p = str; *p; p++) {
for (p = str; *p; p++) {
o = NULL; o = NULL;
if (*p == '\\') if (*p == '\\')
o = "\\\\"; o = "\\\\";
@ -91,14 +83,12 @@ __printf_render_quote(struct __printf_io *io, const struct printf_info *pi __unu
else if (isspace(*p)) { else if (isspace(*p)) {
sprintf(r, "\\%03o", *p); sprintf(r, "\\%03o", *p);
o = r; o = r;
r += strlen(r) + 1;
} else } else
continue; continue;
if (p != t) { if (p != t)
ret += __printf_out(io, pi, t, p - t); ret += __printf_out(io, pi, t, p - t);
t = p + 1;
}
ret += __printf_out(io, pi, o, strlen(o)); ret += __printf_out(io, pi, o, strlen(o));
t = p + 1;
} }
if (p != t) if (p != t)
ret += __printf_out(io, pi, t, p - t); ret += __printf_out(io, pi, t, p - t);