File: buffer_printf.c

package info (click to toggle)
wget2 2.2.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,468 kB
  • sloc: ansic: 121,166; sh: 11,559; makefile: 878; xml: 182; sed: 16
file content (576 lines) | stat: -rw-r--r-- 14,341 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
 * Copyright (c) 2012 Tim Ruehsen
 * Copyright (c) 2015-2024 Free Software Foundation, Inc.
 *
 * This file is part of libwget.
 *
 * Libwget is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Libwget is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with libwget.  If not, see <https://www.gnu.org/licenses/>.
 *
 *
 * Memory buffer printf routines
 *
 * Changelog
 * 24.09.2012  Tim Ruehsen  created
 *
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <c-ctype.h>

#include <wget.h>
#include "private.h"

/**
 * \file
 * \brief Buffer management functions
 * \defgroup libwget-buffer Buffer management functions
 * @{
 */

/* \cond _hide_internal_symbols */
#define FLAG_ZERO_PADDED   1U
#define FLAG_LEFT_ADJUST   2U
#define FLAG_ALTERNATE     4U
#define FLAG_SIGNED        8U
#define FLAG_DECIMAL      16U
#define FLAG_OCTAL        32U
#define FLAG_HEXLO        64U
#define FLAG_HEXUP       128U
/* \endcond */

static void copy_string(wget_buffer *buf, unsigned int flags, int field_width, int precision, const char *arg)
{
	size_t length;

	if (!arg) {
		wget_buffer_strcat(buf, "(null)");
		return;
	}

	if (precision >= 0) {
		length = strnlen(arg, precision);
	} else {
		length = strlen(arg);
	}

	// debug_printf("flags=0x%02x field_width=%d precision=%d length=%zu arg='%s'\n",
	//	flags,field_width,precision,length,arg);

	if (field_width) {
		if ((unsigned)field_width > length) {
			if (flags & FLAG_LEFT_ADJUST) {
				wget_buffer_memcat(buf, arg, length);
				wget_buffer_memset_append(buf, ' ', field_width - length);
			} else {
				wget_buffer_memset_append(buf, ' ', field_width - length);
				wget_buffer_memcat(buf, arg, length);
			}
		} else {
			wget_buffer_memcat(buf, arg, length);
		}
	} else {
		wget_buffer_memcat(buf, arg, length);
	}
}

static void convert_dec_fast(wget_buffer *buf, int arg)
{
	char str[32]; // long enough to hold decimal long long
	char *dst = str + sizeof(str) - 1;
	int minus;

	if (arg < 0) {
		minus = 1;
		arg = -arg;
	} else
		minus = 0;

	while (arg >= 10) {
		*dst-- = (arg % 10) + '0';
		arg /= 10;
	}
	*dst-- = (arg % 10) + '0';

	if (minus)
		*dst-- = '-';

	wget_buffer_memcat(buf, dst + 1, sizeof(str) - (dst - str) - 1);
}

