XPRINTF(5) File Formats Manual XPRINTF(5)

xprintfextensible printf

#include <printf.h>

typedef int
printf_arginfo_function(const struct printf_info *info, size_t n, int *argtypes);

typedef int
printf_function(FILE *stream, const struct printf_info *info, const void *const *args);

The standard printf(3) family of routines provides a convenient way to convert one or more arguments to various forms for output, under the control of a format string. The format string may contain any number of conversion specifications, which start with the ‘%’ character and end with a conversion specifier character (like ‘d’ or ‘f’), with conversion flag characters in-between.

Extensible printf is an enhancement that allows adding new (user-defined) conversion specifiers, or modifying/removing existing ones. The implementation of extensible printf in Mac OS X is derived from the FreeBSD version, which is based on the one in GNU libc (GLIBC). Documentation for the GLIBC version is available at:

http://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html

The main problem with the usual forms of extensible printf is that changes to printf(3) are program-wide. But this is unsafe, since frameworks, libraries or some other thread could change printf behavior in ways unexpected by the main program, or the latter could unexpectedly affect the former.

So instead, the implementation used in Mac OS X makes changes to conversion specifiers within printf domains, which are independent structures containing the specifier definitions. These domains are created as described in xprintf_domain(3), and once set up, it can be passed to a xprintf(3) variant along with the format string and arguments to generate output. The standard printf(3) behavior is never affected.

To define a new conversion specifier, two function typedefs are defined, and the user must provide two functions based on these typedefs. These functions will get called from extensible printf while processing the corresponding conversion specification.

During the first of three phases of extensible printf processing, the format string is parsed, and for each conversion specification, a struct printf_info is created, containing the option flags specified in the conversion specification as well as other settings. Important fields in struct printf_info are:

alt
Boolean value whether the ‘#’ flag was specified.
context
A void * pointer to arbitrary data specified in the original call to register_printf_domain_function(3).
group
Boolean value whether the ‘'’ flag was specified.
is_char
Boolean value whether the ‘hh’ flag was specified.
is_intmax
Boolean value whether the ‘j’ flag was specified.
is_long
Boolean value whether the ‘l’ flag was specified.
is_long_double
Boolean value whether the ‘L’ or ‘ll’ flags were specified.
is_ptrdiff
Boolean value whether the ‘t’ flag was specified.
is_quad
Boolean value whether the ‘q’ flag was specified.
is_short
Boolean value whether the ‘h’ flag was specified.
is_size
Boolean value whether the ‘z’ flag was specified.
is_vec
Boolean value whether the ‘v’ flag was specified.
left
Boolean value whether the ‘-’ flag was specified.
loc
The extended locale (see xlocale(3)) specified by the extensible printf caller (never NULL).
pad
The padding character; either ‘0’ or space.
prec
The value of the optional precision. -1 means the precision was unspecified.
showsign
Boolean value whether the ‘+’ flag was specified.
signchar
The sign character, either ‘+’, space or zero if none.
space
Boolean value whether the space flag was specified.
spec
The specifier character itself.
vsep
The separator character between vector items (using the ‘v’ flag). Can be any one of the four characters “,:;_” or ‘X’ if no separator character was specified (meaning that a space is used as the separator, unless the specifier is ‘c’, in which case no separator is used).
width
The value of the minimum field width (defaults to zero).

