forked from zephyrproject-rtos/zephyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcbprintf.c
114 lines (89 loc) · 1.83 KB
/
cbprintf.c
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
/*
* Copyright (c) 2020 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdarg.h>
#include <stddef.h>
#include <zephyr/sys/cbprintf.h>
int cbprintf(cbprintf_cb out, void *ctx, const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = cbvprintf(out, ctx, format, ap);
va_end(ap);
return rc;
}
#if defined(CONFIG_CBPRINTF_LIBC_SUBSTS)
#include <stdio.h>
/* Context for sn* variants is the next space in the buffer, and the buffer
* end.
*/
struct str_ctx {
char *dp;
char *const dpe;
};
static int str_out(int c,
void *ctx)
{
struct str_ctx *scp = ctx;
/* s*printf must return the number of characters that would be
* output, even if they don't all fit, so conditionally store
* and unconditionally succeed.
*/
if (scp->dp < scp->dpe) {
*(scp->dp++) = c;
}
return c;
}
int fprintfcb(FILE *stream, const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = vfprintfcb(stream, format, ap);
va_end(ap);
return rc;
}
int vfprintfcb(FILE *stream, const char *format, va_list ap)
{
return cbvprintf(fputc, stream, format, ap);
}
int printfcb(const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = vprintfcb(format, ap);
va_end(ap);
return rc;
}
int vprintfcb(const char *format, va_list ap)
{
return cbvprintf(fputc, stdout, format, ap);
}
int snprintfcb(char *str, size_t size, const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = vsnprintfcb(str, size, format, ap);
va_end(ap);
return rc;
}
int vsnprintfcb(char *str, size_t size, const char *format, va_list ap)
{
struct str_ctx ctx = {
.dp = str,
.dpe = str + size,
};
int rv = cbvprintf(str_out, &ctx, format, ap);
if (ctx.dp < ctx.dpe) {
ctx.dp[0] = 0;
} else {
ctx.dp[-1] = 0;
}
return rv;
}
#endif /* CONFIG_CBPRINTF_LIBC_SUBSTS */