static void convert_dec(wget_buffer *buf, unsigned int flags, int field_width, int precision, long long arg)
{
	unsigned long long argu = (unsigned long long) arg;
	char str[32], minus = 0; // long enough to hold decimal long long
	char *dst = str + sizeof(str) - 1;
	unsigned char c;
	size_t length;

	// info_printf("arg1 = %lld %lld\n",arg,-arg);

	if (flags & FLAG_DECIMAL) {
		if (flags & FLAG_SIGNED && arg < 0) {
			minus = 1;
			argu = -arg;
		}

		while (argu) {
			*dst-- = argu % 10 + '0';
			argu /= 10;
		}
	} else if (flags & FLAG_HEXLO) {
		while (argu) {
			// slightly faster than having a HEX[] lookup table
			*dst-- = (c = (argu & 0xf)) >= 10 ? c + 'a' - 10 : c + '0';
			argu >>= 4;
		}
	} else if (flags & FLAG_HEXUP) {
		while (argu) {
			// slightly faster than having a HEX[] lookup table
			*dst-- = (c = (argu & 0xf)) >= 10 ? c + 'A' - 10 : c + '0';
			argu >>= 4;
		}
	} else if (flags & FLAG_OCTAL) {
		while (argu) {
			*dst-- = (argu & 0x07) + '0';
			argu >>= 3;
		}
	}

	// info_printf("arg2 = %lld\n",arg);


	dst++;

	length =  sizeof(str) - (dst - str);

	if (precision < 0) {
		precision = 1;
	} else {
		flags &= ~FLAG_ZERO_PADDED;
	}

	// info_printf("flags=0x%02x field_width=%d precision=%d length=%zd dst='%.*s'\n",
	//	flags,field_width,precision,length,length,dst);

	if (field_width) {
		if ((unsigned)field_width > length + minus) {
			if (flags & FLAG_LEFT_ADJUST) {
				if (minus)
					wget_buffer_memset_append(buf, '-', 1);

				if (length < (unsigned)precision) {
					wget_buffer_memset_append(buf, '0', precision - length);
					wget_buffer_memcat(buf, dst, length);
					if (field_width > precision + minus)
						wget_buffer_memset_append(buf, ' ', field_width - precision - minus);
				} else {
						wget_buffer_memcat(buf, dst, length);
						wget_buffer_memset_append(buf, ' ', field_width - length - minus);
				}
			} else {
				if (length < (unsigned)precision) {
					if (field_width > precision + minus) {
						if (flags & FLAG_ZERO_PADDED) {
							if (minus)
								wget_buffer_memset_append(buf, '-', 1);
							wget_buffer_memset_append(buf, '0', field_width - precision - minus);
						} else {
							wget_buffer_memset_append(buf, ' ', field_width - precision - minus);
							if (minus)
								wget_buffer_memset_append(buf, '-', 1);
						}
					} else {
						if (minus)
							wget_buffer_memset_append(buf, '-', 1);
					}
					wget_buffer_memset_append(buf, '0', precision - length);
				} else {
					if (flags & FLAG_ZERO_PADDED) {
						if (minus)
							wget_buffer_memset_append(buf, '-', 1);
						wget_buffer_memset_append(buf, '0', field_width - length - minus);
					} else {
						wget_buffer_memset_append(buf, ' ', field_width - length - minus);
						if (minus)
							wget_buffer_memset_append(buf, '-', 1);
					}
				}
				wget_buffer_memcat(buf, dst, length);
			}
		} else {
			if (minus)
				wget_buffer_memset_append(buf, '-', 1);
			if (length < (unsigned)precision)
				wget_buffer_memset_append(buf, '0', precision - length);
			wget_buffer_memcat(buf, dst, length);
		}
	} else {
		if (minus)
			wget_buffer_memset_append(buf, '-', 1);

		if (length < (unsigned)precision)
			wget_buffer_memset_append(buf, '0', precision - length);

		wget_buffer_memcat(buf, dst, length);
	}
}

static void convert_pointer(wget_buffer *buf, void *pointer)
{
	static const char HEX[16] = "0123456789abcdef";
	char str[32]; // long enough to hold hexadecimal pointer
	char *dst;
	int length;
	size_t arg;

	if (!pointer) {
		wget_buffer_memcat(buf, "0x0", 3);
		return;
	} else {
		wget_buffer_memcat(buf, "0x", 2);
	}

	// convert to a size_t (covers full address room) tp allow integer arithmetic
	arg = (size_t)pointer;

	length = 0;
	dst = str + sizeof(str);
	*--dst = 0;
	do {
		*--dst = HEX[arg&0xF];
		arg >>= 4;
		length++;
	} while (arg);

	wget_buffer_memcat(buf, dst, length);
}

static const char *read_precision(const char *p, int *out, bool precision_is_external)
{
	int precision;

	if (precision_is_external) {
		precision = *out;
		if (precision < 0 )
			precision = 0;
		p++;
	} else if (c_isdigit(*p)) {
		precision = 0;
		do {
			precision = precision * 10 + (*p - '0');
		} while (c_isdigit(*++p));
	} else {
		precision = -1;
	}

	*out = precision;
	return p;
}

