Branch data Line data Source code
1 : : /* sprintf.c */
2 : :
3 : : /*
4 : : * Copyright (c) 1997-2010, 2013-2014 Wind River Systems, Inc.
5 : : *
6 : : * SPDX-License-Identifier: Apache-2.0
7 : : */
8 : :
9 : : #include <stdarg.h>
10 : : #include <stdio.h>
11 : : #include <sys/cbprintf.h>
12 : :
13 : : struct emitter {
14 : : char *ptr;
15 : : int len;
16 : : };
17 : :
18 : 0 : static int sprintf_out(int c, struct emitter *p)
19 : : {
20 [ # # ]: 0 : if (p->len > 1) { /* need to reserve a byte for EOS */
21 : 0 : *(p->ptr) = c;
22 : 0 : p->ptr += 1;
23 : 0 : p->len -= 1;
24 : : }
25 : 0 : return 0; /* indicate keep going so we get the total count */
26 : : }
27 : :
28 : : int snprintf(char *ZRESTRICT str, size_t len,
29 : : const char *ZRESTRICT format, ...)
30 : : {
31 : : va_list vargs;
32 : :
33 : : struct emitter p;
34 : : int r;
35 : : char dummy;
36 : :
37 [ # # ]: 0 : if (len == 0) {
38 : 0 : str = &dummy; /* write final NUL to dummy, can't change *s */
39 : : }
40 : :
41 : 0 : p.ptr = str;
42 : 0 : p.len = (int) len;
43 : :
44 : 0 : va_start(vargs, format);
45 : 0 : r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
46 : 0 : va_end(vargs);
47 : :
48 : 0 : *(p.ptr) = 0;
49 : 0 : return r;
50 : : }
51 : :
52 : : int sprintf(char *ZRESTRICT str, const char *ZRESTRICT format, ...)
53 : : {
54 : : va_list vargs;
55 : :
56 : : struct emitter p;
57 : : int r;
58 : :
59 : 0 : p.ptr = str;
60 : 0 : p.len = (int) 0x7fffffff; /* allow up to "maxint" characters */
61 : :
62 : 0 : va_start(vargs, format);
63 : 0 : r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
64 : 0 : va_end(vargs);
65 : :
66 : 0 : *(p.ptr) = 0;
67 : 0 : return r;
68 : : }
69 : :
70 : : int vsnprintf(char *ZRESTRICT str, size_t len,
71 : : const char *ZRESTRICT format, va_list vargs)
72 : : {
73 : : struct emitter p;
74 : : int r;
75 : : char dummy;
76 : :
77 [ # # ]: 0 : if (len == 0) {
78 : 0 : str = &dummy; /* write final NUL to dummy, can't change * *s */
79 : : }
80 : :
81 : 0 : p.ptr = str;
82 : 0 : p.len = (int) len;
83 : :
84 : 0 : r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
85 : :
86 : 0 : *(p.ptr) = 0;
87 : 0 : return r;
88 : : }
89 : :
90 : : int vsprintf(char *ZRESTRICT str, const char *ZRESTRICT format,
91 : : va_list vargs)
92 : : {
93 : : struct emitter p;
94 : : int r;
95 : :
96 : 0 : p.ptr = str;
97 : 0 : p.len = (int) 0x7fffffff; /* allow up to "maxint" characters */
98 : :
99 : 0 : r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
100 : :
101 : 0 : *(p.ptr) = 0;
102 : 0 : return r;
103 : : }
|