-cpnumber(charstring_t dest, int num, unsigned int wid, char fill, size_t max) {
- if (wid < (num >= 0 ? max : max-1)) {
- /* Build up the string representation of num in reverse. */
- charstring_t rev = charstring_create (0);
- int i = num >= 0 ? num : -num;
-
- do {
- charstring_push_back (rev, i % 10 + '0');
- i /= 10;
- } while (--wid > 0 && i > 0);
- if (i > 0) {
- /* Overflowed the field (wid). */
- charstring_push_back (rev, '?');
- } else if (num < 0 && wid > 0) {
- /* Shouldn't need the wid > 0 check, that's why the condition
- at the top checks wid < max-1 when num < 0. */
- charstring_push_back (rev, '-');
- --wid;
- }
- while (wid-- > 0 && fill != 0) {
- charstring_push_back (rev, fill);
- }
+cpnumber(charstring_t dest, int num, int width, char fill, size_t max)
+{
+ if (width == 0 || width == INT_MIN) {
+ return;
+ }
+
+ bool padright = width < 0;
+ if (padright) {
+ width = -width; /* Can't overflow after above check. */
+ }
+ size_t w = width;
+ if (w > max) {
+ return; /* The padded result can't fit. */
+ }
+ if (num < 0 && w == 1) {
+ return; /* No room for `-' and a digit or `?'. */
+ }