Perfect Hash Function Generator - 3 High-Level Description of GNU gperf

Go to the first, previous, next, last section, table of contents.

# 3 High-Level Description of GNU `gperf`

The perfect hash function generator `gperf` reads a set of "keywords" from a keyfile (or from the standard input by default). It attempts to derive a perfect hashing function that recognizes a member of the static keyword set with at most a single probe into the lookup table. If `gperf` succeeds in generating such a function it produces a pair of C source code routines that perform hashing and table lookup recognition. All generated C code is directed to the standard output. Command-line options described below allow you to modify the input and output format to `gperf`.

By default, `gperf` attempts to produce time-efficient code, with less emphasis on efficient space utilization. However, several options exist that permit trading-off execution time for storage space and vice versa. In particular, expanding the generated table size produces a sparse search structure, generally yielding faster searches. Conversely, you can direct `gperf` to utilize a C `switch` statement scheme that minimizes data space storage size. Furthermore, using a C `switch` may actually speed up the keyword retrieval time somewhat. Actual results depend on your C compiler, of course.

In general, `gperf` assigns values to the characters it is using for hashing until some set of values gives each keyword a unique value. A helpful heuristic is that the larger the hash value range, the easier it is for `gperf` to find and generate a perfect hash function. Experimentation is the key to getting the most from `gperf`.

## 3.1 Input Format to `gperf`

You can control the input keyfile format by varying certain command-line arguments, in particular the ``-t'` option. The input's appearance is similar to GNU utilities `flex` and `bison` (or UNIX utilities `lex` and `yacc`). Here's an outline of the general format:

    declarations
    %%
    keywords
    %%
    functions

Unlike `flex` or `bison`, all sections of `gperf`'s input are optional. The following sections describe the input format for each section.

### 3.1.1 `struct` Declarations and C Code Inclusion

The keyword input file optionally contains a section for including arbitrary C declarations and definitions, as well as provisions for providing a user-supplied `struct`. If the ``-t'` option is enabled, you must provide a C `struct` as the last component in the declaration section from the keyfile file. The first field in this struct must be a `char *` or `const char *` identifier called ``name'`, although it is possible to modify this field's name with the ``-K'` option described below.

Here is a simple example, using months of the year and their attributes as input:

    struct months { char *name; int number; int days; int leap_days; };
    %%
    january,   1, 31, 31
    february,  2, 28, 29
    march,     3, 31, 31
    april,     4, 30, 30
    may,       5, 31, 31
    june,      6, 30, 30
    july,      7, 31, 31
    august,    8, 31, 31
    september, 9, 30, 30
    october,  10, 31, 31
    november, 11, 30, 30
    december, 12, 31, 31

Separating the `struct` declaration from the list of keywords and other fields are a pair of consecutive percent signs, ``%%'`, appearing left justified in the first column, as in the UNIX utility `lex`.

