1 /* @(#)snprintf.c	1.16 19/10/19 Copyright 1985, 1996-2019 J. Schilling */
2 /*
3  *	Copyright (c) 1985, 1996-2019 J. Schilling
4  */
5 /*
6  * The contents of this file are subject to the terms of the
7  * Common Development and Distribution License, Version 1.0 only
8  * (the "License").  You may not use this file except in compliance
9  * with the License.
10  *
11  * See the file CDDL.Schily.txt in this distribution for details.
12  * A copy of the CDDL is also available via the Internet at
13  * http://www.opensource.org/licenses/cddl1.txt
14  *
15  * When distributing Covered Code, include this CDDL HEADER in each
16  * file and include the License file CDDL.Schily.txt from this distribution.
17  */
18 
19 #define	snprintf __nothing__	/* prototype may be wrong (e.g. IRIX) */
20 #include <schily/mconfig.h>
21 #include <schily/unistd.h>	/* include <sys/types.h> try to get size_t */
22 #include <schily/stdio.h>	/* Try again for size_t	*/
23 #include <schily/stdlib.h>	/* Try again for size_t	*/
24 #include <schily/varargs.h>
25 #include <schily/standard.h>
26 #include <schily/schily.h>
27 #undef	snprintf
28 
29 /*
30  * If PORT_ONLY is defined, snprintf() will only be compiled in if it is
31  * missing on the local platform. This is used by e.g. libschily.
32  */
33 #if	!defined(HAVE_SNPRINTF) || !defined(PORT_ONLY)
34 
35 EXPORT	int snprintf __PR((char *, size_t maxcnt, const char *, ...));
36 
37 typedef struct {
38 	char	*ptr;
39 	int	count;
40 } *BUF, _BUF;
41 
42 #ifdef	PROTOTYPES
43 static void
_cput(char c,void * l)44 _cput(char c, void *l)
45 #else
46 static void
47 _cput(c, l)
48 	char	c;
49 	void	*l;
50 #endif
51 {
52 	register BUF	bp = (BUF)l;
53 
54 	if (--bp->count > 0) {
55 		*bp->ptr++ = c;
56 	} else {
57 		/*
58 		 * Make sure that there will never be a negative overflow.
59 		 */
60 		bp->count++;
61 	}
62 }
63 
64 /* VARARGS2 */
65 #ifdef	PROTOTYPES
66 EXPORT int
snprintf(char * buf,size_t maxcnt,const char * form,...)67 snprintf(char *buf, size_t maxcnt, const char *form, ...)
68 #else
69 EXPORT int
70 snprintf(buf, maxcnt, form, va_alist)
71 	char		*buf;
72 	size_t		maxcnt;
73 	const char	*form;
74 	va_dcl
75 #endif
76 {
77 	va_list	args;
78 	int	cnt;
79 	_BUF	bb;
80 
81 	bb.ptr = buf;
82 	bb.count = maxcnt;
83 
84 #ifdef	PROTOTYPES
85 	va_start(args, form);
86 #else
87 	va_start(args);
88 #endif
89 	cnt = format(_cput, &bb, form,  args);
90 	va_end(args);
91 	if (maxcnt > 0)
92 		*(bb.ptr) = '\0';
93 	if (bb.count < 0)
94 		return (-1);
95 
96 	return (cnt);
97 }
98 
99 #endif	/* !defined(HAVE_SNPRINTF) || !defined(PORT_ONLY) */
100