snprintf.c revision 90792
1/*
2 * Copyright (c) 2000-2001 Sendmail, Inc. and its suppliers.
3 *      All rights reserved.
4 * Copyright (c) 1990, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Chris Torek.
9 *
10 * By using this file, you agree to the terms and conditions set
11 * forth in the LICENSE file which can be found at the top level of
12 * the sendmail distribution.
13 */
14
15#include <sm/gen.h>
16SM_RCSID("@(#)$Id: snprintf.c,v 1.23 2001/09/11 04:04:49 gshapiro Exp $")
17#include <limits.h>
18#include <sm/varargs.h>
19#include <sm/io.h>
20#include "local.h"
21
22/*
23**  SM_SNPRINTF -- format a string to a memory location of restricted size
24**
25**	Parameters:
26**		str -- memory location to place formatted string
27**		n -- size of buffer pointed to by str, capped to
28**			a maximum of INT_MAX
29**		fmt -- the formatting directives
30**		... -- the data to satisfy the formatting
31**
32**	Returns:
33**		Failure: -1
34**		Success: number of bytes that would have been written
35**			to str, not including the trailing '\0',
36**			up to a maximum of INT_MAX, as if there was
37**			no buffer size limitation.  If the result >= n
38**			then the output was truncated.
39**
40**	Side Effects:
41**		If n > 0, then between 0 and n-1 bytes of formatted output
42**		are written into 'str', followed by a '\0'.
43*/
44
45int
46#if SM_VA_STD
47sm_snprintf(char *str, size_t n, char const *fmt, ...)
48#else /* SM_VA_STD */
49sm_snprintf(str, n, fmt, va_alist)
50	char *str;
51	size_t n;
52	char *fmt;
53	va_dcl
54#endif /* SM_VA_STD */
55{
56	int ret;
57	SM_VA_LOCAL_DECL
58	SM_FILE_T fake;
59
60	/* While snprintf(3) specifies size_t stdio uses an int internally */
61	if (n > INT_MAX)
62		n = INT_MAX;
63	SM_VA_START(ap, fmt);
64
65	/* XXX put this into a static? */
66	fake.sm_magic = SmFileMagic;
67	fake.f_file = -1;
68	fake.f_flags = SMWR | SMSTR;
69	fake.f_cookie = &fake;
70	fake.f_bf.smb_base = fake.f_p = (unsigned char *)str;
71	fake.f_bf.smb_size = fake.f_w = n ? n - 1 : 0;
72	fake.f_timeout = SM_TIME_FOREVER;
73	fake.f_timeoutstate = SM_TIME_BLOCK;
74	fake.f_close = NULL;
75	fake.f_open = NULL;
76	fake.f_read = NULL;
77	fake.f_write = NULL;
78	fake.f_seek = NULL;
79	fake.f_setinfo = fake.f_getinfo = NULL;
80	fake.f_type = "sm_snprintf:fake";
81	ret = sm_io_vfprintf(&fake, SM_TIME_FOREVER, fmt, ap);
82	if (n > 0)
83		*fake.f_p = '\0';
84	SM_VA_END(ap);
85	return ret;
86}
87