[hackers] [scc] Avoid call to strlen in expand() || Roberto E. Vargas Caballero

From: <git_AT_suckless.org>
Date: Sat, 18 Jul 2015 10:27:46 +0200 (CEST)

commit 606c7f4022fb99a23c906e1d2b23b68f620ca3dd
Author: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
AuthorDate: Sat Jul 18 09:18:19 2015 +0200
Commit: Roberto E. Vargas Caballero <k0ga_AT_shike2.com>
CommitDate: Sat Jul 18 09:18:19 2015 +0200

    Avoid call to strlen in expand()
    
    We know the size of the expanded string in all the cases,
    so it is better to avoid the cll to strlen. We also know that
    BUFSIZ is at least 509 bytes, so the calls to snprintf can be
    substituted by sprintf

diff --git a/cc1/cpp.c b/cc1/cpp.c
index 094bd65..cabb1d9 100644
--- a/cc1/cpp.c
+++ b/cc1/cpp.c
_AT_@ -139,10 +139,10 @@ parsepars(char *buffer, char **listp, int nargs)
         return 1;
 }
 
-static void
-copymacro(char *bp, char *s, size_t bufsiz, char *arglist[])
+static size_t
+copymacro(char *buffer, char *s, size_t bufsiz, char *arglist[])
 {
- char prevc, c, *arg;
+ char prevc, c, *arg, *bp = buffer;
 
         for (prevc = '\0'; c = *s; prevc = c, ++s) {
                 if (c != '_AT_') {
_AT_@ -172,7 +172,7 @@ copymacro(char *bp, char *s, size_t bufsiz, char *arglist[])
         }
         *bp = '\0';
 
- return;
+ return bp - buffer;
 
 expansion_too_long:
         error("expansion of macro \"%s\" is too long", macroname);
_AT_@ -183,22 +183,17 @@ bool
 expand(char *begin, Symbol *sym)
 {
         size_t total, elen, rlen, llen, ilen;
- int n, r;
+ int n;
         char *s = sym->u.s;
         char *arglist[NR_MACROARG], arguments[INPUTSIZ], buffer[BUFSIZE];
 
         if (sym == symfile) {
- sprintf(buffer, "\"%s\"", input->fname);
- goto print_subs;
+ elen = sprintf(buffer, "\"%s\"", input->fname);
+ goto substitute;
         }
         if (sym == symline) {
- r = snprintf(buffer, sizeof(buffer), "%d", input->nline);
- if(r == -1 || (size_t)r >= sizeof(buffer)) {
- error("expansion of macro \"%s\" is too long", sym->name);
- return 0;
- }
- fprintf(stderr, "Expansion of line '%s'\n", buffer);
- goto print_subs;
+ elen = sprintf(buffer, "%d", input->nline);
+ goto substitute;
         }
 
         macroname = sym->name;
_AT_@ -207,11 +202,10 @@ expand(char *begin, Symbol *sym)
         for (n = 0; n < atoi(s); ++n)
                 fprintf(stderr, "PAR%d:%s\n", n, arglist[n]);
 
- copymacro(buffer, s+3, INPUTSIZ-1, arglist);
+ elen = copymacro(buffer, s+3, INPUTSIZ-1, arglist);
 
-print_subs:
+substitute:
         fprintf(stderr, "macro '%s' expanded to :'%s'\n", macroname, buffer);
- elen = strlen(buffer); /* expansion lentgh */
         rlen = strlen(input->p); /* rigth length */
         llen = begin - input->line; /* left length */
         ilen = input->p - begin; /* invocation length */
Received on Sat Jul 18 2015 - 10:27:46 CEST

This archive was generated by hypermail 2.3.0 : Sat Jul 18 2015 - 10:36:12 CEST