]> code.delx.au - gnu-emacs/blob - src/doprnt.c
* doprnt.c (doprnt): Support "ll" length modifier, for long long.
[gnu-emacs] / src / doprnt.c
1 /* Output like sprintf to a buffer of specified size.
2 Also takes args differently: pass one pointer to the end
3 of the format string in addition to the format string itself.
4 Copyright (C) 1985, 2001-2011 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 /* If you think about replacing this with some similar standard C function of
22 the printf family (such as vsnprintf), please note that this function
23 supports the following Emacs-specific features:
24
25 . For %c conversions, it produces a string with the multibyte representation
26 of the (`int') argument, suitable for display in an Emacs buffer.
27
28 . For %s and %c, when field width is specified (e.g., %25s), it accounts for
29 the diplay width of each character, according to char-width-table. That
30 is, it does not assume that each character takes one column on display.
31
32 . If the size of the buffer is not enough to produce the formatted string in
33 its entirety, it makes sure that truncation does not chop the last
34 character in the middle of its multibyte sequence, producing an invalid
35 sequence.
36
37 . It accepts a pointer to the end of the format string, so the format string
38 could include embedded null characters.
39
40 . It signals an error if the length of the formatted string is about to
41 overflow MOST_POSITIVE_FIXNUM, to avoid producing strings longer than what
42 Emacs can handle.
43
44 OTOH, this function supports only a small subset of the standard C formatted
45 output facilities. E.g., %u and %ll are not supported, and precision is
46 ignored %s and %c conversions. (See below for the detailed documentation of
47 what is supported.) However, this is okay, as this function is supposed to
48 be called from `error' and similar functions, and thus does not need to
49 support features beyond those in `Fformat', which is used by `error' on the
50 Lisp level. */
51
52 /* This function supports the following %-sequences in the `format'
53 argument:
54
55 %s means print a string argument.
56 %S is silently treated as %s, for loose compatibility with `Fformat'.
57 %d means print a `signed int' argument in decimal.
58 %l means print a `long int' argument in decimal.
59 %o means print an `unsigned int' argument in octal.
60 %x means print an `unsigned int' argument in hex.
61 %e means print a `double' argument in exponential notation.
62 %f means print a `double' argument in decimal-point notation.
63 %g means print a `double' argument in exponential notation
64 or in decimal-point notation, whichever uses fewer characters.
65 %c means print a `signed int' argument as a single character.
66 %% means produce a literal % character.
67
68 A %-sequence may contain optional flag, width, and precision specifiers, as
69 follows:
70
71 %<flags><width><precision>character
72
73 where flags is [+ -0l], width is [0-9]+, and precision is .[0-9]+
74
75 The + flag character inserts a + before any positive number, while a space
76 inserts a space before any positive number; these flags only affect %d, %l,
77 %o, %x, %e, %f, and %g sequences. The - and 0 flags affect the width
78 specifier, as described below.
79
80 The l (lower-case letter ell) flag is a `long' data type modifier: it is
81 supported for %d, %o, and %x conversions of integral arguments, and means
82 that the respective argument is to be treated as `long int' or `unsigned
83 long int'. ll means to use 'long long'. EMACS_INT arguments
84 should use the pI macro, which expands to whatever length modifier
85 is needed for the target host, e.g., "", "l", "ll".
86
87 The width specifier supplies a lower limit for the length of the printed
88 representation. The padding, if any, normally goes on the left, but it goes
89 on the right if the - flag is present. The padding character is normally a
90 space, but (for numerical arguments only) it is 0 if the 0 flag is present.
91 The - flag takes precedence over the 0 flag.
92
93 For %e, %f, and %g sequences, the number after the "." in the precision
94 specifier says how many decimal places to show; if zero, the decimal point
95 itself is omitted. For %s and %S, the precision specifier is ignored. */
96
97 #include <config.h>
98 #include <stdio.h>
99 #include <ctype.h>
100 #include <setjmp.h>
101
102 #ifdef STDC_HEADERS
103 #include <float.h>
104 #endif
105
106 #include <unistd.h>
107
108 #include <limits.h>
109 #ifndef SIZE_MAX
110 # define SIZE_MAX ((size_t) -1)
111 #endif
112
113 #include "lisp.h"
114
115 /* Since we use the macro CHAR_HEAD_P, we have to include this, but
116 don't have to include others because CHAR_HEAD_P does not contains
117 another macro. */
118 #include "character.h"
119
120 #ifndef DBL_MAX_10_EXP
121 #define DBL_MAX_10_EXP 308 /* IEEE double */
122 #endif
123
124 /* Generate output from a format-spec FORMAT,
125 terminated at position FORMAT_END.
126 Output goes in BUFFER, which has room for BUFSIZE chars.
127 If the output does not fit, truncate it to fit.
128 Returns the number of bytes stored into BUFFER, excluding
129 the terminating null byte. Output is always null-terminated.
130 String arguments are passed as C strings.
131 Integers are passed as C integers. */
132
133 size_t
134 doprnt (char *buffer, register size_t bufsize, const char *format,
135 const char *format_end, va_list ap)
136 {
137 const char *fmt = format; /* Pointer into format string */
138 register char *bufptr = buffer; /* Pointer into output buffer.. */
139
140 /* Use this for sprintf unless we need something really big. */
141 char tembuf[DBL_MAX_10_EXP + 100];
142
143 /* Size of sprintf_buffer. */
144 size_t size_allocated = sizeof (tembuf);
145
146 /* Buffer to use for sprintf. Either tembuf or same as BIG_BUFFER. */
147 char *sprintf_buffer = tembuf;
148
149 /* Buffer we have got with malloc. */
150 char *big_buffer = NULL;
151
152 register size_t tem;
153 char *string;
154 char fixed_buffer[20]; /* Default buffer for small formatting. */
155 char *fmtcpy;
156 int minlen;
157 char charbuf[MAX_MULTIBYTE_LENGTH + 1]; /* Used for %c. */
158 USE_SAFE_ALLOCA;
159
160 if (format_end == 0)
161 format_end = format + strlen (format);
162
163 if ((format_end - format + 1) < sizeof (fixed_buffer))
164 fmtcpy = fixed_buffer;
165 else
166 SAFE_ALLOCA (fmtcpy, char *, format_end - format + 1);
167
168 bufsize--;
169
170 /* Loop until end of format string or buffer full. */
171 while (fmt != format_end && bufsize > 0)
172 {
173 if (*fmt == '%') /* Check for a '%' character */
174 {
175 size_t size_bound = 0;
176 EMACS_INT width; /* Columns occupied by STRING on display. */
177 int long_flag = 0;
178
179 fmt++;
180 /* Copy this one %-spec into fmtcpy. */
181 string = fmtcpy;
182 *string++ = '%';
183 while (1)
184 {
185 *string++ = *fmt;
186 if ('0' <= *fmt && *fmt <= '9')
187 {
188 /* Get an idea of how much space we might need.
189 This might be a field width or a precision; e.g.
190 %1.1000f and %1000.1f both might need 1000+ bytes.
191 Parse the width or precision, checking for overflow. */
192 size_t n = *fmt - '0';
193 while ('0' <= fmt[1] && fmt[1] <= '9')
194 {
195 if (n >= SIZE_MAX / 10
196 || n * 10 > SIZE_MAX - (fmt[1] - '0'))
197 error ("Format width or precision too large");
198 n = n * 10 + fmt[1] - '0';
199 *string++ = *++fmt;
200 }
201
202 if (size_bound < n)
203 size_bound = n;
204 }
205 else if (*fmt == '-' || *fmt == ' ' || *fmt == '.' || *fmt == '+')
206 ;
207 else if (*fmt == 'l')
208 {
209 long_flag = 1;
210 if (fmt[1] == 'l')
211 {
212 long_flag = 2;
213 fmt++;
214 }
215 if (!strchr ("dox", fmt[1]))
216 /* %l as conversion specifier, not as modifier. */
217 break;
218 }
219 else
220 break;
221 fmt++;
222 }
223 *string = 0;
224
225 /* Make the size bound large enough to handle floating point formats
226 with large numbers. */
227 if (size_bound > SIZE_MAX - DBL_MAX_10_EXP - 50)
228 error ("Format width or precision too large");
229 size_bound += DBL_MAX_10_EXP + 50;
230
231 /* Make sure we have that much. */
232 if (size_bound > size_allocated)
233 {
234 if (big_buffer)
235 big_buffer = (char *) xrealloc (big_buffer, size_bound);
236 else
237 big_buffer = (char *) xmalloc (size_bound);
238 sprintf_buffer = big_buffer;
239 size_allocated = size_bound;
240 }
241 minlen = 0;
242 switch (*fmt++)
243 {
244 default:
245 error ("Invalid format operation %%%c", fmt[-1]);
246
247 /* case 'b': */
248 case 'l':
249 case 'd':
250 {
251 int i;
252 long l;
253
254 if (1 < long_flag)
255 {
256 #ifdef HAVE_LONG_LONG_INT
257 long long ll = va_arg (ap, long long);
258 sprintf (sprintf_buffer, fmtcpy, ll);
259 #else
260 abort ();
261 #endif
262 }
263 else if (long_flag)
264 {
265 l = va_arg(ap, long);
266 sprintf (sprintf_buffer, fmtcpy, l);
267 }
268 else
269 {
270 i = va_arg(ap, int);
271 sprintf (sprintf_buffer, fmtcpy, i);
272 }
273 /* Now copy into final output, truncating as necessary. */
274 string = sprintf_buffer;
275 goto doit;
276 }
277
278 case 'o':
279 case 'x':
280 {
281 unsigned u;
282 unsigned long ul;
283
284 if (1 < long_flag)
285 {
286 #ifdef HAVE_UNSIGNED_LONG_LONG_INT
287 unsigned long long ull = va_arg (ap, unsigned long long);
288 sprintf (sprintf_buffer, fmtcpy, ull);
289 #else
290 abort ();
291 #endif
292 }
293 else if (long_flag)
294 {
295 ul = va_arg(ap, unsigned long);
296 sprintf (sprintf_buffer, fmtcpy, ul);
297 }
298 else
299 {
300 u = va_arg(ap, unsigned);
301 sprintf (sprintf_buffer, fmtcpy, u);
302 }
303 /* Now copy into final output, truncating as necessary. */
304 string = sprintf_buffer;
305 goto doit;
306 }
307
308 case 'f':
309 case 'e':
310 case 'g':
311 {
312 double d = va_arg(ap, double);
313 sprintf (sprintf_buffer, fmtcpy, d);
314 /* Now copy into final output, truncating as necessary. */
315 string = sprintf_buffer;
316 goto doit;
317 }
318
319 case 'S':
320 string[-1] = 's';
321 case 's':
322 if (fmtcpy[1] != 's')
323 minlen = atoi (&fmtcpy[1]);
324 string = va_arg (ap, char *);
325 tem = strlen (string);
326 if (tem > MOST_POSITIVE_FIXNUM)
327 error ("String for %%s or %%S format is too long");
328 width = strwidth (string, tem);
329 goto doit1;
330
331 /* Copy string into final output, truncating if no room. */
332 doit:
333 /* Coming here means STRING contains ASCII only. */
334 tem = strlen (string);
335 if (tem > MOST_POSITIVE_FIXNUM)
336 error ("Format width or precision too large");
337 width = tem;
338 doit1:
339 /* We have already calculated:
340 TEM -- length of STRING,
341 WIDTH -- columns occupied by STRING when displayed, and
342 MINLEN -- minimum columns of the output. */
343 if (minlen > 0)
344 {
345 while (minlen > width && bufsize > 0)
346 {
347 *bufptr++ = ' ';
348 bufsize--;
349 minlen--;
350 }
351 minlen = 0;
352 }
353 if (tem > bufsize)
354 {
355 /* Truncate the string at character boundary. */
356 tem = bufsize;
357 while (!CHAR_HEAD_P (string[tem - 1])) tem--;
358 memcpy (bufptr, string, tem);
359 /* We must calculate WIDTH again. */
360 width = strwidth (bufptr, tem);
361 }
362 else
363 memcpy (bufptr, string, tem);
364 bufptr += tem;
365 bufsize -= tem;
366 if (minlen < 0)
367 {
368 while (minlen < - width && bufsize > 0)
369 {
370 *bufptr++ = ' ';
371 bufsize--;
372 minlen++;
373 }
374 minlen = 0;
375 }
376 continue;
377
378 case 'c':
379 {
380 int chr = va_arg(ap, int);
381 tem = CHAR_STRING (chr, (unsigned char *) charbuf);
382 string = charbuf;
383 string[tem] = 0;
384 width = strwidth (string, tem);
385 if (fmtcpy[1] != 'c')
386 minlen = atoi (&fmtcpy[1]);
387 goto doit1;
388 }
389
390 case '%':
391 fmt--; /* Drop thru and this % will be treated as normal */
392 }
393 }
394
395 {
396 /* Just some character; Copy it if the whole multi-byte form
397 fit in the buffer. */
398 char *save_bufptr = bufptr;
399
400 do { *bufptr++ = *fmt++; }
401 while (--bufsize > 0 && !CHAR_HEAD_P (*fmt));
402 if (!CHAR_HEAD_P (*fmt))
403 {
404 bufptr = save_bufptr;
405 break;
406 }
407 }
408 };
409
410 /* If we had to malloc something, free it. */
411 xfree (big_buffer);
412
413 *bufptr = 0; /* Make sure our string ends with a '\0' */
414
415 SAFE_FREE ();
416 return bufptr - buffer;
417 }