Using a syntax similar to GNU utilities `flex` and `bison`, it is possible to directly include C source text and comments verbatim into the generated output file. This is accomplished by enclosing the region inside left-justified surrounding ``%{'`, ``%}'` pairs. Here is an input fragment based on the previous example that illustrates this feature:

    %{
    #include <assert.h>
    /* This section of code is inserted directly into the output. */
    int return_month_days (struct months *months, int is_leap_year);
    %}
    struct months { char *name; int number; int days; int leap_days; };
    %%
    january,   1, 31, 31
    february,  2, 28, 29
    march,     3, 31, 31
    ...

It is possible to omit the declaration section entirely. In this case the keyfile begins directly with the first keyword line, e.g.:

    january,   1, 31, 31
    february,  2, 28, 29
    march,     3, 31, 31
    april,     4, 30, 30
    ...

### 3.1.2 Format for Keyword Entries

The second keyfile format section contains lines of keywords and any associated attributes you might supply. A line beginning with ``#'` in the first column is considered a comment. Everything following the ``#'` is ignored, up to and including the following newline.

The first field of each non-comment line is always the key itself. It can be given in two ways: as a simple name, i.e., without surrounding string quotation marks, or as a string enclosed in double-quotes, in C syntax, possibly with backslash escapes like `\"` or `\234` or `\xa8`. In either case, it must start right at the beginning of the line, without leading whitespace. In this context, a "field" is considered to extend up to, but not include, the first blank, comma, or newline. Here is a simple example taken from a partial list of C reserved words:

    # These are a few C reserved words, see the c.gperf file
    # for a complete list of ANSI C reserved words.
    unsigned
    sizeof
    switch
    signed
    if
    default
    for
    while
    return

Note that unlike `flex` or `bison` the first ``%%'` marker may be elided if the declaration section is empty.

Additional fields may optionally follow the leading keyword. Fields should be separated by commas, and terminate at the end of line. What these fields mean is entirely up to you; they are used to initialize the elements of the user-defined `struct` provided by you in the declaration section. If the ``-t'` option is not enabled these fields are simply ignored. All previous examples except the last one contain keyword attributes.

### 3.1.3 Including Additional C Functions

The optional third section also corresponds closely with conventions found in `flex` and `bison`. All text in this section, starting at the final ``%%'` and extending to the end of the input file, is included verbatim into the generated output file. Naturally, it is your responsibility to ensure that the code contained in this section is valid C.

## 3.2 Output Format for Generated C Code with `gperf`

Several options control how the generated C code appears on the standard output. Two C function are generated. They are called `hash` and `in_word_set`, although you may modify their names with a command-line option. Both functions require two arguments, a string, `char *` str, and a length parameter, `int` len. Their default function prototypes are as follows:

Function: unsigned int hash (const char * str, unsigned int len)
  By default, the generated `hash` function returns an integer value created by adding len to several user-specified str key positions indexed into an associated values table stored in a local static array. The associated values table is constructed internally by `gperf` and later output as a static local C array called ``hash_table'`; its meaning and properties are described below (see section 7 Implementation Details of GNU `gperf`). The relevant key positions are specified via the ``-k'` option when running `gperf`, as detailed in the Options section below(see section 4 Invoking `gperf`).

Function: in_word_set (const char * str, unsigned int len)
  If str is in the keyword set, returns a pointer to that keyword. More exactly, if the option ``-t'` was given, it returns a pointer to the matching keyword's structure. Otherwise it returns `NULL`.

If the option ``-c'` is not used, str must be a NUL terminated string of exactly length len. If ``-c'` is used, str must simply be an array of len characters and does not need to be NUL terminated.

The code generated for these two functions is affected by the following options:

``-t'`
``--struct-type'`
  Make use of the user-defined `struct`.
``-S total-switch-statements'`
``--switch=total-switch-statements'`
  Generate 1 or more C `switch` statement rather than use a large, (and potentially sparse) static array. Although the exact time and space savings of this approach vary according to your C compiler's degree of optimization, this method often results in smaller and faster code.

If the ``-t'` and ``-S'` options are omitted, the default action is to generate a `char *` array containing the keys, together with additional null strings used for padding the array. By experimenting with the various input and output options, and timing the resulting C code, you can determine the best option choices for different keyword set characteristics.

## 3.3 Use of NUL characters

By default, the code generated by `gperf` operates on zero terminated strings, the usual representation of strings in C. This means that the keywords in the input file must not contain NUL characters, and the str argument passed to `hash` or `in_word_set` must be NUL terminated and have exactly length len.

If option ``-c'` is used, then the str argument does not need to be NUL terminated. The code generated by `gperf` will only access the first len, not len+1, bytes starting at str. However, the keywords in the input file still must not contain NUL characters.

If option ``-l'` is used, then the hash table performs binary comparison. The keywords in the input file may contain NUL characters, written in string syntax as `\000` or `\x00`, and the code generated by `gperf` will treat NUL like any other character. Also, in this case the ``-c'` option is ignored.

Go to the first, previous, next, last section, table of contents.