-/*
- * copy a number to the destination subject to a maximum width
- */
-static void
-cpnumber(char **dest, int num, unsigned int wid, char fill, size_t n) {
- int i, c;
- char *sp;
- char *cp = *dest;
- char *ep = cp + n;
-
- if (cp + wid < ep) {
- if ((i = (num)) < 0)
- i = -(num);
- if ((c = (wid)) < 0)
- c = -c;
- sp = cp + c;
- do {
- *--sp = (i % 10) + '0';
- i /= 10;
- } while (i > 0 && sp > cp);
- if (i > 0)
- *sp = '?';
- else if ((num) < 0 && sp > cp)
- *--sp = '-';
- while (sp > cp)
- *--sp = fill;
- cp += c;
+/* cpnumber formats num as a signed decimal,
+ * appending it to dest if the result doesn't exceed max.
+ * The absolute value of width is the minimum width to produce.
+ * A smaller string is padded;
+ * on the left if width is positive, else the right.
+ * Left-padding uses fill. It is either ' ' or '0'.
+ * Right-padding is always with space. */
+void
+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 `?'. */
+ }
+
+ char *s = m_str(num);
+ size_t len = strlen(s);
+ if (len == w) {
+ charstring_append_cstring(dest, s);
+ return;
+ }
+
+ bool neg = *s == '-';
+ if (len < w) {
+ if (padright) {
+ charstring_append_cstring(dest, s);
+ while (len++ < w) {
+ charstring_push_back(dest, ' ');
+ }
+ return;
+ }
+
+ if (neg && fill == '0') {
+ charstring_push_back(dest, *s++);
+ }
+ while (len++ < w) {
+ charstring_push_back(dest, fill);
+ }
+ charstring_append_cstring(dest, s);
+ return;