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 <zephyr/sys/cbprintf.h>
12 
13 struct emitter {
14 	char *ptr;
15 	int len;
16 };
17 
sprintf_out(int c,struct emitter * p)18 static int sprintf_out(int c, struct emitter *p)
19 {
20 	if (p->len > 1) { /* need to reserve a byte for EOS */
21 		*(p->ptr) = c;
22 		p->ptr += 1;
23 		p->len -= 1;
24 	}
25 	return 0; /* indicate keep going so we get the total count */
26 }
27 
snprintf(char * ZRESTRICT str,size_t len,const char * ZRESTRICT format,...)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 	if (len == 0) {
38 		str = &dummy; /* write final NUL to dummy, can't change *s */
39 	}
40 
41 	p.ptr = str;
42 	p.len = (int) len;
43 
44 	va_start(vargs, format);
45 	r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
46 	va_end(vargs);
47 
48 	*(p.ptr) = 0;
49 	return r;
50 }
51 
sprintf(char * ZRESTRICT str,const char * ZRESTRICT format,...)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 	p.ptr = str;
60 	p.len = (int) 0x7fffffff; /* allow up to "maxint" characters */
61 
62 	va_start(vargs, format);
63 	r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
64 	va_end(vargs);
65 
66 	*(p.ptr) = 0;
67 	return r;
68 }
69 
vsnprintf(char * ZRESTRICT str,size_t len,const char * ZRESTRICT format,va_list vargs)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 	if (len == 0) {
78 		str = &dummy; /* write final NUL to dummy, can't change * *s */
79 	}
80 
81 	p.ptr = str;
82 	p.len = (int) len;
83 
84 	r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
85 
86 	*(p.ptr) = 0;
87 	return r;
88 }
89 
vsprintf(char * ZRESTRICT str,const char * ZRESTRICT format,va_list vargs)90 int vsprintf(char *ZRESTRICT str, const char *ZRESTRICT format,
91 	     va_list vargs)
92 {
93 	struct emitter p;
94 	int     r;
95 
96 	p.ptr = str;
97 	p.len = (int) 0x7fffffff; /* allow up to "maxint" characters */
98 
99 	r = cbvprintf(sprintf_out, (void *) (&p), format, vargs);
100 
101 	*(p.ptr) = 0;
102 	return r;
103 }
104