static const char *read_flag_chars(const char *p, unsigned int *out)
{
	unsigned int flags;

	for (flags = 0; *p; p++) {
		if (*p == '0')
			flags |= FLAG_ZERO_PADDED;
		else if (*p == '-')
			flags |= FLAG_LEFT_ADJUST;
		else if (*p == '#')
			flags |= FLAG_ALTERNATE;
		else
			break;
	}

	*out = flags;
	return p;
}

static const char *read_field_width(const char *p, int *out, unsigned int *flags, bool width_is_external)
{
	int field_width;

	if (width_is_external) {
		field_width = *out;

		if (field_width < 0) {
			*flags |= FLAG_LEFT_ADJUST;
			field_width = -field_width;
		}

		p++;
	} else {
		for (field_width = 0; c_isdigit(*p); p++)
			field_width = field_width * 10 + (*p - '0');
	}

	*out = field_width;
	return p;
}

/**
 * \param[in] buf A buffer, created with wget_buffer_init() or wget_buffer_alloc()
 * \param[in] fmt A `printf(3)`-like format string
 * \param[in] args A `va_list` with the format string placeholders' values
 * \return Length of the buffer after appending the formatted string
 *
 * Formats the string \p fmt (with `printf(3)`-like args) and appends the result to the end
 * of the buffer \p buf (using wget_buffer_memcat()).
 *
 * For more information, see `vprintf(3)`.
 */
size_t wget_buffer_vprintf_append(wget_buffer *buf, const char *fmt, va_list args)
{
	const char *p = fmt, *begin;
	int field_width, precision;
	unsigned int flags;
	long long arg;
	unsigned long long argu;

	if (!p)
		return 0;

	for (;*p;) {

		/*
		 * Collect plain char sequence.
		 * Walk the string until we find a '%' character.
		 */
		for (begin = p; *p && *p != '%'; p++);
		if (p != begin)
			wget_buffer_memcat(buf, begin, p - begin);

		if (!*p)
			break;

		/* Shortcut to %s and %p, handle %% */
		if (*++p == 's') {
			const char *s = va_arg(args, const char *);
			wget_buffer_strcat(buf, s ? s : "(null)");
			p++;
			continue;
		} else if (*p == 'd') {
			convert_dec_fast(buf, va_arg(args, int));
			p++;
			continue;
		} else if (*p == 'c') {
			char c = (char ) va_arg(args, int);
			wget_buffer_memcat(buf, &c, 1);
			p++;
			continue;
		} else if (*p == 'p') {
			convert_pointer(buf, va_arg(args, void *));
			p++;
			continue;
		} else if (*p == '%') {
			wget_buffer_memset_append(buf, '%', 1);
			p++;
			continue;
		}

		/* Read the flag chars (optional, simplified) */
		p = read_flag_chars(p, &flags);

		/*
		 * Read field width (optional).
		 * If '*', then the field width is given as an additional argument,
		 * which precedes the argument to be formatted.
		 */
		if (*p == '*') {
			field_width = va_arg(args, int);
			p = read_field_width(p, &field_width, &flags, 1);
		} else {
			p = read_field_width(p, &field_width, &flags, 0);
		}

		/*
		 * Read precision (optional).
		 * If '*', the precision is given as an additional argument,
		 * just as the case for the field width.
		 */
		if (*p == '.') {
			if (*++p == '*') {
				precision = va_arg(args, int);
				p = read_precision(p, &precision, 1);
			} else {
				p = read_precision(p, &precision, 0);
			}
		} else
			precision = -1;

		/* Read length modifier (optional) */
		switch (*p) {
		case 'z':
			arg = va_arg(args, ssize_t);
			argu = (size_t)arg;
			p++;
			break;

		case 'l':
			if (p[1] == 'l') {
				p += 2;
				arg = va_arg(args, long long);
				argu = (unsigned long long)arg;
			} else {
				p++;
				arg = (long)va_arg(args, long);
				argu = (unsigned long)arg;
			}
			break;

		case 'L':
			p++;
			arg = va_arg(args, long long);
			argu = (unsigned long long)arg;
			break;

		case 'h':
			if (p[1] == 'h') {
				p += 2;
				arg = (signed char) va_arg(args, int);
				argu = (unsigned char) arg;
			} else {
				p++;
				arg = (short) va_arg(args, int);
				argu = (unsigned short) arg;
			}
			break;

		case 's':
			p++;
			copy_string(buf, flags, field_width, precision, va_arg(args, const char *));
			continue;

		case 'c':
		{
			char c[2] = { (char) va_arg(args, int), 0 };
			p++;
			copy_string(buf, flags, field_width, precision, c);
			continue;
		}

		case 'p': // %p shortcut
			p++;
			convert_dec(buf, flags | FLAG_HEXLO | FLAG_ALTERNATE, field_width, precision, (long long)(ptrdiff_t)va_arg(args, void *));
			continue;

		default:
			arg = va_arg(args, int);
			argu = (unsigned int)arg;
		}

		if (*p == 'd' || *p == 'i') {
			convert_dec(buf, flags | FLAG_SIGNED | FLAG_DECIMAL, field_width, precision, arg);
		} else if (*p == 'u') {
			convert_dec(buf, flags | FLAG_DECIMAL, field_width, precision, (long long) argu);
		} else if (*p == 'x') {
			convert_dec(buf, flags | FLAG_HEXLO, field_width, precision, (long long) argu);
		} else if (*p == 'X') {
			convert_dec(buf, flags | FLAG_HEXUP, field_width, precision, (long long) argu);
		} else if (*p == 'o') {
			convert_dec(buf, flags | FLAG_OCTAL, field_width, precision, (long long) argu);
		} else {
			/*
			 * This is an unknown conversion specifier,
			 * so just put '%' and move on.
			 */
			wget_buffer_memset_append(buf, '%', 1);
			p = begin + 1;
			continue;
		}

		p++;
	}

	return buf->length;
}

