Skip to content

Instantly share code, notes, and snippets.

@00-matt
Created August 2, 2021 07:37
Show Gist options
  • Save 00-matt/b6e43f787df9cf6bd9ab333f2066fc26 to your computer and use it in GitHub Desktop.
Save 00-matt/b6e43f787df9cf6bd9ab333f2066fc26 to your computer and use it in GitHub Desktop.
static size_t debug_itoa(int value, char *buf, unsigned int radix, int sign) {
int neg = 0;
char *pbuf = buf;
unsigned int i;
unsigned int len;
if (radix > 16) {
*buf = '\0';
return 0;
}
if (sign && value < 0) {
neg = 1;
value = -value;
}
do {
int digit = value % radix;
*(pbuf++) = (digit < 10 ? '0' + digit : 'A' + digit - 10);
value /= radix;
} while (value > 0);
if (neg) {
*(pbuf++) = '-';
}
*pbuf = '\0';
len = pbuf - buf;
for (i = 0; i < len / 2; i++) {
char tmp = buf[i];
buf[i] = buf[len - i - 1];
buf[len - i - 1] = tmp;
}
return len;
}
static size_t debug_vprintf(const char *fmt, va_list args) {
char buf[12]; // Big enough for "-214783647\0".
size_t n = 0;
while (*fmt){
if (fmt[0] != '%' || fmt[1] == '%') {
if (fmt[0] == '%') fmt++;
size_t i = 0;
while (fmt[i] && fmt[i] != '%') {
putchar(fmt[i]);
i++;
}
fmt += i;
n += i;
continue;
}
const char *start = fmt++;
switch (*fmt) {
case 'c': {
fmt++;
putchar((char)va_arg(args, int));
n++;
break;
}
case 's': {
fmt++;
const char *str = va_arg(args, const char *);
size_t len = strlen(str);
for (size_t i = 0; i < len; i++) putchar(str[i]);
n += len;
break;
}
case 'x': /* fall-thru */
case 'i': /* fall-thru */
case 'u': {
fmt++;
int val = va_arg(args, int);
size_t len = debug_itoa(val,
buf,
*(fmt - 1) == 'x' ? 16 : 10,
*(fmt - 1) == 'i');
for (size_t i = 0; i < len; i++) putchar(buf[i]);
n += len;
break;
}
default: {
fmt = start;
size_t len = strlen(fmt);
for (size_t i = 0; i < len; i++) putchar(fmt[i]);
n += len;
fmt += len;
break;
}
}
}
return n;
}
__attribute__((format(printf, 1, 2)))
static size_t debug_printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
size_t n = debug_vprintf(fmt, args);
va_end(args);
return n;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment