3 /* Purpose: Low level text formatting -BEN- */
12 * Here is some information about the routines in this file.
14 * In general, the following routines take a "buffer", a "max length",
15 * a "format string", and some "arguments", and use the format string
16 * and the arguments to create a (terminated) string in the buffer
17 * (using only the first "max length" bytes), and return the "length"
18 * of the resulting string, not including the (mandatory) terminator.
20 * The format strings allow the basic "sprintf()" format sequences, though
21 * some of them are processed slightly more carefully or portably, as well
22 * as a few "special" sequences, including the "%r" and "%v" sequences, and
23 * the "capilitization" sequences of "%C", "%S", and "%V".
25 * Note that some "limitations" are enforced by the current implementation,
26 * for example, no "format sequence" can exceed 100 characters, including any
27 * "length" restrictions, and the result of combining and "format sequence"
28 * with the relevent "arguments" must not exceed 1000 characters.
30 * These limitations could be fixed by stealing some of the code from,
31 * say, "vsprintf()" and placing it into my "vstrnfmt()" function.
33 * Note that a "^" inside a "format sequence" causes the first non-space
34 * character in the string resulting from the combination of the format
35 * sequence and the argument(s) to be "capitalized" if possible. Note
36 * that the "^" character is removed before the "standard" formatting
37 * routines are called. Likewise, a "*" inside a "format sequence" is
38 * removed from the "format sequence", and replaced by the textual form
39 * of the next argument in the argument list. See examples below.
41 * Legal format characters: %,n,p,c,s,d,i,o,u,X,x,E,e,F,f,G,g,r,v.
44 * Append the literal "%".
47 * Format("%n", int *np)
48 * Save the current length into (*np).
51 * Format("%p", vptr v)
52 * Append the pointer "v" (implementation varies).
55 * Format("%E", double r)
56 * Format("%F", double r)
57 * Format("%G", double r)
58 * Format("%e", double r)
59 * Format("%f", double r)
60 * Format("%g", double r)
61 * Append the double "r", in various formats.
63 * Format("%ld", long int i)
64 * Append the long integer "i".
67 * Append the integer "i".
69 * Format("%lu", unsigned long int i)
70 * Append the unsigned long integer "i".
72 * Format("%u", unsigned int i)
73 * Append the unsigned integer "i".
75 * Format("%lo", unsigned long int i)
76 * Append the unsigned long integer "i", in octal.
78 * Format("%o", unsigned int i)
79 * Append the unsigned integer "i", in octal.
81 * Format("%lX", unsigned long int i)
82 * Note -- use all capital letters
83 * Format("%lx", unsigned long int i)
84 * Append the unsigned long integer "i", in hexidecimal.
86 * Format("%X", unsigned int i)
87 * Note -- use all capital letters
88 * Format("%x", unsigned int i)
89 * Append the unsigned integer "i", in hexidecimal.
91 * Format("%c", char c)
92 * Append the character "c".
93 * Do not use the "+" or "0" flags.
95 * Format("%s", cptr s)
96 * Append the string "s".
97 * Do not use the "+" or "0" flags.
98 * Note that a "NULL" value of "s" is converted to the empty string.
100 * Format("%V", vptr v)
101 * Note -- possibly significant mode flag
102 * Format("%v", vptr v)
103 * Append the object "v", using the current "user defined print routine".
104 * User specified modifiers, often ignored.
106 * Format("%r", vstrnfmt_aux_func *fp)
107 * Set the "user defined print routine" (vstrnfmt_aux) to "fp".
108 * No legal modifiers.
111 * For examples below, assume "int n = 0; int m = 100; char buf[100];",
112 * plus "char *s = NULL;", and unknown values "char *txt; int i;".
114 * For example: "n = strnfmt(buf, -1, "(Max %d)", i);" will have a
115 * similar effect as "sprintf(buf, "(Max %d)", i); n = strlen(buf);".
117 * For example: "(void)strnfmt(buf, 16, "%s", txt);" will have a similar
118 * effect as "strncpy(buf, txt, 16); buf[15] = '\0';".
120 * For example: "if (strnfmt(buf, 16, "%s", txt) < 16) ..." will have
121 * a similar effect as "strcpy(buf, txt)" but with bounds checking.
123 * For example: "s = buf; s += vstrnfmt(s, -1, ...); ..." will allow
124 * multiple "appends" to "buf" (at the cost of losing the max-length info).
126 * For example: "s = buf; n = vstrnfmt(s+n, 100-n, ...); ..." will allow
127 * multiple bounded "appends" to "buf", with constant access to "strlen(buf)".
129 * For example: "format("The %r%v was destroyed!", obj_desc, obj);"
130 * (where "obj_desc(buf, max, fmt, obj)" will "append" a "description"
131 * of the given object to the given buffer, and return the total length)
132 * will return a "useful message" about the object "obj", for example,
133 * "The Large Shield was destroyed!".
135 * For example: "format("%^-.*s", i, txt)" will produce a string containing
136 * the first "i" characters of "txt", left justified, with the first non-space
137 * character capitilized, if reasonable.
145 * The "type" of the "user defined print routine" pointer
147 typedef uint (*vstrnfmt_aux_func)(char *buf, uint max, cptr fmt, vptr arg);
150 * The "default" user defined print routine. Ignore the "fmt" string.
152 static uint vstrnfmt_aux_dflt(char *buf, uint max, cptr fmt, vptr arg)
160 /* Pointer display */
161 sprintf(tmp, "<<%p>>", arg);
163 if (len >= max) len = max - 1;
170 * The "current" user defined print routine. It can be changed
171 * dynamically by sending the proper "%r" sequence to "vstrnfmt()"
173 static vstrnfmt_aux_func vstrnfmt_aux = vstrnfmt_aux_dflt;
178 * Basic "vararg" format function.
180 * This function takes a buffer, a max byte count, a format string, and
181 * a va_list of arguments to the format string, and uses the format string
182 * and the arguments to create a string to the buffer. The string is
183 * derived from the format string and the arguments in the manner of the
184 * "sprintf()" function, but with some extra "format" commands. Note that
185 * this function will never use more than the given number of bytes in the
186 * buffer, preventing messy invalid memory references. This function then
187 * returns the total number of non-null bytes written into the buffer.
189 * Method: Let "str" be the (unlimited) created string, and let "len" be the
190 * smaller of "max-1" and "strlen(str)". We copy the first "len" chars of
191 * "str" into "buf", place "\0" into buf[len], and return "len".
193 * In English, we do a sprintf() into "buf", a buffer with size "max",
194 * and we return the resulting value of "strlen(buf)", but we allow some
195 * special format commands, and we are more careful than "sprintf()".
197 * Typically, "max" is in fact the "size" of "buf", and thus represents
198 * the "number" of chars in "buf" which are ALLOWED to be used. An
199 * alternative definition would have required "buf" to hold at least
200 * "max+1" characters, and would have used that extra character only
201 * in the case where "buf" was too short for the result. This would
202 * give an easy test for "overflow", but a less "obvious" semantics.
204 * Note that if the buffer was "too short" to hold the result, we will
205 * always return "max-1", but we also return "max-1" if the buffer was
206 * "just long enough". We could have returned "max" if the buffer was
207 * too short, not written a null, and forced the programmer to deal with
208 * this special case, but I felt that it is better to at least give a
209 * "usable" result when the buffer was too long instead of either giving
210 * a memory overwrite like "sprintf()" or a non-terminted string like
211 * "strncpy()". Note that "strncpy()" also "null-pads" the result.
213 * Note that in most cases "just long enough" is probably "too short".
215 * We should also consider extracting and processing the "width" and other
216 * "flags" by hand, it might be more "accurate", and it would allow us to
217 * remove the limit (1000 chars) on the result of format sequences.
219 * Also, some sequences, such as "%+d" by hand, do not work on all machines,
220 * and could thus be correctly handled here.
222 * Error detection in this routine is not very graceful, in particular,
223 * if an error is detected in the format string, we simply "pre-terminate"
224 * the given buffer to a length of zero, and return a "length" of zero.
225 * The contents of "buf", except for "buf[0]", may then be undefined.
227 uint vstrnfmt(char *buf, uint max, cptr fmt, va_list vp)
231 /* The argument is "long" */
234 /* The argument needs "processing" */
237 /* Bytes used in buffer */
240 /* Bytes used in format sequence */
243 /* Format sequence */
246 /* Resulting string */
250 /* Mega-Hack -- treat "illegal" length as "infinite" */
251 if (!max) max = 32767;
253 /* Mega-Hack -- treat "no format" as "empty string" */
257 /* Begin the buffer */
260 /* Begin the format string */
263 /* Scan the format string */
269 /* Normal character */
272 /* Check total length */
273 if (n == max-1) break;
275 /* Save the character */
282 /* Skip the "percent" */
285 /* Pre-process "%%" */
288 /* Check total length */
289 if (n == max-1) break;
291 /* Save the percent */
301 /* Pre-process "%n" */
306 /* Access the next argument */
307 arg = va_arg(vp, int *);
309 /* Save the current length */
319 /* Hack -- Pre-process "%r" */
322 /* Extract the next argument, and save it (globally) */
323 vstrnfmt_aux = va_arg(vp, vstrnfmt_aux_func);
333 /* Begin the "aux" string */
336 /* Save the "percent" */
339 /* Assume no "long" argument */
342 /* Assume no "xtra" processing */
345 /* Build the "aux" string */
348 /* Error -- format sequence is not terminated */
351 /* Terminate the buffer */
358 /* Error -- format sequence may be too long */
361 /* Terminate the buffer */
368 /* Handle "alphabetic" chars */
371 /* Hack -- handle "long" request */
374 /* Save the character */
377 /* Note the "long" flag */
381 /* Mega-Hack -- handle "extra-long" request */
384 /* Error -- illegal format char */
391 /* Handle normal end of format sequence */
394 /* Save the character */
397 /* Stop processing the format sequence */
402 /* Handle "non-alphabetic" chars */
405 /* Hack -- Handle 'star' (for "variable length" argument) */
410 /* Access the next argument */
411 arg = va_arg(vp, int);
413 /* Hack -- append the "length" */
414 sprintf(aux + q, "%d", arg);
416 /* Hack -- accept the "length" */
423 /* Mega-Hack -- Handle 'caret' (for "uppercase" request) */
426 /* Note the "xtra" flag */
433 /* Collect "normal" characters (digits, "-", "+", ".", etc) */
436 /* Save the character */
443 /* Terminate "aux" */
449 /* Process the "format" char */
452 /* Simple Character -- standard format */
457 /* Access next argument */
458 arg = va_arg(vp, int);
460 /* Format the argument */
461 sprintf(tmp, aux, arg);
467 /* Signed Integers -- standard format */
474 /* Access next argument */
475 arg = va_arg(vp, long);
477 /* Format the argument */
478 sprintf(tmp, aux, arg);
484 /* Access next argument */
485 arg = va_arg(vp, int);
487 /* Format the argument */
488 sprintf(tmp, aux, arg);
495 /* Unsigned Integers -- various formats */
496 case 'u': case 'o': case 'x': case 'X':
502 /* Access next argument */
503 arg = va_arg(vp, unsigned long);
505 /* Format the argument */
506 sprintf(tmp, aux, arg);
512 /* Access next argument */
513 arg = va_arg(vp, unsigned int);
515 /* Format the argument */
516 sprintf(tmp, aux, arg);
523 /* Floating Point -- various formats */
530 /* Access next argument */
531 arg = va_arg(vp, double);
533 /* Format the argument */
534 sprintf(tmp, aux, arg);
540 /* Pointer -- implementation varies */
545 /* Access next argument */
546 arg = va_arg(vp, vptr);
548 /* Format the argument */
549 sprintf(tmp, aux, arg);
561 /* Access next argument */
562 arg = va_arg(vp, cptr);
564 /* Hack -- convert NULL to EMPTY */
567 /* Prevent buffer overflows */
568 strncpy(arg2, arg, 1024);
571 /* Format the argument */
572 sprintf(tmp, aux, arg2);
578 /* User defined data */
584 /* Access next argument */
585 arg = va_arg(vp, vptr);
587 /* Format the "user data" */
588 (void)vstrnfmt_aux(tmp, 1000, aux, arg);
598 /* Error -- illegal format char */
608 for (q = 0; tmp[q]; q++) if ( iskanji(tmp[q]) ) { do_xtra=FALSE;break;}
610 /* Mega-Hack -- handle "capitilization" */
613 /* Now append "tmp" to "buf" */
614 for (q = 0; tmp[q]; q++)
616 /* Notice first non-space */
617 if (!isspace(tmp[q]))
619 /* Capitalize if possible */
621 if (!iskanji(tmp[q]))
624 tmp[q] = toupper(tmp[q]);
632 /* Now append "tmp" to "buf" */
633 for (q = 0; tmp[q]; q++)
635 /* Check total length */
636 if (n == max-1) break;
638 /* Save the character */
644 /* Terminate buffer */
653 * Do a vstrnfmt (see above) into a (growable) static buffer.
654 * This buffer is usable for very short term formatting of results.
656 char *vformat(cptr fmt, va_list vp)
658 static char *format_buf = NULL;
659 static huge format_len = 0;
661 /* Initial allocation */
665 C_MAKE(format_buf, format_len, char);
668 /* Null format yields last result */
669 if (!fmt) return (format_buf);
671 /* Keep going until successful */
676 /* Build the string */
677 len = vstrnfmt(format_buf, format_len, fmt, vp);
680 if (len < format_len-1) break;
682 /* Grow the buffer */
683 C_KILL(format_buf, format_len, char);
684 format_len = format_len * 2;
685 C_MAKE(format_buf, format_len, char);
688 /* Return the new buffer */
695 * Do a vstrnfmt (see above) into a buffer of a given size.
697 uint strnfmt(char *buf, uint max, cptr fmt, ...)
703 /* Begin the Varargs Stuff */
706 /* Do a virtual fprintf to stderr */
707 len = vstrnfmt(buf, max, fmt, vp);
709 /* End the Varargs Stuff */
712 /* Return the number of bytes written */
718 * Do a vstrnfmt (see above) into a buffer of unknown size.
719 * Since the buffer size is unknown, the user better verify the args.
721 uint strfmt(char *buf, cptr fmt, ...)
727 /* Begin the Varargs Stuff */
730 /* Build the string, assume 32K buffer */
731 len = vstrnfmt(buf, 32767, fmt, vp);
733 /* End the Varargs Stuff */
736 /* Return the number of bytes written */
744 * Do a vstrnfmt() into (see above) into a (growable) static buffer.
745 * This buffer is usable for very short term formatting of results.
746 * Note that the buffer is (technically) writable, but only up to
747 * the length of the string contained inside it.
749 char *format(cptr fmt, ...)
754 /* Begin the Varargs Stuff */
757 /* Format the args */
758 res = vformat(fmt, vp);
760 /* End the Varargs Stuff */
763 /* Return the result */
771 * Vararg interface to plog()
773 void plog_fmt(cptr fmt, ...)
778 /* Begin the Varargs Stuff */
781 /* Format the args */
782 res = vformat(fmt, vp);
784 /* End the Varargs Stuff */
794 * Vararg interface to quit()
796 void quit_fmt(cptr fmt, ...)
801 /* Begin the Varargs Stuff */
805 res = vformat(fmt, vp);
807 /* End the Varargs Stuff */
817 * Vararg interface to core()
819 void core_fmt(cptr fmt, ...)
824 /* Begin the Varargs Stuff */
827 /* If requested, Do a virtual fprintf to stderr */
828 res = vformat(fmt, vp);
830 /* End the Varargs Stuff */