[PATCH] itoa

Freddie Chopin freddie_chopin@op.pl
Mon Dec 8 14:28:00 GMT 2014


On 12/08/2014 01:00 PM, Corinna Vinschen wrote:
> Hmm. The code of both functions is rather shirt. How much would you 
> actually save, code-wise?

Well, if you can easily save something, why not do it? (; This is not a 
hack, it works no matter what your platform is or what ABI is used - 
everything that itoa() does that is _NOT_ done by utoa() is adding a '-' 
at the beginning and negating the value - if it is negative. Except for 
that operations - which are easily factored out - the behavior (and 
implementation) is identical.

On my ARM Cortex-M3 these functions (with -O2 optimization) are 132 
bytes (itoa()) and 104 bytes (utoa()). The string with the characters 
"01234..." for the functions uses additional 37 bytes, and linker 
noticed that it is the same for both functions, but in the case of 
library it may not work that well.

With my trivial modification to itoa() - making it a wrapper for utoa() 
the size of itoa() decreased to 24 bytes. I agree that ~100 bytes of 
savings is not much, but it is something. Plus - you get to maintain 
only one real function and one brain-dead wrapper, instead of two real 
functions.

Here's my itoa():

char *
_DEFUN (itoa, (value, str, base),
         int value _AND
         char *str _AND
         int base)
{
   unsigned uvalue;

   /* Negative numbers are only supported for decimal.
    * Cast to unsigned to avoid overflow for maximum negative value. */
   if ((base == 10) && (value < 0))
     {
       *str++ = '-';
       uvalue = (unsigned)-value;
     }
   else
     uvalue = (unsigned)value;

   return utoa(uvalue, str, base);
}

Anyway - you can actually commit the stuff as it is, I can provide a 
patch which turns itoa() into a wrapper for utoa() and you'll judge 
whether or not to commit that as well.

I think it's worth to make such improvement - its costs are pretty small 
- exactly one additional function call (possibly changed to branch, as 
the call is the last thing in the function - it was assembled like that 
in my case, but I'm not sure it would work the same for a library), 
while the benefits are present too, small but noticeable - both for the 
user and for the maintainers of the library.

Regards,
FCh



More information about the Newlib mailing list