All other structure fields are either unused or private (and shouldn't be used).

This struct printf_info structure is then passed to the corresponding printf_arginfo_function callback function. The callback function should return the number of consecutive arguments the specifier handles, including zero (the maximum number of consecutive arguments a single specifier can handle is __PRINTFMAXARG, which is currently set to 2, but could be increased in the future if there is need).

The callback function is also passed an integer array and the length of that array; the length will typically be __PRINTFMAXARG. The function should fill out the array up to the number of arguments it expects, using the following values:

The argument type is an int cast to a char.
The argument type is a double. OR-ing PA_DOUBLE with PA_FLAG_LONG_DOUBLE specifies a long double type.
(Defined but unused; best to avoid, since float is automatically promoted to double anyways.)
The argument type is int (either signed or unsigned). The size can be adjusted by OR-ing the following values to PA_INT:
The integer is the size of a intmax_t.
The integer is the size of a long.
The integer is the size of a long long.
The integer is the size of a ptrdiff_t.
The integer is the size of a quad_t (deprecated).
The integer is the size of a short.
The integer is the size of a size_t.
The argument type is a pointer type, cast to a void *.
The argument type is a null-terminated character string (char *).
The argument type is an AltiVec or SSE vector (16 bytes).
The argument type is a wchar_t.
The argument type is a null-terminated wide character string (wchar_t *).

After the printf_arginfo_function returns, phase 2 of extensible printf processing involves converting the argument according to the types specified by the returned type array. Note that positional arguments are dealt with here as well.

Then in phase 3, output is generated, either from the text in-between the conversion specifications, or by calling the so-called rendering functions associated with each conversion specifier (with typedef printf_function). The rendering function is passed the same struct printf_info structure, as well as an array of pointers to each of the arguments converted in phase 2 that it is responsible for. The callback should write its output to the provided output stdio stream, and then return the number of characters written.

Here is an example that demonstrates many of the features of extensible printf:

#include <stdio.h>
#include <stdlib.h>
#include <printf.h>
#include <locale.h>
#include <xlocale.h>
#include <err.h>

/* The Coordinate type */
typedef struct {
    double x;
    double y;
} Coordinate;

#define L	(1 << 0)
#define P	(1 << 1)

/* The renderer callback for Coordinate */
static int
print_coordinate (FILE *stream, const struct printf_info *info,
    const void *const *args)
{
    const Coordinate *c;
    int width, ret, which = 0;
    char fmt[32];
    char *bp, *cp, *ep;
    /* The optional coordinate labels */
    const char **labels = (const char **)info->context;

    /* Get the argument pointer to a Coordinate */
    c = *((const Coordinate **) (args[0]));

    /* Set up the format string */
    cp = fmt;
    if(info->alt) *cp++ = '(';
    bp = cp;
    if(labels) {
	which |= L;
	*cp++ = '%';
	*cp++ = 's';
    }
    *cp++ = '%';
    if(info->group) *cp++ = '\'';
    *cp++ = '*';
    if(info->prec >= 0) {
	which |= P;
	*cp++ = '.';
	*cp++ = '*';
    }
    *cp++ = 'l';
    *cp++ = 'f';
    ep = cp;
    if(info->alt) *cp++ = ',';
    *cp++ = ' ';
    while(bp < ep) *cp++ = *bp++;
    if(info->alt) *cp++ = ')';
    *cp = 0;

    width = info->left ? -info->width : info->width;

    /* Output to the given stream */
    switch(which) {
    case 0:
	ret = fprintf_l(stream, info->loc, fmt, width, c->x, width, c->y);
	break;
    case L:
	ret = fprintf_l(stream, info->loc, fmt, labels[0], width, c->x,
			labels[1], width, c->y);
	break;
    case P:
	ret = fprintf_l(stream, info->loc, fmt, width, info->prec, c->x,
			width, info->prec, c->y);
	break;
    case (L | P):
	ret = fprintf_l(stream, info->loc, fmt, labels[0], width,
			info->prec, c->x, labels[1], width, info->prec,
			c->y);
	break;
    }

    return ret;
}

/* The arginfo callback for Coordinate */
static int
coordinate_arginfo (const struct printf_info *info, size_t n,
		    int *argtypes)
{
  /* We always take exactly one argument and this is a pointer to the
     structure.. */
  if (n > 0)
    argtypes[0] = PA_POINTER;
  return 1;
}

int
main (void)
{
    Coordinate mycoordinate = {12345.6789, 3.141593};
    printf_domain_t domain;
    locale_t loc;
    const char *labels[] = {"x=", "y="};

    /* Set up a domain to add support for Coordinate conversion */
    domain = new_printf_domain();
    if(!domain)
	err(1, "new_printf_domain");
    /* Set up an extended locale to test locale support */
    loc = newlocale(LC_ALL_MASK, "uk_UA.UTF-8", NULL);
    if(!loc)
	err(1, "newlocale");

    /* Register the callbacks for Coordinates in the domain */
    register_printf_domain_function (domain, 'C', print_coordinate,
				     coordinate_arginfo, NULL);

    /* Print the coordinate using the current locale (C). */
    xprintf(domain, NULL, "|%'C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'14C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'-14.2C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'#C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'#14C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'#-14.2C|\n", &mycoordinate);

    printf("-------------\n");
    /* Reregister the callbacks, specifying coordinate labels
     * and setting the global locale (notice thousands separator) */
    register_printf_domain_function (domain, 'C', print_coordinate,
				     coordinate_arginfo, labels);
    if(setlocale(LC_ALL, "en_US.UTF-8") == NULL)
	errx(1, "setlocale");

    /* Reprint with labels */
    xprintf(domain, NULL, "|%'C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'14C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'-14.2C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'#C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'#14C|\n", &mycoordinate);
    xprintf(domain, NULL, "|%'#-14.2C|\n", &mycoordinate);

    printf("-------------\n");
    /* Now print with the test locale (notice decimal point and
     * thousands separator) */
    xprintf(domain, loc, "|%'C|\n", &mycoordinate);
    xprintf(domain, loc, "|%'14C|\n", &mycoordinate);
    xprintf(domain, loc, "|%'-14.2C|\n", &mycoordinate);
    xprintf(domain, loc, "|%'#C|\n", &mycoordinate);
    xprintf(domain, loc, "|%'#14C|\n", &mycoordinate);
    xprintf(domain, loc, "|%'#-14.2C|\n", &mycoordinate);

    return 0;
}

This example defines a Coordinate type, that consists of a pair of doubles. We create a conversion specifier that displays a Coordinate type, either just as two floating point numbers, or with the ‘#’ (alternate form) flag, as parenthesized numbers separated by a comma. Note the use of printf_l to do the actual output; this is using regular printf from within an extensible printf renderer callback. The use of printf_l also insures correct handling of extended locales.

The output of the programs looks like:

|12345.678900 3.141593|
|  12345.678900       3.141593|
|12345.68       3.14          |
|(12345.678900, 3.141593)|
|(  12345.678900,       3.141593)|
|(12345.68      , 3.14          )|
-------------
|x=12,345.678900 y=3.141593|
|x= 12,345.678900 y=      3.141593|
|x=12,345.68      y=3.14          |
|(x=12,345.678900, y=3.141593)|
|(x= 12,345.678900, y=      3.141593)|
|(x=12,345.68     , y=3.14          )|
-------------
|x=12 345,678900 y=3,141593|
|x= 12 345,678900 y=      3,141593|
|x=12 345,68      y=3,14          |
|(x=12 345,678900, y=3,141593)|
|(x= 12 345,678900, y=      3,141593)|
|(x=12 345,68     , y=3,14          )|

Notice:

Because of the three phase processing of extensible printf, as well as the use of two callbacks for each conversion specifier, performance is considerably slower than the one pass, highly optimized regular printf(3). Recursive use of printf(3) from within an extensible printf renderer callback (as in the EXAMPLE above) adds additional overhead.

To ameliorate some of this slowness, the concept of separate compilation and execution phases has be added to extensible printf. The functions in xprintf_comp(3) allow the creation of pre-compiled extensible printf structures (performing phase one of extensible printf processing). These pre-compiled structures can then be passed to the printf variants in xprintf_exec(3) to produce the actual output (performing phases 2 and 3). The compilation phase need only be done once, while execution can be performed any number of times.

A simple example of use is:

    printf_comp_t pc = new_printf_comp(domain, loc, "%d: %C\n");
    for(i = 0; i = sizeof(coords) / sizeof(*coords); i++) {
	xprintf_exec(pc, i, &coords[i]);
    }
    free_printf_comp(pc);

Here, coords is a array containing Coordinate structures that are to be printed and the domain and loc variables are as from EXAMPLE above. (Error checking on the return value from () is not shown).

printf(3), xlocale(3), xprintf(3), xprintf_comp(3), xprintf_domain(3), xprintf_exec(3)

August 19, 2012 Darwin