summaryrefslogtreecommitdiffstats
path: root/lib/string/sprintf.h
blob: 748536943234da91afaa172576cf890ed12f2d48 (plain)
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
/*
 * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
 * SPDX-License-Identifier: BSD-3-Clause
 */


#ifndef SHADOW_INCLUDE_LIB_SPRINTF_H_
#define SHADOW_INCLUDE_LIB_SPRINTF_H_


#include <config.h>

#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>

#include "attr.h"
#include "defines.h"
#include "sizeof.h"


#define SNPRINTF(s, fmt, ...)                                                 \
	snprintf_(s, NITEMS(s), fmt __VA_OPT__(,) __VA_ARGS__)


format_attr(printf, 2, 3)
inline int xasprintf(char **restrict s, const char *restrict fmt, ...);
format_attr(printf, 2, 0)
inline int xvasprintf(char **restrict s, const char *restrict fmt, va_list ap);

format_attr(printf, 3, 4)
inline int snprintf_(char *restrict s, size_t size, const char *restrict fmt,
    ...);
format_attr(printf, 3, 0)
inline int vsnprintf_(char *restrict s, size_t size, const char *restrict fmt,
    va_list ap);


inline int
xasprintf(char **restrict s, const char *restrict fmt, ...)
{
	int      len;
	va_list  ap;

	va_start(ap, fmt);
	len = xvasprintf(s, fmt, ap);
	va_end(ap);

	return len;
}


inline int
xvasprintf(char **restrict s, const char *restrict fmt, va_list ap)
{
	int  len;

	len = vasprintf(s, fmt, ap);
	if (len == -1) {
		perror("asprintf");
		exit(EXIT_FAILURE);
	}

	return len;
}


inline int
snprintf_(char *restrict s, size_t size, const char *restrict fmt, ...)
{
	int      len;
	va_list  ap;

	va_start(ap, fmt);
	len = vsnprintf_(s, size, fmt, ap);
	va_end(ap);

	return len;
}


inline int
vsnprintf_(char *restrict s, size_t size, const char *restrict fmt, va_list ap)
{
	int  len;

	len = vsnprintf(s, size, fmt, ap);
	if (len == -1)
		return -1;
	if ((size_t) len >= size)
		return -1;

	return len;
}


#endif  // include guard