summaryrefslogtreecommitdiffstats
path: root/include/c/str/cpy/stp/stpe/stpeprintf.h
blob: 1a74dd8b0711051cea7861e539beea2fd2cef3bb (plain) (blame)
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
// Copyright 2022 Alejandro Colomar <alx@kernel.org>
// SPDX-License-Identifier:  LGPL-3.0-or-later WITH LGPL-3.0-linking-exception


#ifndef INCLUDE_C_STR_CPY_STP_STPE_STPEPRINTF_H_
#define INCLUDE_C_STR_CPY_STP_STPE_STPEPRINTF_H_


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

#include <c/str/cpy/stp/_compiler.h>


#pragma clang assume_nonnull begin
inline char *c_nullable c_stpeprintf(char *c_nullable dst, char *end,
    const char *restrict fmt, ...);
inline char *c_nullable c_vstpeprintf(char *c_nullable dst, char *end,
    const char *restrict fmt, va_list ap);


inline char *c_nullable
c_stpeprintf(char *c_nullable dst, char *end, const char *restrict fmt, ...)
{
	char     *c_nullable p;
	va_list  ap;

	va_start(ap, fmt);
	p = c_vstpeprintf(dst, end, fmt, ap);
	va_end(ap);

	return p;
}


inline char *c_nullable
c_vstpeprintf(char *c_nullable dst, char *end, const char *restrict fmt,
    va_list ap)
{
	int  len;

	if (dst == end)
		return end;
	if (c_unlikely(dst == NULL))
		return NULL;
	c_impossible(dst > end);

	len = vsnprintf(dst, end - dst, fmt, ap);

	c_impossible(len < -1);
	if (c_unlikely(len == -1))
		return NULL;
	if (len >= end - dst)
		return end;

	return dst + len;
}
#pragma clang assume_nonnull end


#endif  // Header guard