/**
 * \param[in] buf A buffer, created with wget_buffer_init() or wget_buffer_alloc()
 * \param[in] fmt A `printf(3)`-like format string
 * \param[in] args A `va_list` with the format string placeholders' values
 * \return Length of the buffer after appending the formatted string
 *
 * Formats the string \p fmt (with `printf(3)`-like args) and overwrites the contents
 * of the buffer \p buf with that formatted string.
 *
 * This is equivalent to the following code:
 *
 *     buf->length = 0;
 *     wget_buffer_vprintf_append(buf, fmt, args);
 *
 * For more information, see `vprintf(3)`.
 */
size_t wget_buffer_vprintf(wget_buffer *buf, const char *fmt, va_list args)
{
	buf->length = 0;

	return wget_buffer_vprintf_append(buf, fmt, args);
}

/**
 * \param[in] buf A buffer, created with wget_buffer_init() or wget_buffer_alloc()
 * \param[in] fmt A `printf(3)`-like format string
 * \param[in] ... Variable arguments
 * \return Length of the buffer after appending the formatted string
 *
 * Formats the string \p fmt (with `printf(3)`-like args) and appends the result to the end
 * of the buffer \p buf (using wget_buffer_memcat()).
 *
 * This function is equivalent to wget_buffer_vprintf_append(), except in that it uses
 * a variable number of arguments rather than a `va_list`.
 *
 * For more information, see `printf(3)`.
 */
size_t wget_buffer_printf_append(wget_buffer *buf, const char *fmt, ...)
{
	va_list args;

	va_start(args, fmt);
	wget_buffer_vprintf_append(buf, fmt, args);
	va_end(args);

	return buf->length;
}

/**
 * \param[in] buf A buffer, created with wget_buffer_init() or wget_buffer_alloc()
 * \param[in] fmt A `printf(3)`-like format string
 * \param[in] ... Variable arguments
 * \return Length of the buffer after appending the formatted string
 *
 * Formats the string \p fmt (with `printf(3)`-like args) and overwrites the contents
 * of the buffer \p buf with that formatted string.
 *
 * This function is equivalent to wget_buffer_vprintf(), except in that it uses
 * a variable number of arguments rather than a `va_list`.
 *
 * For more information, see `printf(3)`.
 */
size_t wget_buffer_printf(wget_buffer *buf, const char *fmt, ...)
{
	va_list args;

	va_start(args, fmt);
	size_t len = wget_buffer_vprintf(buf, fmt, args);
	va_end(args);

	return len;
}
/** @} */