Replace str_fromprint() with strn_fromprint()

This commit is contained in:
Andrew Bettison 2013-09-02 17:31:13 +09:30
parent 8d0e056f81
commit 080ccd957a
3 changed files with 16 additions and 11 deletions

View File

@ -482,7 +482,7 @@ int app_echo(const struct cli_parsed *parsed, struct cli_context *context)
DEBUGF("echo:argv[%d]=\"%s\"", i, arg);
if (escapes) {
unsigned char buf[strlen(arg)];
size_t len = str_fromprint(buf, arg);
size_t len = strn_fromprint(buf, sizeof buf, arg, '\0', NULL);
cli_write(context, buf, len);
} else
cli_puts(context, arg);

23
str.c
View File

@ -343,37 +343,42 @@ size_t toprint_str_len(const char *srcStr, const char quotes[2])
return srcStr ? strbuf_count(strbuf_toprint_quoted(strbuf_local(NULL, 0), quotes, srcStr)) : 4;
}
size_t str_fromprint(unsigned char *dst, const char *src)
size_t strn_fromprint(unsigned char *dst, size_t dstlen, const char *src, char endquote, const char **afterp)
{
unsigned char *const odst = dst;
while (*src) {
unsigned char *const edst = dst + dstlen;
while (*src && *src != endquote && dst < edst) {
switch (*src) {
case '\\':
++src;
unsigned char d;
switch (*src) {
case '\0': *dst++ = '\\'; break;
case '0': *dst++ = '\0'; ++src; break;
case 'n': *dst++ = '\n'; ++src; break;
case 'r': *dst++ = '\r'; ++src; break;
case 't': *dst++ = '\t'; ++src; break;
case '\0': d = '\\'; break;
case '0': d = '\0'; ++src; break;
case 'n': d = '\n'; ++src; break;
case 'r': d = '\r'; ++src; break;
case 't': d = '\t'; ++src; break;
case 'x':
if (isxdigit(src[1]) && isxdigit(src[2])) {
++src;
fromhex(dst++, src, 1);
fromhex(&d, src, 1);
src += 2;
break;
}
// fall through
default:
*dst++ = *src++;
d = *src++;
break;
}
*dst++ = d;
break;
default:
*dst++ = *src++;
break;
}
}
if (afterp)
*afterp = src;
return dst - odst;
}

2
str.h
View File

@ -81,7 +81,7 @@ char *toprint(char *dstStr, ssize_t dstBufSiz, const char *srcBuf, size_t srcByt
char *toprint_str(char *dstStr, ssize_t dstBufSiz, const char *srcStr, const char quotes[2]);
size_t toprint_len(const char *srcBuf, size_t srcBytes, const char quotes[2]);
size_t toprint_str_len(const char *srcStr, const char quotes[2]);
size_t str_fromprint(unsigned char *dst, const char *src);
size_t strn_fromprint(unsigned char *dst, size_t dstlen, const char *src, char endquote, const char **afterp);
#define alloca_toprint(dstlen,buf,len) toprint((char *)alloca((dstlen) == -1 ? toprint_len((const char *)(buf),(len), "``") + 1 : (dstlen)), (dstlen), (const char *)(buf), (len), "``")
#define alloca_str_toprint_quoted(str, quotes) toprint_str((char *)alloca(toprint_str_len((str), (quotes)) + 1), -1, (str), (quotes))