Lightweight vsnprintf replacement. Supports: s, d, u, x, X, p, c, %%. Supports padding with '0' and width specifier.
74 {
75 char *start = buf;
76 size_t initial_size = size;
77
78 if (size == 0) return 0;
79
80 while (*fmt && size > 1) {
81 if (*fmt == '%') {
82 fmt++;
83 bool left_align = false;
84 if (*fmt == '-') {
85 left_align = true;
86 fmt++;
87 }
88 char pad = ' ';
89 int width = 0;
90 if (*fmt == '0') {
91 pad = '0';
92 fmt++;
93 }
94 while (isdigit((int)*fmt)) {
95 width = width * 10 + (*fmt - '0');
96 fmt++;
97 }
98
99
100 while (*fmt == 'l') fmt++;
101
102 switch (*fmt) {
103 case 's':
104 out_str(&buf, &size, va_arg(args,
const char *), width, left_align);
105 break;
106 case 'd':
107 case 'i':
108 out_int(&buf, &size, va_arg(args, int32_t), 10, width, pad);
109 break;
110 case 'u':
111 out_uint(&buf, &size, va_arg(args, uint32_t), 10, width, pad,
false);
112 break;
113 case 'x':
114 out_uint(&buf, &size, va_arg(args, uint32_t), 16, width, pad,
false);
115 break;
116 case 'X':
117 out_uint(&buf, &size, va_arg(args, uint32_t), 16, width, pad,
true);
118 break;
119 case 'p':
120 out_str(&buf, &size,
"0x", 0,
false);
121 out_uint(&buf, &size, (uint32_t)(uintptr_t)va_arg(args,
void *), 16, 8,
'0',
false);
122 break;
123 case 'c':
124 out_char(&buf, &size, (
char)va_arg(args,
int));
125 break;
126 case '%':
128 break;
129 default:
132 break;
133 }
134 } else {
136 }
137 fmt++;
138 }
139
140 if (size > 0) {
141 *buf = '\0';
142 } else if (initial_size > 0) {
143 start[initial_size - 1] = '\0';
144 }
145
146 return (int)(buf - start);
147}
static void out_char(char **buf, size_t *size, char c)
Definition meshx_tiny_printf.c:15
static void out_uint(char **buf, size_t *size, uint32_t val, int base, int width, char pad, bool upper)
Definition meshx_tiny_printf.c:41
static void out_int(char **buf, size_t *size, int32_t val, int base, int width, char pad)
Definition meshx_tiny_printf.c:65
static void out_str(char **buf, size_t *size, const char *s, int width, bool left_align)
Definition meshx_tiny_printf.c:23