Useless Containers Library


Next: , Up: (dir)

Useless Containers Library

This document describes version 2.0d2 of Useless Containers Library, a C language library implementing a set of containers.

The package is distributed under the terms of the GNU General Public License (GPL).

The latest release can be downloaded from:

https://bitbucket.org/marcomaggi/ucl/downloads

development takes place at:

http://github.com/marcomaggi/ucl

and as backup at:

https://bitbucket.org/marcomaggi/ucl

Copyright © 2001-2010, 2013, 2015 by Marco Maggi marco.maggi-ipsu@poste.it

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with Invariant Sections being “GNU Free Documentation License” and “GNU General Public License”, no Front–Cover Texts, and no Back–Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”.

Appendices


Next: , Previous: Top, Up: Top

1 Overview of the library

This container library may be thought of as “low level”. Methods are provided to handle collected data, but no container can be used without wrapping it in a module whose functions “know” how to deal with the type of collected data.

Useless Containers Library installs the single header file ucl.h. All the function names in the API are prefixed with ucl_; all the constant names are prefixed with UCL_; all the type names are prefixed with ucl_ and suffixed with _t.

There is no error reporting system: it is our responsibility to validate function's arguments using the appropriate UCL functions. With the single exception of the vector module: UCL does no memory allocation.

The library is developed and tested under the GNU+Linux system and officially it supports only the GNU infrastructure: requires the GNU C library and compiles fine with the GNU C compiler (-std=c99 -pedantic switches).

The library makes use of inline functions and it is designed to be used only by C libraries and programs; it is probably impossible to interface it with other languages, unless through a C language wrapper library.


Next: , Up: overview

1.1 Linking code with the library

This package installs a data file for pkg-config, so when searching for the installed library with the GNU Autotools, we can:

Alternatively we can use the raw GNU Autoconf macros:

     AC_CHECK_LIB([ucl],[cct_version_string],,
       [AC_MSG_FAILURE([test for UCL library failed])])
     AC_CHECK_HEADERS([ucl.h],,
       [AC_MSG_FAILURE([test for UCL header failed])])


Next: , Previous: overview linking, Up: overview

1.2 Error handling

The design of methods tries to be the one that maximises the number of functions that cannot fail. This sometimes leads to “strange” or “dangerous” methods: functions that will cause the application to crash if an argument is incorrect. But, in these cases, the library provides a function to test the argument separately: to assert the precondition.

For example: if a vector index is out of range, we have to make sure not to hand it to an insertion/extraction method; we have to test it first and make use of it only if the test result is good.


Next: , Previous: overview error, Up: overview

1.3 Structures size

Under the examples directory of the source tree there is a small program that links to the library and prints the size of the UCL data structures; it can be built and run with the examples makefile rule. On a i686-pc-linux-gnu the output is:

     Size of common data types:
     
     char            1 :)
     void *          4
     int             4
     short int       2
     long int        4
     long long       8
     float           4
     double          8
     long double     12
     size_t          4
     ptrdiff_t       4
     ucl_value_t     4
     
     Limits:
     
     short int (SHRT_MIN, SHRT_MAX)  -32768 32767
     integer (INT_MIN, INT_MAX)      -2147483648 2147483647
     unsigned short int (USHRT_MAX)  65535
     unsigned (UINT_MAX)             4294967295
     
     Size of UCL structures:
     
     ucl_circular_t       16
     ucl_hash_table_t     36
     ucl_heap_t           32
     ucl_iterator_t       20
     ucl_map_t            28
     ucl_vector_t         48
     
     Size of UCL link structures:
     
     ucl_node_tag_t       16
     ucl_graph_node_tag_t 24
     ucl_graph_link_tag_t 28


Previous: overview size, Up: overview

1.4 Constification

This library has the need to write functions, conceptually, like this one:

     void data_type_t *
     the_function (data_type_t * p)
     {
       return p;
     }

that is: functions that do not modify the arguments, but whose return value must be modifiable. To write them like this:

     void data_type_t *
     the_function (const data_type_t * p)
     {
       return p;
     }

would be useful because:

  1. it makes clear to the user that the data referenced by p is not modified;
  2. causes the compiler to raise an error if we attempt to modify the data;

but a warning is issued because the return statement discards the const qualifier.

The adopted solution is to avoid the -Wcast-qual flag of the GNU C compiler, which is responsible to issue a warning if we discard a qualifier with a cast; so the following implementation does not raise warnings:

     void data_type_t *
     the_function (const data_type_t * p)
     {
       return (data_type_t *)p;
     }

It is not beautiful. But the ugliness is only in the UCL code, the user does not see it.


Next: , Previous: overview, Up: Top

2 Version functions

The installed libraries follow version numbering as established by the GNU Autotools. For an explanation of interface numbers as managed by GNU Libtool See interface.

— Function: const char * ucl_version_string (void)

Return a pointer to a statically allocated ASCIIZ string representing the interface version number.

— Function: int ucl_version_interface_current (void)

Return an integer representing the library interface current number.

— Function: int ucl_version_interface_revision (void)

Return an integer representing the library interface current revision number.

— Function: int ucl_version_interface_age (void)

Return an integer representing the library interface current age.


Next: , Previous: version, Up: Top

3 Memory allocation

UCL tries to avoid as much as possible the responsibility to allocate and release memory. Dynamic structures based on trees or linked lists do not call any memory allocation function: the responsibility to allocate UCL data structures is delegated to the user's code.

This makes the library a little more complex to use, but it also makes the code simpler by reducing the error cases that have to be dealt with. Also, user's code can implement a custom allocator and feed memory blocks to UCL's functions. This behaviour can be leveraged to improve performance, because the UCL makes use of a lot of little data structures.

When needed: the library makes use of a default allocator that reverts to the standard malloc(), realloc() and free() functions.


Next: , Up: memory

3.1 Data types

The following API has two main purposes:

  1. to implement the classic alloc, realloc and free operations;
  2. to define an allocator data structure that is small enough to be used directly as function argument (that is: passed by value).
— Struct Typedef: ucl_memory_allocator_t

Type of the memory allocator. We may build structures of this type to select a memory allocation policy. Fields description follows.

void * data
Pointer to an allocator data structure holding the state of the allocator; it is used as first argument to the allocator function, it can be NULL.
ucl_memory_alloc_fun_t * alloc
Pointer to a function used to allocate/reallocate/free a memory block.

— Function Prototype: void ucl_memory_alloc_fun_t (void * data, void * pp, size_t dim)

Allocate, reallocate or free memory blocks.

data
The value of the data field in the allocator data structure.
pp
Internally cast to void **, it is a pointer to the variable that holds the pointer to handle.
dim
The dimension of the memory block. It is expressed in bytes for the UCL functions.

The protocol:

This function must work like malloc(), realloc() and free() with the fundamental difference that: in case of error it must not return. What it does instead of returning is not the business of UCL; the default allocator will terminate the process with an invocation to exit() with code EXIT_FAILURE. The UCL guarantees that an error allocating memory will not corrupt any container (so the alloc function can longjump() to somewhere in case of error).

Example of new memory block allocation:

     ucl_memory_allocator_t allocator;
     void * p = NULL;
     
     allocator.alloc(allocator.data, &p, 4096);

example of memory block reallocation:

     ucl_memory_allocator_t allocator;
     void * p = ...;
     
     allocator.alloc(allocator.data, &p, 4096);

example of memory release:

     ucl_memory_allocator_t allocator;
     void * p = ...;
     
     allocator.alloc(allocator.data, &p, 0);


Next: , Previous: memory typedefs, Up: memory

3.2 Public interface

— Variable: const ucl_memory_allocator_t ucl_memory_allocator

Predefined memory allocator. Selects ucl_memory_alloc() as allocation function.

— Function: void ucl_memory_alloc (void * data, void * q, size_t dim)

Allocate, reallocate or free a block of memory using the standard calloc(), realloc() and free() functions. data is ignored: it is perfectly correct to invoke this function with data set to NULL.

This function can be used as alloc function in a ucl_memory_allocator_t.

The implementation is:

          void
          ucl_memory_alloc (void * dummy, void * qq, size_t dim)
          {
            void **       pp = qq;
            void *        p;
            if (0 == dim) {
              if (NULL != *pp) {
                free(*pp);
                *pp = NULL;
              }
            } else {
              p = (NULL == *pp)? calloc(1, dim) : realloc(*pp, dim);
              if (NULL == p) {
                perror(strerror(errno));
                exit(EXIT_FAILURE);
              }
              *pp = p;
            }
          }
— Function: void * ucl_malloc (ucl_memory_allocator_t allocator, size_t dim)
— Function: void * ucl_realloc (ucl_memory_allocator_t allocator, void * p, size_t dim)
— Function: void ucl_free (ucl_memory_allocator_t allocator, void * p)

These functions implement the classic alloc, realloc and free operations using the selected allocator.


Next: , Previous: memory functions, Up: memory

3.3 Memory blocks

This module offers a set of functions to handle memory blocks; its purpose is to provide a small data structure (ucl_block_t) which can be used directly as argument to function and return value from function, instead of the couple: pointer to memory block, block length in bytes. All the functions are defined in the header ucl.h and declared as __inline__.

— Struct Typedef: ucl_block_t

The type of memory block; fields description follows:

size_t len
The number of bytes in the block; can be zero.
uint8_t * ptr
Pointer to the memory block or NULL.

To initialise a block to empty state do this:

          ucl_block_t     B = { .ptr = NULL, .len = 0 };

or this:

          ucl_block_t     B;
          ucl_block_reset(&B);
Memory allocation
— Function: ucl_block_t ucl_block_alloc (ucl_memory_allocator_t allocator, size_t dim)
— Function: ucl_block_t ucl_block_realloc (ucl_memory_allocator_t allocator, ucl_block_t block, size_t new_dim)

Allocate or reallocate a memory block using the allocator and return the resulting block.

— Function: void ucl_block_free (ucl_memory_allocator_t allocator, ucl_block_t block)

If the ptr field of block is not NULL: free the referenced memory block using allocator.

Setting
— Function: void ucl_block_set (ucl_block_t * block, void * ptr, size_t len)

Set the fields of the block structure.

— Function: void ucl_block_reset (ucl_block_t * block)

Reset to zero all the fields of the block.

Inspection
— Function: bool ucl_block_is_null (ucl_block_t block)

Return true if the ptr field of block is NULL.

Memory operations
— Function: void ucl_block_clean_memory (ucl_block_t block)

Reset to zero all the bytes in the memory block.

Block operations
— Function: void ucl_block_shift_x (ucl_block_t * block, ssize_t offset, size_t dim)

Shift the memory reference in block by offset slots each of dim bytes. offset can be zero, positive or negative.

— Function: ucl_block_t ucl_block_shift (ucl_block_t block, ssize_t offset, size_t dim)

Like ucl_block_shift_x(), but produce a new block.

— Function: ucl_block_t ucl_block_difference (ucl_block_t a, ucl_block_t b)

This function assumes that b is contiguous to or included in a; return a new block c referencing the first portion of a not in b.

                    c.len             b.len
            |.........................|.................|
          
          c.ptr                     b.ptr
            v                         v
            |-------------------------|---------------------|
            ^
          a.ptr
          
            |...............................................|
                                 a.len
          


Next: , Previous: memory blocks, Up: memory

3.4 Handling ASCII strings

This module offers a set of functions to handle ASCII coded, zero terminated strings; its purpose is to provide a small data structure (ucl_ascii_t) which can be used directly as argument to function and return value from function, instead of the couple: pointer to memory block, block length in bytes. All the functions are defined in the header ucl.h and declared as __inline__.

— Struct Typedef: ucl_ascii_t

The type of zero–terminated ASCII strings; fields description follows:

size_t len
The number of characters in the block; can be zero; it does not include the terminating null character.
char * ptr
Pointer to the memory block or NULL; the last char must be zero.

To initialise an ascii to empty state do this:

          ucl_ascii_t     A = { .ptr = NULL, .len = 0 };

or this:

          ucl_ascii_t     A;
          ucl_ascii_reset(&A);

or this:

          ucl_ascii_t     A = ucl_ascii_empty;
— Struct Typedef: ucl_ascii_list_t

Holds an array of char *. Fields:

size_t len
the number of strings;
char ** ptr
the array of pointers.

— Variable: const ucl_ascii_t ucl_ascii_empty

Represent an empty string. It is a statically allocated structure, referencing a zero–terminated empty string.

— Function: void ucl_ascii_set (ucl_ascii_t * ascii, void * ptr, size_t len)

Initialise the fields of a structure.

— Function: void ucl_ascii_reset (ucl_ascii_t * ascii)

Reset to zero the fields.

— Function: ucl_ascii_t ucl_ascii_const (char * string)

Build and return a structure initialised with string. The length is determined with the standard strlen() function.

— Function: bool ucl_ascii_is_null (ucl_ascii_t ascii)

Return true if the pointer field is set to NULL.

— Function: ucl_bool_t ucl_ascii_is_terminated (ucl_ascii_t ascii)

Return true if the string referenced by ascii is zero–terminated.

— Function: void ucl_ascii_clean_memory (ucl_ascii_t ascii)

Reset the block of memory to zero bytes.

— Function: void ucl_ascii_terminate (ucl_ascii_t ascii)

Make sure that the string referenced by ascii is zero–terminated.

— Function: ucl_block_t ucl_block_from_ascii (ucl_ascii_t ascii)

Return a block initialised with the fields of an ASCII block.

— Function: ucl_ascii_t ucl_ascii_from_block (ucl_block_t block)

Return an ASCII block initialised with the fields of a block.

— Function: ucl_ascii_t ucl_ascii_alloc (ucl_memory_allocator_t allocator, size_t dim)
— Function: ucl_ascii_t ucl_ascii_realloc (ucl_memory_allocator_t allocator, ucl_ascii_t ascii, size_t new_dim)

Allocate or reallocate an ASCII block using allocator; dim and new_dim are the number of characters to be stored in the block, with the exclusion of the terminating zero.

— Function: void ucl_ascii_free (ucl_memory_allocator_t allocator, ucl_ascii_t ascii)

If the ptr field of ascii is not NULL: free the referenced memory block using allocator.


Previous: memory ascii, Up: memory

3.5 Miscellaneous macros

3.5.1 Structures

— Macro: ucl_struct_clean (struct_p, type)
— Macro: ucl_struct_reset (struct_p, type)

Reset to zero, using memset(), the structure of type pointed to by struct_p.

— Macro: ucl_struct_alloc (ucl_memory_allocator_t allocator, void * p, type)

Allocate a new structure of type using allocator and store a pointer to it in p. Example:

          typedef struct a_t {
            int      i;
          } a_t;
          
          a_t * p;
          
          ucl_struct_alloc(allocator, p, a_t);


Next: , Previous: memory, Up: Top

4 Data types you have to know

The types of container structures and links/nodes are described in the sections dedicated to containers. Here common data types are described.


Next: , Up: typedefs

4.1 Collected values and others

— Union Typedef: ucl_value_t

The data type of objects that can be stored in the containers; it's a union with the following members:

char t_char
unsigned char t_unsigned_char
int t_int
unsigned int t_unsigned_int
long t_long
unsigned long t_unsigned_long
int8_t t_int8
uint8_t t_uint8
int16_t t_int16
uint16_t t_uint16
int32_t t_int32
uint32_t t_uint32
One field for each built in C language type.
size_t t_size
ssize_t t_ssize
intptr_t t_intptr
uintptr_t t_uintptr
Fields for miscellaneous types.
void * ptr
void * pointer
uint8_t * bytes
char * chars
Fields for miscellaneous pointer types.

— Variable: const ucl_value_t ucl_value_null

Constant value representing the null ucl_value_t; its fields are set to zero.

— Alias Typedef: ucl_bool_t

Alias for _Bool, which is defined by the C99 standard. The standard defines also the true and false values (in the stdbool.h header).

— Alias Typedef: ucl_index_t

Alias for size_t.

— Struct Typedef: ucl_array_of_pointers_t

Array of pointers. Public fields:

void ** slots
pointer to an array of pointers: void *; this type implies no assumption upon the origin of the array memory, it can be statically or dynamically allocated, or it can be on the stack;
size_t number_of_slots
the number of elements in slots;
ucl_value_t data;
custom value that can be used to store a context associated to the array; this field is useful when we need to hand a pointer to an array to some function like a callback.

Temporary linked lists

Let's say that we want to preallocate a set of structures to be used with the UCL, for example: ucl_list_link_t, the structure representing a node in the UCL's doubly linked list. We allocate them with code like:

     #define NUMBER_OF_PREALLOCATED_STRUCTS          4096
     ucl_memory_allocator    allocator;
     ucl_list_link_t *       link_p;
     
     for (size_t i=0; i<NUMBER_OF_PREALLOCATED_STRUCTS; ++i) {
       link_p = NULL;
       allocator.alloc(allocator.data, &link_p, sizeof(ucl_list_link_t));
       /* here we have to put the links somewhere */
     }

it can be convenient to put the links in a linked list and extract them at usage time. We do not want to use the ucl_list_t container, because it is overkill for this application, so we can use the following special type.

— Struct Typedef: ucl_link_t

A structure with a single field, ucl_link_t * next_p, to be used to collect structures in a linked list.

With it the preallocation code looks like this:

     #define NUMBER_OF_PREALLOCATED_STRUCTS          4096
     ucl_memory_allocator    allocator;
     ucl_link_t *            link_list_p = NULL;
     
     
     {
       ucl_link_t *          link_p;
     
     
       for (size_t i=0; i<NUMBER_OF_PREALLOCATED_STRUCTS; ++i)
         {
           link_p = NULL;
           allocator.alloc(allocator.data, &link_p, sizeof(ucl_list_link_t));
           if (link_list_p)
             {
               link_p->next_p = link_list_p;
               link_list_p    = link_p;
             }
           else
             {
               link_list_p = link_p;
               link_list_p->next_p = NULL; /* just to be sure */
             }
         }
     }

to extract the links we do:

     ucl_link_t *            link_p;
     ucl_link_t *            link_list_p;
     ucl_list_link_t *       list_link_p;
     
     ...
     
     if (link_list_p)
       {
         link_p = link_list_p;
         link_list_p = link_p->next_p;
         list_link_p = (ucl_list_link_t *)link_p;
         /* here we can use 'list_link_p' */
       }
     else
       {
         /* no more preallocated links */
       }

and to put them back:

     ucl_link_t *            link_p;
     ucl_link_t *            link_list_p;
     
     ...
     
     if (link_list_p)
       {
         link_p->next_p = link_list_p;
         link_list_p    = link_p;
       }
     else
       {
         link_list_p = link_p;
         link_list_p->next_p = NULL;
       }

With better memory allocation:

     #define NUMBER_OF_PREALLOCATED_STRUCTS          4096
     #define SIZE_OF_PREALLOCATED_MEMORY             \
       (NUMBER_OF_PREALLOCATED_STRUCTS * sizeof(ucl_list_link_t))
     
     ucl_memory_allocator    allocator;
     void *                  preallocated_links = NULL;
     ucl_link_t *            link_list_p;
     
     
     /* let's assume that this allocator initialises the
        block to zero bytes */
     allocator.alloc(allocator.data, &preallocated_links,
                     SIZE_OF_PREALLOCATED_MEMORY);
     
     {
       ucl_link_t *          link_p;
     
     
       link_p = link_list_p = preallocated_links;
       for (size_t i=0; i<NUMBER_OF_PREALLOCATED_STRUCTS-1; ++i)
         {
           link_p->next_p = link_p + sizeof(ucl_list_link_t);
           link_p = link_p->next_p;
         }
     }


Next: , Previous: typedefs value, Up: typedefs

4.2 Range selectors

RANGES ARE INCLUSIVE

All these macros accept as range arguments the name of a range structure, not the name of a pointer to the structure. Range stuff is written in macros, not __inline__ functions, so that they work with all the type structures defined below.

— Struct Typedef: ucl_range_t

Data type used to describe a range of elements in a sequence, by selecting the indexes. The fields are of type size_t.

— Struct Typedef: ucl_char_range_t
— Struct Typedef: ucl_unsigned_char_range_t
— Struct Typedef: ucl_int_range_t
— Struct Typedef: ucl_unsigned_range_t
— Struct Typedef: ucl_long_range_t
— Struct Typedef: ucl_unsigned_long_range_t
— Struct Typedef: ucl_size_t_range_t
— Struct Typedef: ucl_float_range_t
— Struct Typedef: ucl_double_range_t
— Struct Typedef: ucl_byte_pointer_range_t
— Struct Typedef: ucl_pointer_range_t

Ranges of values.

— Macro: ucl_range_set_min_max (range, min, max)

Initialise the min and max fields.

— Macro: ucl_range_set_min_size (range, min, size)

Initialise the min and sets the max to: min+size-1.

— Macro: ucl_range_set_max_size (range, max, size)

Initialise the max and sets the min to: max-size+1.

— Macro: ucl_range_set_size_on_min (range, size)

Set the max to: min+size-1.

— Macro: ucl_range_set_size_on_max (range, size)

Set the min to: max-size+1.

— Macro: ucl_range_size (range)

Evaluate to the size of the range.

— Macro: ucl_range_is_empty (range)

Evaluate to true if range is empty.

— Macro: ucl_range_min (range)

Evaluate to the min.

— Macro: ucl_range_max (range)

Evaluate to the max.

— Macro: ucl_range_value_is_in (range, value)

Evaluate to true if the value is inside the range.

— Macro: ucl_range_value_is_out (range, value)

Evaluate to true if the value is outside the range.

— Macro: ucl_range_equal (range_a, range_b)

Evaluate to true if the ranges are equal.


Next: , Previous: typedefs ranges, Up: typedefs

4.3 Comparison functions

— Struct Typedef: ucl_comparison_t

Structure holding a policy for values comparison. Fields:

ucl_value_t data
context to be used as first argument to the function;
ucl_comparison_fun_t * func
pointer to the function that compares two values of type ucl_value_t.

— Function Typedef: int ucl_comparison_fun_t (ucl_value_t data, ucl_value_t a, ucl_value_t b)

The type of functions used to compare values. Functions of this type are used by the associative containers.

The behaviour of the function must be the one of the standard function strcmp(): return -1 if a<b, return 0 if a==b, return 1 if a>b.

The function has the responsibility to provide the comparison policy: to select a field in the ucl_value_t unions and establish when a value is formally greater than the other.

Example:

     ucl_comparison_fun_t    intcmp;
     ucl_comparison_t        compar = {
       .data = NULL, .func = intcmp
     };
     ucl_value_t             a = ...;
     ucl_value_t             b = ...;
     int                     result;
     
     result = compar.func(compar.data, a, b);


Next: , Previous: typedefs compar, Up: typedefs

4.4 Hash functions

— Struct Typedef: ucl_hash_t

Structure holding the hash function and its context. Fields:

ucl_value_t data
a context to be used as first argument to the function;
ucl_hash_fun_t * func
pointer to the function that computes the hash value.

— Function Typedef: ucl_index_t ucl_hash_fun_t (ucl_value_t data, ucl_value_t key)

Type of hash functions used by the hash table. The return value must be the “position” of the key in a vector. hash for details.


Next: , Previous: typedefs hash, Up: typedefs

4.5 Callback functions

— Struct Typedef: ucl_callback_t

Holds a function pointer and a context value. Public fields:

ucl_callback_fun_t * func
pointer to the callback function;
ucl_value_t data
the context value.

To initialise a ucl_callback_t structure we can do:

          ucl_callback_t cb = {
            .func = pointer_to_function,
            .data = { .ptr = pointer_to_data }
          };

to initialise to no–function and no–data:

          ucl_callback_t cb = ucl_callback_null;

Example of callback invocation:

          ucl_callback_t  cb = ...;
          int             a  = 123;
          int             b  = 456;
          
          ucl_callback_apply(cb, a, b);
— Variable: const ucl_callback_t ucl_callback_null

Statically allocated structure representing a null callback.

— Function Prototype: ucl_value_t ucl_callback_fun_t (ucl_value_t context, va_list ap)

Callback function. context is the value stored in the callback structure, representing the callback context. ap is the list of arguments: it is responsibility of the function to know how to interpret them.

— Inline Function: ucl_bool_t ucl_callback_is_present (ucl_callback_t cb)

Return true if the func field of cb is not NULL.

— Function: ucl_value_t ucl_callback_apply (ucl_callback_t cb, ...)

If ucl_callback_is_present() applied to cb evaluates to true: invoke the callback function using the callback context as first argument and a va_list as second argument; the va_list will hold references to the arguments to this function. Return the return value of the callback function.

If the callback function is not present nothing happens and the return value is a ucl_value_t with all the bytes set to zero.

— Function: ucl_value_t ucl_callback_eval_thunk (ucl_callback_t cb)

Like ucl_callback_invoke() but the va_list argument is replaced by NULL. Return the return value of the callback function.

Custom callback application

The UCL does not support any error reporting mechanism; this means that ucl_callback_apply() does not expect the callback to fail. To avoid problems all the UCL modules that need to apply a callback to arguments, do so by invoking a customisable function and are written in such a way that if the callback raises an exception nothing bad happens. The following API handles this.

— Function Prototype: ucl_value_t ucl_callback_apply_fun_t (ucl_callback_t callback, ...)

The prototype of functions that apply a callback to a list of arguments. ucl_callback_apply() has this prototype.

— Function: void ucl_callback_set_application_function (ucl_callback_apply_fun_t * f)

Register in UCL a new function for the application of callbacks to arguments; it will be used by all the UCL functions that invoke a callback. The default application function is ucl_callback_apply().


Previous: typedefs callback, Up: typedefs

4.6 Wrapping node structures

— Function Prototype: ucl_value_t ucl_node_getkey_fun_t (ucl_value_t context, void * node)

Type of function which, applied to a pointer to node, returns the key (or a reference to the key) associated to the node.

— Struct Typedef: ucl_node_getkey_t

Structure holding the method used to extract the key from a node. It has the following fields:

ucl_value_t data
Custom data value.
ucl_node_getkey_fun_t * func
Pointer to the function used to extract the key.

The following is a usage example:

     typedef struct link_tag_t {
       ucl_node_tag_t        node;
       ucl_value_t           key;
     } link_tag_t;
     
     typedef link_tag_t *        link_t;
     
     static ucl_value_t
     link_key (ucl_value_t context UCL_UNUSED, void * L_)
     {
       link_t    L = L_;
       return L->key;
     }
     
     static const ucl_node_getkey_t getkey = {
       .data = { .pointer = NULL },
       .func = link_key
     };

we can use the key extractor directly like this:

     link_t          L;
     ucl_value_t     K;
     
     K = getkey.func(getkey.data, L);


Next: , Previous: typedefs, Up: Top

5 The data structures


Next: , Up: containers

5.1 The binary tree container


Next: , Up: btree

5.1.1 Implementation and type definitions

This section presents an implementation of binary tree; the container is a chain of structures:

       ------  bro   ------
      | node |----->| node |
      |   1  |<-----|   2  |
       ------  dad   ------
        | ^
     son| |dad
        v |
       ------
      | node |
      |   3  |
       ------

each node data structure is a collection of pointers and of metadata fields whose usage is reserved by UCL; there's no data field.

— Struct Typedef: ucl_node_tag_t
— Pointer Typedef: ucl_node_t

The data type of the node structure and of the pointer to the node structure; nodes must be allocated and freed by client code. Public fields:

ucl_node_t dad
pointer to the parent of this node; NULL if this node has no parent;
ucl_node_t son
pointer to the son of this node; NULL if this node has no son;
ucl_node_t bro
pointer to the bro of this node; NULL if this node has no bro.

— Macro: UCL_NODE_SIZE

The size in bytes of the structure ucl_node_tag_t.


Next: , Previous: btree typedefs, Up: btree

5.1.2 Usage examples

Let's say we want to organise a set of characters in a binary tree; we define the tree node type and allocation functions like these:

     typedef struct node_tag_t {
       ucl_node_tag_t  node;
       char            c;
     } node_tag_t;
     
     typedef node_tag_t *    node_t;
     
     ucl_memory_allocator_t  A = {
       .data  = NULL,
       .alloc = ucl_memory_alloc
     };
     
     node_t
     node_make (char c)
     {
       node_t        p = NULL;
     
       A.alloc(A.data, &p, sizeof(node_tag_t));
       p->c = c;
       return p;
     }
     void
     node_final (node_t p)
     {
       A.alloc(A.data, &p, 0);
     }
     __inline__ void
     node_clean (node_t p)
     {
       ucl_struct_clean(p, node_tag_t);
     }

and we remember that the built in UCL allocation function (ucl_memory_alloc()) sets to zero all the bytes of newly allocated blocks.

We define the getter/setter functions in “generic” form, like these:

     __inline__ void
     node_set (node_t p, void * data)
     {
       p->c = *((char *)data);
     }
     __inline__ void *
     node_get (node_t p)
     {
       return &(p->c);
     }

Now if we want the following hierarchy:

            ---  bro  ---
           | a |---->| c |
            ---       ---
             |         |
         son v     son v
            ---       ---
           | b |     | d |
            ---       ---

we do it like this, taking advantage of the fact that the binary tree functions accept void * values as arguments:

     node_t  a, b, c, d;
     
     a = node_make('a');
     b = node_make('b');
     c = node_make('c');
     d = node_make('d');
     
     ucl_btree_dadson(a, b);
     ucl_btree_dadbro(a, c);
     ucl_btree_dadson(c, d);

the following expressions are true:

     NULL == ucl_btree_getdad(a)
     a    == ucl_btree_getdad(b)
     a    == ucl_btree_getdad(c)
     c    == ucl_btree_getdad(d)
     
     c    == ucl_btree_getbro(a)
     NULL == ucl_btree_getbro(b)
     NULL == ucl_btree_getbro(c)
     NULL == ucl_btree_getbro(d)
     
     b    == ucl_btree_getson(a)
     NULL == ucl_btree_getson(b)
     d    == ucl_btree_getson(c)
     NULL == ucl_btree_getson(d)


Next: , Previous: btree examples, Up: btree

5.1.3 Building btrees hierarchies

The correct way of building binary trees is to allocate node structures with a function that cleans them up, like calloc(), then use the following functions to initialise the fields. If a structure is recycled, we must reset its fields to zero first.

All the following functions accept void * values as arguments: internally these pointers are cast to ucl_node_t.

Single link setters
— Inline Function: void ucl_btree_set_dad (void * self, void * dad)

Select a new parent node for self.

— Inline Function: void ucl_btree_set_bro (void * self, void * bro)

Select a new brother node for self.

— Inline Function: void ucl_btree_set_son (void * self, void * son)

Select a new child node for self.

Double link setters
— Inline Function: void ucl_btree_set_dadson (void * dad, void * son)

Link dad and son to be the parent and the son respectively.

— Inline Function: void ucl_btree_set_dadbro (void * dad, void * bro)

Link dad and bro to be the parent and the bro respectively.

Triple link setters
— Inline Function: void ucl_btree_set_dadsonbro (void * dad, void * son, void * bro)

Link dad, son and bro to be the parent, the son and the bro respectively.


Next: , Previous: btree creation, Up: btree

5.1.4 Accessing nodes

All the following functions accept void * values as arguments and return void * values; internally these pointers are cast to ucl_node_t.

— Inline Function: void * ucl_btree_ref_dad (void * self)

Return a pointer to the parent of self or NULL if the node has no parent.

— Inline Function: void * ucl_btree_ref_bro (void * self)

Return a pointer to the brother of self or NULL if the node has no brother.

— Inline Function: void * ucl_btree_ref_son (void * self)

Return a pointer to the son of self or NULL if the node has no son.

— Inline Function: void * ucl_btree_data (void * self)

Assuming that the first field of the memory block referenced by self is a structure of type ucl_node_tag_t, return a pointer to the first byte after that structure. The returned pointer references the first byte of the data area of the tree node.

— Inline Function: ucl_bool_t ucl_btree_is_leaf (void * self)

Return true if the node is a leaf (no brother and no son).

— Inline Function: ucl_bool_t ucl_btree_is_root (void * self)

Return true if the node is the root of a binary tree: it has no dad.

— Function: int ucl_btree_depth (void * N)

Function with recursive implementation which computes the depth of the tree having N as root, N included. Return zero if N is NULL.


Next: , Previous: btree inspection, Up: btree

5.1.5 Removing elements

It's a matter of setting pointers to NULL; care must be taken not to loose references to subtrees.

All the following functions accept void * values as arguments and return void * values; internally these pointers are cast to ucl_node_t.

— Inline Function: void * ucl_btree_detach_son (void * self)

Detach the son of self and return a pointer to it. The two nodes hold references to each other no more.

— Inline Function: void * ucl_btree_detach_bro (void * self)

Detach the bro of self and return a pointer to it. The two nodes hold references to each other no more.

— Inline Function: void * ucl_btree_detach_dad (void * self)

Detach the dad of self and return a pointer to it. The two nodes hold references to each other no more.

— Function: void ucl_btree_clean (void * self)

Set to zero all the bytes in the node structure.


Next: , Previous: btree removing, Up: btree

5.1.6 Finding values

The purpose of a binary tree is to organise values in a hierarchy; the functions described in this section can be used to find values.

The following function accepts void * values as arguments and return a void * value; internally these pointers are cast to ucl_node_t.

— Function: void * ucl_btree_find_value (void * root, ucl_value_t value, ucl_comparison_t compar)

Interpret root as a pointer to the root node of a btree (whose dad is NULL) and find a node equal to value according to the comparison closure. compar is invoked like this:

          ucl_node_t  N = ...;
          ucl_value_t D = { .pointer = N };
          
          compar.func(compar.data, value, D);

where N is the current node in the search; if the return value is:

zero
the node is returned;
negative
the search goes on in the son subtree;
positive
the search goes on in the bro subtree;

if value is not found, the return value is NULL.


Next: , Previous: btree find, Up: btree

5.1.7 Swapping nodes

The following function accepts void * values as arguments and return a void * value; internally these pointers are cast to ucl_node_t.

— Function: void ucl_btree_swap_out (void * A, void * B)

Given two pointers to nodes: interpret A as pointer to a node in a tree and B as pointer to a node out of any tree; store the links and meta value of A into B, then resets the links and meta value of A.

— Function: void ucl_btree_swap (void * A, void * B)

Given two pointers to nodes: swap the links and the meta value in the node structures. Take care of the fact that A and B may reference each other.

— Function: void ucl_btree_swap_no_meta (void * A, void * B)

Given two pointers to nodes: swap the links but not the meta value in the node structures. Take care of the fact that A and B may reference each other.


Next: , Previous: btree swap, Up: btree

5.1.8 Finding nodes

All the following functions accept void * values as arguments and return void * values; internally these pointers are cast to ucl_node_t.

— Function: void * ucl_btree_find_leftmost (void * self)

Find the leftmost node in the subtree of the supplied node. To do this, we traverse the tree choosing always the son of the current node.

Example:

                5-------10----12
                |        |     |
                1--3--4  7--9 11
                   |     |  |
                   2     6  8

starting from 5 the selected node is 1, starting from 10 the selected node is 6.

Return a pointer to the leftmost node in the self sub–hierarchy or to self itself if it has no son.

— Function: void * ucl_btree_find_rightmost (void * self)

Find the rightmost node in the subtree of the supplied node. To do this, we traverse the tree choosing always the brother of the current node.

Example:

                5-------10----12
                |        |     |
                1--3--4  7--9 11
                   |     |  |
                   2     6  8

starting from 5 the selected node is 12, starting from 7 the selected node is 9.

Return a pointer to the rightmost node in the self sub–hierarchy or to self itself if it has no brother.

— Function: void * ucl_btree_find_deepest_son (void * self)

Find the deepest leftmost son in a subtree. This is different from ucl_btree_find_leftmost().

Example:

                5-------10----12
                |        |     |
                1--3--4  7--9 11
                   |     |  |
                   2     6  8

starting from 5 the selected node is 2, starting from 10 the selected node is 6.

Return a pointer to the deepest son in the self sub–hierarchy, or self itself if it has no son.

— Function: void * ucl_btree_find_deepest_bro (void * self)

Find the deepest rightmost bro in a subtree. This is different from ucl_btree_find_rightmost().

Example:

                5-------10----12
                |        |     |
                1--3--4  7--9 11
                   |     |  |
                   2     6  8

starting from 5 the selected node is 11, starting from 1 the selected node is 4.

Return a pointer to the deepest bro in the self sub–hierarchy, or self itself if it has no son.

— Function: void * ucl_btree_find_root (void * node)

Step up the hierarchy, dad by dad, and return a pointer to a node that has NULL as dad.


Next: , Previous: btree visitors, Up: btree

5.1.9 Iterations in a btree hierarchy


Next: , Up: btree iteration
5.1.9.1 Inorder iteration

Forward inorder iteration: visit all the nodes from the leftmost to the rightmost. Backward inorder iteration: visit all the nodes from the rightmost to the leftmost. Example: given the tree:

     5-------10----12
     |        |     |
     1--3--4  7--9 11
        |     |  |
        2     6  8

the inorder iteration is:

     forward:   1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12
     backward: 12, 11, 10,  9,  8,  7,  6,  5,  4,  3,  2,  1

All the following functions accept void * values as arguments and return void * values; internally these pointers are cast to ucl_node_t.

— Inline Function: void * ucl_btree_first_inorder (void * root)
— Inline Function: void * ucl_btree_first_inorder_backward (void * root)

Given a pointer to the root node of a tree, return the first node of an inorder iteration. For the forward iteration: it is the leftmost node; for the backward iteration: it is the rightmost node.

— Function: void * ucl_btree_step_inorder (void * current)
— Function: void * ucl_btree_step_inorder_backward (void * current)

Advance an inorder iteration. Given a pointer to a node in a tree: perform a single step and return a pointer to the next node, or NULL if the iteration is over.

— Function: void ucl_btree_iterator_inorder (ucl_iterator_t iter, void * root)
— Function: void ucl_btree_iterator_inorder_backward (ucl_iterator_t iter, void * root)

Initialise a whole tree iterator; root must be the root node of a btree.

— Function: void ucl_btree_subtree_iterator_inorder (ucl_iterator_t iter, void * node)
— Function: void ucl_btree_subtree_iterator_inorder_backward (ucl_iterator_t iter, void * node)

Initialise a subtree iterator; node must be the a node of a btree, and will be used as root node of the subtree.

— Function: void ucl_btree_range_iterator_inorder (ucl_iterator_t iter, ucl_pointer_range_t range)
— Function: void ucl_btree_range_iterator_inorder_backward (ucl_iterator_t iter, ucl_pointer_range_t range)

Initialise a range iterator over the range of nodes selected by range (remember that ranges are inclusive); the minimum field of range is interpreted as the starting node of the iteration, while the maximum field of range is interpreted as the ending node of the iteration.

Examples of forward iteration

To perform a complete forward inorder iteration, we have to start from the leftmost node (0 in the picture above), already visited, and begin from there. Example:

     ucl_node_t   cur = get_the_top_node();
     
     for (cur = ucl_btree_find_leftmost(cur);
          cur;
          cur = ucl_btree_step_inorder(cur));
       {
         do_something_with(cur);
       }

To restrict the iteration to a subtree of a tree or to a range of nodes in a tree, we have to select the first and last nodes and check when the iterator reaches the last.

Example of subtree restriction: does an inorder iteration from the top of a subtree to the rightmost node in the subtree:

     ucl_node_t        cur, end;
     
     cur = get_a_node(...);
     end = ucl_btree_find_rightmost(cur);
     
     for (cur = ucl_btree_find_leftmost(cur);
          cur != end;
          cur = ucl_btree_step_inorder(cur))
       {
         do_something_with(cur);
       }
     
     /* Here "cur == end" and we visit it. */
     do_something_with(cur);

cur can't be NULL because end is in the subtree of the top node; this code will work even when cur == end at the beginning.

Example of range restriction: does an iteration starting from a node (not the leftmost) to the rightmost one:

     ucl_node_t        root, cur, end;
     
     root	= get_a_node();
     end	= ucl_btree_find_rightmost(root);
     
     for (cur = select_first(root, ...);
          cur != end;
          cur = ucl_btree_step_inorder(cur))
       {
         do_something_with(cur);
       }

cur can't be NULL because we selected the first and last nodes in a subtree; this code will work even when root == cur == end at the beginning.

Examples of backward iteration

To perform a complete backward iteration, we have to start from the rightmost node (12 in the picture above), already visited, and begin from there. Example:

     ucl_node_t   cur = get_the_top_node();
     
     for (cur = ucl_btree_find_rightmost(cur);
          cur;
          cur = ucl_btree_step_inorder_backward(cur))
       {
         do_something_with(cur);
       }

To restrict the iteration to a subtree of a tree or to a range of nodes in a tree, we have to select the first and last nodes and check when the iterator reaches the last.

Example of subtree restriction: does an iteration from the rightmost to the leftmost nodes in a subtree:

     ucl_node_t        cur, end;
     
     cur = get_a_node(...);
     end = ucl_btree_find_leftmost(cur);
     
     for (cur = ucl_btree_find_rightmost(cur);
          cur != end;
          cur = ucl_btree_step_inorder_backward(cur))
       {
         do_something_with(cur);
       }
     
     /* Here "cur == end" and we visit it. */
     do_something_with(cur);

cur can't be NULL because end is in the subtree of the top node; this code will work even when cur == end at the beginning.

Example of range restriction:

     ucl_node_t        root, cur, end;
     
     root	= get_a_node();
     end	= ucl_btree_find_leftmost(root);
     
     for (cur = select_first(root, ...);
          cur != end;
          cur = ucl_btree_step_inorder_backward(cur))
       {
         do_something_with(cur);
       }
     
     /* Here "cur == end" and we visit it. */
     do_something_with(cur);

cur can't be NULL since we selected the first and last nodes in a subtree; this code will work even when root == cur == end a the beginning.


Next: , Previous: btree inorder iteration, Up: btree iteration
5.1.9.2 Preorder iteration

Preorder iteration: visit the current node then the son then the brother. Example:

     5-------10----12
     |        |     |
     1--3--4  7--9 11
        |     |  |
        2     6  8

the preorder iteration is:

     forward:    5,  1,  3,  2,  4, 10,  7,  6,  9,  8, 12, 11
     backward:   5, 10, 12, 11,  7,  9,  8,  6,  1,  3,  4,  2

the forward iteration is a “worm that always turns right”, while the backward iteration is a “worm that always turns left”.

All the following functions accept void * values as arguments and return void * values; internally these pointers are cast to ucl_node_t.

— Inline Function: void * ucl_btree_first_preorder (void * root)
— Inline Function: void * ucl_btree_first_preorder_backward (void * root)

Given a pointer to the root node of a tree, return the first node of a preorder iteration. For both the forward and backward iterations: it is the root node itself.

— Function: void * ucl_btree_step_preorder (void * current)
— Function: void * ucl_btree_step_preorder_backward (void * current)

Advance a preorder iteration. Given a node in a btree: perform a single step and return a pointer to the next node, or NULL if the iteration is over.

— Function: void ucl_btree_iterator_preorder (ucl_iterator_t iter, void * root)
— Function: void ucl_btree_iterator_preorder_backward (ucl_iterator_t iter, void * root)

Initialise a whole tree iterator; root must be the root node of a btree.

— Function: void ucl_btree_subtree_iterator_preorder (ucl_iterator_t iter, void * node)
— Function: void ucl_btree_subtree_iterator_preorder_backward (ucl_iterator_t iter, void * node)

Initialise a subtree iterator; node must be the a node of a btree, and will be used as root node of the subtree.

— Function: void ucl_btree_range_iterator_preorder (ucl_iterator_t iter, ucl_pointer_range_t range)
— Function: void ucl_btree_range_iterator_preorder_backward (ucl_iterator_t iter, ucl_pointer_range_t range)

Initialise a range iterator over the range of nodes selected by range (remember that ranges are inclusive); the minimum field of range is interpreted as the starting node of the iteration, while the maximum field of range is interpreted as the ending node of the iteration.

Examples of forward iteration

To perform a complete iteration, we have to start from the top node of the tree (5 in the picture above), already visited, and begin from there. Example:

     ucl_node_t        cur;
     
     for (cur = select_the_top_node();
          cur;
          cur = ucl_btree_step_pre(cur))
       {
         do_something_with(cur);
       }

this works because the top node of a btree has a NULL value in the dad pointer field.

To restrict the iteration to a subtree of a tree: we cannot loop until the function returns NULL, because the top node of a subtree has a non–NULL value in the dad pointer field. With reference to the picture above: we select the top node (number 10) and we visit it; then we step to the next (number 7) and visit it; then we enter the loop until the iterator reaches the top node (number 10 again).

Example:

     ucl_node_t        cur, end;
     
     end = cur = get_a_node();
     
     do_something_with(cur);
     for (cur = ucl_btree_step_preorder(cur);
          cur != end;
          cur = ucl_btree_step_preorder(cur))
       {
         do_something_with(cur);
       }


Next: , Previous: btree preorder iteration, Up: btree iteration
5.1.9.3 Postorder iteration

Postorder iteration: visit the son, then the brother, then the parent node. Example:

     5-------10----12
     |        |     |
     1--3--4  7--9 11
        |     |  |
        2     6  8

the postorder iteration is:

     forward:    2,  4,  3,  1,  6,  8,  9,  7, 11, 12, 10,  5
     backward:  11, 12,  8,  9,  6,  7, 10,  4,  2,  3,  1,  5

All the following functions accept void * values as arguments and return void * values; internally these pointers are cast to ucl_node_t.

— Inline Function: void * ucl_btree_first_postorder (void * root)
— Inline Function: void * ucl_btree_first_postorder_backward (void * root)

Given a pointer to the root node of a tree, return the first node of a postorder iteration. For the forward iteration: it is the deepest son found by ucl_btree_find_deepest_son(); for the backward iteration: it is the deepest bro found by ucl_btree_find_deepest_bro().

— Function: void * ucl_btree_step_postorder (void * current)
— Function: void * ucl_btree_step_postorder_backward (void * current)

Advance a forward postorder iteration. Given a node in a btree: perform a single step and return a pointer to the next node, or NULL if the iteration is over.

— Function: void ucl_btree_iterator_postorder (ucl_iterator_t iter, void * root)
— Function: void ucl_btree_iterator_postorder_backward (ucl_iterator_t iter, void * root)

Initialise a whole tree iterator; root must be the root node of a btree.

— Function: void ucl_btree_subtree_iterator_postorder (ucl_iterator_t iter, void * node)
— Function: void ucl_btree_subtree_iterator_postorder_backward (ucl_iterator_t iter, void * node)

Initialise a subtree iterator; node must be the a node of a btree, and will be used as root node of the subtree.

— Function: void ucl_btree_range_iterator_postorder (ucl_iterator_t iter, ucl_pointer_range_t range)
— Function: void ucl_btree_range_iterator_postorder_backward (ucl_iterator_t iter, ucl_pointer_range_t range)

Initialise a range iterator over the range of nodes selected by range (remember that ranges are inclusive); the minimum field of range is interpreted as the starting node of the iteration, while the maximum field of range is interpreted as the ending node of the iteration.

Examples of forward iteration

To perform a complete iteration, we have to select the deepest leftmost son in the tree (2 in the example) and begin from there. Example:

     ucl_node_t        cur;
     
     cur = get_a_node();
     for (cur = ucl_btree_find_deepest_son(cur);
          cur != NULL;
          cur = ucl_btree_step_postorder(cur));
       {
         do_something_with(cur);
       }

To restrict the iteration to a subtree of a tree, we have to check when the iterator reaches the top node. Example:

To restrict the iteration to a subtree of a tree: we cannot loop until the function returns NULL, because the top node of a subtree has a non–NULL value in the parent pointer field. With reference to the tree in the picture above: we select the top node (number 10); then we move to the deepest son (number 6) and we visit it; then we enter the loop until the iterator reaches the top node (number 10 again).

Example:

     ucl_node_t        cur, end;
     
     cur = end = get_a_node();
     
     for (cur = ucl_btree_find_deepest_son(cur);
          cur != end;
          cur = ucl_btree_step_postorder(cur));
       {
         do_something_with(cur);
       }
     
     /* Here "cur == end" and we visit it. */
     do_something_with(cur);

cur can't be null in the loop.


Previous: btree postorder iteration, Up: btree iteration
5.1.9.4 Breadth first iteration

Breadth first iteration: visit the tree level by level. Example:

     5-------10----12
     |        |     |
     1--3--4  7--9 11
        |     |  |
        2     6  8

the order of the forward iteration is: 5, 1, 10, 3, 7, 12, 2, 4, 6, 9, 11, 8. To do it we need a moving cursor that always “turns right” keeping the count of the level. The order of the backward iteration is: 5, 10, 1, 12, 7, 3, 11, 9, 6, 4, 2, 8.

All the following functions accept void * values as arguments and return void * values; internally these pointers are cast to ucl_node_t.

— Inline Function: void * ucl_btree_first_levelorder (void * root)
— Inline Function: void * ucl_btree_first_levelorder_backward (void * root)

Given a pointer to the root node of a tree, return the first node of a levelorder iteration. For both the forward and backward iterations: it is the root node itself.

— Function: void * ucl_btree_step_levelorder (void * self)
— Function: void * ucl_btree_step_levelorder_backward (void * self)

Advance a breadth first iteration. Given a node in the three: perform a single step and return a pointer to the next node, or NULL if the iteration is over.

— Function: void ucl_btree_iterator_levelorder (ucl_iterator_t iter, void * root)
— Function: void ucl_btree_iterator_levelorder_backward (ucl_iterator_t iter, void * root)

Initialise a whole tree iterator; root must be the root node of a btree.

Examples of forward iteration

To perform a complete iteration, we just call the function until it returns NULL. Example:

     ucl_node_t cur;
     
     for (cur = get_the_top_node();
          cur != NULL;
          cur = ucl_btree_step_levelorder(cur));
       {
         do_something_with(cur);
       }
Examples of backward iteration

To perform a complete iteration, we just call the function until it returns NULL. Example:

     ucl_node_t cur;
     
     for (cur = get_the_top_node();
          cur != NULL;
          cur = ucl_btree_step_levelorder_backward(cur));
       {
         do_something_with(cur);
       }


Next: , Previous: btree iteration, Up: btree

5.1.10 Routines for raw binary search trees

The following routines can be used in the implementation of raw binary search trees (BST); they are included in UCL only for completeness, because we should use balanced trees not raw ones.

All the following functions accept void * values as arguments and return values; internally these pointers are cast to ucl_node_t.

— Function: void ucl_bst_insert (void * top, void * new, ucl_comparison_t keycmp, ucl_node_getkey_t getkey)

Insert the node referenced by new in the binary search tree whose root is referenced by top; use keycmp to compare keys and getkey to extract a key from its node.

— Function: void * ucl_bst_find (void * top, ucl_value_t K, ucl_comparison_t keycmp, ucl_node_getkey_t getkey)

Find the node having key referenced by K in the binary search tree having root referenced by top; use keycmp to compare keys and getkey to extract a key from its node. Return a pointer to the first found node, or NULL if none was found.

— Function: void * ucl_bst_delete (void * root, void * cur)

Remove the node referenced by cur from the binary search tree whose root is root. Return the root node after the deletion, which may be root or not.


Previous: btree bst, Up: btree

5.1.11 Routines for AVL trees

The following routines are used in the implementation of the AVL binary search tree; they are not meant to be used directly. map for the UCL implementation of AVL search trees.

All the following functions accept void * values as arguments and return values; internally these pointers are cast to ucl_node_t.

The meta field of the ucl_node_tag_t structure is used to store an AVL status integer which is: -1 when the son subtree is higher than the bro subtree; +1 when the bro subtree is higher than the son subtree; 0 when the son subtree and the bro subtree have equal depth. In a balanced AVL tree the difference in depth between a son subtree and a bro subtree is always at most 1; so we can say that the AVL status is the bro's subtree depth minus the son's subtree depth, such difference is called balance factor.

— Function: void * ucl_btree_avl_rot_left (void * cur)

Perform a clockwise rotation (or son rotation or left rotation) which balances a son deeper subtree:

             cur      son
            /     =>    \
          son            cur

return a pointer to the node that has replaced cur in the tree, which is always the son of cur.

This function must be called only when ‘cur’ has balance factor -2 and ‘son’ has balance factor -1 or 0; these are the useful cases and also the cases for which computing the AVL statuses after the rotation is not costly.

Example with cur being ‘11’ and having son being son deeper (balance factors in parentheses):

               (top)                   (top)
                 |                       |
                11(-2)                   9(0)
               /  \                 -----+-----
           9(-1)   12              7          11(0)
             / \             =>   / \        /  \
            7   10               6   8     10    12
           / \
          6   8

Example with cur being 12 and having son being equal depth (balance factors in parentheses):

               (top)                      (top)
                 |                          |
                12(-2)                      9(+1)
               /  \                    -----+-----
             9(0)  13                 7          12(-1)
             / \              =>     / \         /  \
            7   10                  6   8      10    13
           / \    \                              \
          6   8    11                             11
— Function: void * ucl_btree_avl_rot_right (void * cur)

Perform a counterclockwise rotation (or right rotation or bro rotation) which balances a right–right–higher subtree:

          cur            bro
             \    =>    /
             bro      cur

return a pointer to the node that has replaced cur in the tree, which is always the bro of cur.

This function must be called only when ‘cur’ has balance factor +2 and its bro has balance factor +1 or 0; these are the useful cases and also the cases for which computing the AVL statuses after the rotation is not costly.

Example with cur being ‘7’ and having bro being bro deeper (balance factors in parentheses):

          (top)                              (top)
            |                                  |
            7(+2)                              9(0)
           / \                            -----+-----
          6   9(+1)         =>           7(0)        11
             / \                        / \         /  \
            8   11                     6   8      10    12
               /  \
             10    12

Example with cur being ‘6’ and having bro being equal depth (balance factors in parentheses):

          (top)                              (top)
            |                                  |
            6(+2)                              9(-1)
           / \                            -----+-----
          5   9(0)          =>           6(+1)       11
             / \                        / \         /  \
            8   11                     5=  8      10    12
           /   /  \                       /
          7  10    12                    7
— Function: void * ucl_btree_avl_rot_left_right (void * cur)

Perform a left/right rotation (or son/bro rotation) which balances a left–right–higher subtree:

             cur           son_bro
            /              /     \
          son        =>  son     cur
             \
            son_bro

it can be seen as the sequence of a counterclockwise rotation for ‘son’ and a clockwise rotation for ‘cur’:

             cur              cur        son_bro
            /                /           /     \
          son        =>    son     =>  son     cur
             \            /
            son_bro     son_bro

return a pointer to the node that has replaced cur in the tree, which is always the bro of the son of cur.

This function must be called only when ‘cur’ has balance factor -2 and ‘son’ has balance factor +1.

Example:

                   (top)                            (top)
                     |                                |
                    10 (old_cur)                      8 (new_cur)
                   /  \                     ----------+----------
            (son) 5    13            (son) 5          (old_cur) 10
                 / \              =>      / \                  /  \
                3   8 (new_cur)          3   7                9    13
                   / \                     (deep_son)  (deep_bro)
                  7   9
          (deep_son) (deep_bro)
— Function: void * ucl_btree_avl_rot_right_left (void * cur)

Perform a right/left rotation (or bro/son rotation) which balances a right–left–higher subtree:

          cur            bro_son
             \            /   \
             bro    =>  cur   bro
            /
           bro_son

it can be seen as the sequence of a clockwise rotation for ‘bro’ and a counterclockwise rotation for ‘cur’:

          cur           cur                  bro_son
             \             \                  /   \
             bro    =>    bro_son       =>  cur   bro
            /                \
           bro_son            bro

return a pointer to the node that has replaced cur in the tree, which is always the bro of the bro of cur.

This function must be called only when ‘cur’ has balance factor +2 and ‘son’ has balance factor -1.

Example:

                    (top)                           (top)
                      |                               |
            (old_cur) 9(+2)                          11 (0) (new_cur)
                     / \                    ----------+---------
                    8   13(-1) (bro)       9(0) (old_cur)       13(0) (bro)
                       /  \         =>    / \                  /  \
           (new_cur) 11    14            8   10              12    14
                    /  \                   (deep_son)  (deep_bro)
                  10    12
          (deep_son)    (deep_bro)
— Function: int ucl_btree_avl_depth (void * N)

Return the depth of the tree of which N is the root; if N is NULL the return value is zero. For this function to return the correct result: the tree must have nodes with correct status. This function is faster than ucl_btree_depth().

— Function: int ucl_btree_avl_factor (void * N)

Return the balance factor of N: the depth of the bro subtree minus the depth of the son subtree. If N is NULL the return value is zero.

— Function: ucl_bool_t ucl_btree_avl_is_balanced (void * N)

Return true if the tree of which N is the root is balanced; if N is NULL the return value is true. This function only checks that the left and right subtrees of each node have depth at most different by 1, it does not validate the AVL status of the nodes.

— Function: ucl_bool_t ucl_btree_avl_is_correct (void * N)

Return true if the tree of which N is the root is balanced and all the statuses are correct; if N is NULL the return value is true. This function checks that the left and right subtrees of each node have depth at most different by 1, and also verifies that the AVL status of each node is coherent with the difference between depths.


Next: , Previous: btree, Up: containers

5.2 The tree structure


Next: , Up: tree

5.2.1 How it's done

The implementation is a binary tree with nodes of type ucl_node_t; the only difference between the btree and the tree is the interpretation of the bro nodes. This means that all the functions in the btree module can be used on a tree, and the tree module adds functions to establish the interpretation policy.

In the following picture: the nodes B, C, D and E are all “children” of the node A; the node A is the father of the nodes B, C, D and E. So in a tree a node can have and indefinite number of children.

        -----
       |  A  |
        -----
         ^ |son
      dad| v
        -----  bro   -----  bro   -----  bro   -----  bro
       |  B  |----->|  C  |----->|  D  |----->|  E  |----->NULL
        ----- <----- ----- <----- ----- <----- -----
         ^ |   dad    ^ |   dad          dad
      dad| vson    dad| vson
        -----        -----
       |  F  |      |  G  |
        -----        -----

Pointers condition meaning:

node.dad == NULL
the node is the root node of a tree;
node.bro == NULL
the node has no brothers, so it's the last brother between the children of its father;
node.son == NULL
the node has no children;
A.dad == B && B.son == A
A is the first between the children of node B;
A.dad == B && B.bro == A
A and B are brothers, and children of the same parent node.


Next: , Previous: tree implementation, Up: tree

5.2.2 Creating a tree hierarchy

The node structures must be allocated by the client code and all the bytes set to zero before usage. The btree functions can be used directly, but UCL provides aliases for them when they must be used for a tree.

All the following functions accept void * values as arguments: internally these pointers are cast ucl_node_t.

Single link setters
— Function: void ucl_tree_set_next (void * node, void * next)

Mutate node so that next becomes the new right brother of node. The old reference to the right brother of node is lost.

— Function: void ucl_tree_set_prev (void * node, void * prev)

Mutate node so that prev becomes the new left brother of node. The old reference to the left brother of node is lost.

Double link setters
— Function: void ucl_tree_set_dadson (void * dad, void * son)

Mutate prev and next so that the two become left and right brothers. The old references to the left and right brothers are lost.

— Function: void ucl_tree_set_prevnext (void * prev, void * next)

Mutate prev and next so that the two become left and right brothers. The old references to the left and right brothers are lost.


Next: , Previous: tree creation, Up: tree

5.2.3 Inserting nodes into a tree

The following functions are used to insert subtrees in a tree. None of the nodes in the target tree are detached. The links in the new subtrees that are not interested by the relations in these functions, are left untouched.

All the following functions accept void * values as arguments: internally these pointers are cast ucl_node_t.

— Function: void ucl_tree_insert_dad (void * node, void * dad)

Inserts a new dad for a node. The dad node becomes the father of the node and the first son of the old dad (if any).

           ---       ---
          | A |     | A |
           ---       ---
            |         |
           ---       ---
          |nod| ->  |dad|
           ---       ---
                      |
                     ---
                    |nod|
                     ---

Example of dad insertion:

     ucl_tree_insert_dad( 1, A )
     
     0               D         0
     |               |         |
     1--2--3--4  +   A--C  =   A--C
     |  |            |         |
     5  6            B         1--2--3--4
                               |  |
                               5  6

the D and B nodes are detached and will be lost if we don't keep a reference to them.

— Function: void ucl_tree_insert_son (void * node, void * son)

Insert a new child for a node. The node referenced by son becomes the last between the children of the node referenced by node.

           ---         ---
          |nod|       |nod|
           ---         ---
            |     ->    |
           ---         ---     ---
          | A |       | A |-->|son|
           ---         ---     ---

Example of son insertion:

     ucl_tree_insert_son( 0, A )
     
     0               D         0
     |               |         |
     1--2--3--4  +   A--C  =   1--2--3--4--A--C
     |  |            |         |  |        |
     5  6            B         5  6        B

the node D is detached and will be lost if we don't keep a reference to it.

— Function: void ucl_tree_insert_prev (void * node, void * bro)

Insert a new brother for a node. The node referenced by bro becomes the left brother of the node referenced by node.

           ---    ---          ---    ---    ---
          | A |--|nod|   ->   | A |--|bro|--|nod|
           ---    ---          ---    ---    ---

Example of prev node insertion:

     ucl_tree_insert_prev( 2, A )
     
     0               D         0
     |               |         |
     1--2--3--4  +   A--C  =   1--A--2--3--4
     |  |            |         |  |  |
     5  6            B         5  B  6

the D and C nodes are detached and will be lost if we don't keep a reference to them.

— Function: void ucl_tree_insert_next (void * node, void * bro)

Insert a new brother for a node. The node referenced by bro becomes the right brother of the node referenced by node.

           ---    ---          ---    ---    ---
          |nod|--| A |   ->   |nod|--|bro|--| A |
           ---    ---          ---    ---    ---

Example of next brother insertion:

     ucl_tree_insert_next( 2, A )
     
     0               D         0
     |               |         |
     1--2--3--4  +   A--C  =   1--2--A--3--4
     |  |            |         |  |
     5  6            B         5  6

the D, B and C nodes are detached and will be lost if we don't keep a reference to them.


Next: , Previous: tree insertion, Up: tree

5.2.4 Testing relationships between nodes

All the following functions accept void * values as arguments: internally these pointers are cast to ucl_node_t.

— Function: ucl_bool_t ucl_tree_is_dad (void * dad, void * cld_p)

Return true if the node referenced by dad is the father of the node referenced by cld_p, otherwise return false.

— Function: ucl_bool_t ucl_tree_is_bro (void * node, void * bro)

Return true if the node referenced by node is a brother of the node referenced by bro, otherwise return false.

— Function: ucl_bool_t ucl_tree_has_dad (void * self)

Return true if the node referenced by self has a parent, otherwise return false.

— Function: ucl_bool_t ucl_tree_has_prev (void * self)

Return true if the node referenced by self has a brother to the left, otherwise return false.

— Function: ucl_bool_t ucl_tree_has_next (void * self)

Return true if the node referenced by self has a brother to the right, otherwise return false.

— Function: ucl_bool_t ucl_tree_has_son (void * self)

Return true if the node referenced by self has a son, otherwise return false.


Next: , Previous: tree testing, Up: tree

5.2.5 Accessing or setting the relatives of a node

All the following functions accept void * values as arguments: internally these pointers are cast to ucl_node_t.

— Function: void * ucl_tree_ref_dad (void * self)

Return a pointer to the father of the node referenced by self; if the node has no parent: return NULL.

— Function: void * ucl_tree_ref_prev (void * self)

Return a pointer to the left brother of the node referenced by self; if the node has no left brother: return NULL.

— Function: void * ucl_tree_ref_next (void * self)

Return a pointer to the right brother of the node referenced by self; if the node has no right brother: return NULL.

— Function: void * ucl_tree_ref_son (void * self)

Return a pointer to the son of the node referenced by self; if the node has no child: return NULL.

— Function: void * ucl_tree_ref_first (void * self)

Return a pointer to the first between the brothers of the node referenced by self; it can be a pointer to self itself, if self is the first.

— Function: void * ucl_tree_ref_last (void * self)

Return a pointer to the last between the brothers of the node referenced by self; it can be a pointer to self itself, if self is the last.


Next: , Previous: tree relatives, Up: tree

5.2.6 Removing elements from a tree

These functions will extract a node from a tree, returning a pointer to the extracted node. All the following functions accept void * values as arguments and return void * values: internally these pointers are cast to ucl_node_t.

— Function: void * ucl_tree_extract_dad (void * node)

Extract the dad of the node referenced by node from the tree. The referenced node and all its brothers are inserted in place of the extracted dad.

Returns a pointer to the extracted node, or NULL if the selected node has no dad. All the pointers in the extracted node structure are reset to NULL.

           ---    ---    ---       ---    ---    ---    ---
          | A |--|dad|--| B |     | A |--|nod|--| C |--| B |
           ---    ---    ---       ---    ---    ---    ---
                   |          ->
                  ---    ---              ---
                 |nod|--| C |            |dad|
                  ---    ---              ---
— Function: void * ucl_tree_extract_son (void * node)

Extract the son of the node referenced by node from the tree. The son of the selected node is extracted from the hierarchy. All of its children become children of the selected node.

Return a pointer to the extracted node or NULL if the selected node has no son. All the pointers in the extracted node structure are reset to NULL.

           ---               ---
          |nod|             |nod|
           ---               ---
            |                 |
           ---    ---        ---    ---    ---
          |son|--| C |  ->  | A |--| B |--| C |
           ---    ---        ---    ---    ---
            |
           ---    ---            ---
          | A |--| B |          |son|
           ---    ---            ---
— Function: void * ucl_tree_extract_prev (void * node)

Extract the left brother of the node referenced by node. The left brother of the selected node is extracted from the hierarchy. Its children become left brothers of the selected node.

Return a pointer to the extracted node, or NULL if the selected node has no left brother. All the pointers in the extracted node structure are reset to NULL.

           ---               ---
          | A |             | A |
           ---               ---
            |                 |
           ---    ---        ---    ---
          |prv|--|nod|  ->  | B |--|nod|
           ---    ---        ---    ---
            |
           ---                   ---
          | B |                 |prv|
           ---                   ---
— Function: void * ucl_tree_extract_next (void * node)

Extract the right brother of the node referenced by node. The right brother of the selected node is extracted from the hierarchy. Its children become right brothers of the selected node.

Return a pointer to the extracted node, or NULL if the selected node has no right brother. All the pointers in the extracted node structure are reset to NULL.

           ---    ---    ---       ---    ---    ---
          |nod|--|nxt|--| A |     |nod|--| B |--| A |
           ---    ---    ---       ---    ---    ---
                   |           ->
                  ---                 ---
                 | B |               |nxt|
                  ---                 ---


Previous: tree removing, Up: tree

5.2.7 Traversing a tree

For the tree iterators, the return value of ucl_iterator_ptr() is a pointer to the current node. All the following functions accept void * values as arguments: internally these pointers are cast to ucl_node_t.

— Function: void ucl_tree_iterator_inorder (void * node, ucl_iterator_t iter)

Initialises an in–order iteration.

— Function: void ucl_tree_iterator_preorder (void * node, ucl_iterator_t iter)

Initialises a pre–order iteration.

— Function: void ucl_tree_iterator_postorder (void * node, ucl_iterator_t iter)

Initialises a post–order iteration.


Next: , Previous: hash, Up: containers

5.3 The heap structure

The heap container allows us to collect a bunch of values and extract them sorted, from the lesser to the greater, according to a custom comparison function. The UCL heap is implemented as a binary tree, with nodes of type ucl_node_tag_t; the current implementation is probably inefficient, especially because of the cost of finding the next node under which append new nodes; but even without that, it would not be an efficient implementation anyway.


Next: , Up: heap

5.3.1 How it is done

The heap is implemented as binary tree in which we keep track of the root node and of the “next dad” node; new nodes are appended as children of the next dad, first as son then as bro; if a new node has key lesser than its dad we raise it in the tree.

Let's see an example of heap construction. Let's say the heap already has ‘5’ as root node; being the only one, the root node is also the next dad (marked with ‘n’ in the pictures). Let's append ‘8’ as son of the next dad:

     n5
      |
      8

now let's append ‘10’ as bro of next dad; the next dad becomes full so we do a breadth first step from ‘5’ to update it:

     n5--10       5--10
      |      =>   |
      8          n8

now let's append ‘3’ as son of next dad, then raise it in the tree while it is lesser than its dad:

      5--10       5--10       3--10
      |           |           |
     n8      =>  n3      =>  n5
      |           |           |
      3           8           8

now let's append ‘4’ as bro of next dad, then raise it in the tree while it is lesser than its dad; finally, since the next dad has become full, we do a breadth first step from ‘4’ to update it:

      3--10       3--10      3--n10
      |           |          |
     n5--4   =>  n4--5   =>  4--5
      |           |          |
      8           8          8

we understand how to add ‘12’:

     3--n10      3----n10
     |           |     |
     4--5    =>  4--5  12
     |           |
     8           8

and how to add ‘14’ updating the next dad with a breadth first step from ‘10’:

     3----n10--14      3-----10--14
     |     |           |     |
     4--5  12      =>  4--5  12
     |                 |
     8                n8

further nodes will be appended to ‘8’.

Let's see some examples of node extraction. Extracting a node from the heap means to extract its root, which is the lesser one; we replace it with the lesser among its children, then recursively descend the tree always replacing with the lesser. So first we extract ‘3’:

      3-----10--14      4-----10--14      4-----10--14
      |     |           |     |           |     |
      4--5  12      =>  *--5  12      =>  5     12
      |                 |                 |
     n8                n8                n8

then we extract ‘4’:

      4-----10--14      5-----10--14      5-----10--14
      |     |           |     |           |     |
      5     12      =>  *     12      => n8     12
      |                 |
     n8                n8

and so on.


Next: , Previous: heap intro, Up: heap

5.3.2 Heap type definitions

— Struct Typedef: ucl_heap_tag_t
— One Element Array Typedef: ucl_heap_t

The base structure of the heap container. The base structure stores the context associated to a heap such as the comparison function for the nodes.

The UCL heap container collects nodes of type ucl_node_tag_t, which hold no custom data; we have to at least associate a key to each node, doing something like this:

     typedef struct link_tag_t {
       ucl_node_tag_t        node;
       ucl_value_t           key;
     } link_tag_t;
     
     typedef link_tag_t *        link_t;
     
     static ucl_value_t
     link_key (ucl_value_t context UCL_UNUSED, void * L_)
     {
       link_t    L = L_;
       return L->key;
     }
     
     static const ucl_node_getkey_t getkey = {
       .data = { .pointer = NULL },
       .func = link_key
     };

and then use getkey as last argument to ucl_heap_initialise(); we can use the key extractor directly like this:

     link_t          L;
     ucl_value_t     K;
     
     K = getkey.func(getkey.data, L);


Next: , Previous: heap types, Up: heap

5.3.3 Creating and destroying heap

— Function: void ucl_heap_initialise (ucl_heap_t H, ucl_comparison_t keycmp, ucl_node_getkey_t getkey)

Initialise an already allocated heap structure. keycmp is the function+context used to compare keys; getkey is the function+context used to extract the key from nodes.

When a heap must be destroyed: all its nodes must be extracted and released with the appropriate function.


Next: , Previous: heap creation, Up: heap

5.3.4 Adding elements to a heap

— Function: void ucl_heap_insert (ucl_heap_t H, void * N)

Insert a new node in the heap. N is internally cast to ucl_node_t.


Next: , Previous: heap insertion, Up: heap

5.3.5 Removing elements from a heap

— Function: void * ucl_heap_extract (ucl_heap_t H)

Extract a node from the heap; return a pointer to it, or NULL if the heap is empty. The extracted node is the one with the smallest value; the returned value can be safely cast to ucl_node_t.


Previous: heap deletion, Up: heap

5.3.6 Various operations on a heap

— Inline Function: size_t ucl_heap_size (const ucl_heap_t H)

Return a value of type size_t representing the number of nodes in the heap.

— Function: void ucl_heap_merge (ucl_heap_t H, ucl_heap_t other)

Merge two heaps: nodes from other are extracted and inserted into H. When the function returns other is empty.

— Inline Function: void * ucl_heap_root (const ucl_heap_t H)

Return a pointer to the top node in the heap, without extracting it.


Next: , Previous: tree, Up: containers

5.4 The circular list

The circular container provides a circular doubly linked list; it is implemented as a chain of ucl_node_t structures; a pointer to the current position is stored in a base structure. The current position marker can be moved forward and backward as a cursor.

The handling of list links is derived from the handling of elements in the TCL (Tool Command Language) hash table by John Ousterhout and others (http://www.tcl.tk for more about TCL).
— Struct Typedef: ucl_circular_tag_t
— One Element Array: ucl_circular_t

Base structure of the container. It must be allocated by the user's code.


Next: , Up: circular

5.4.1 Creating and destroying circulars

— Function: void ucl_circular_constructor (ucl_circular_t self)

Initialise an already allocated structure. Set all the fields of self so that the structure represents an empty circular list.

— Function: void ucl_circular_destructor (ucl_circular_t self)

Destroys the structure. Set all the fields of self so that the structure represents an empty circular list. Before calling this function the user's code has to make sure that all the links are extracted from the list.

To extract all the links from a circular list, we can do:

     ucl_circular_t  circ;
     ucl_node_t      link;
     ucl_value_t     val;
     
     while (ucl_circular_size(circ))
       {
         link = ucl_circular_extract(circ);
         /* insert here the code to destroy the value */
         /* insert here the code to free the link memory */
       }

if the value needs no destructor and we are using a memory allocator as implemented by UCL, we can do:

     ucl_memory_allocator_t  A;
     ucl_circular_t  circ;
     ucl_node_t      link;
     
     while (ucl_circular_size(circ))
       {
         link = ucl_circular_extract(circ);
         A.alloc(A.data, &link, 0);
       }


Next: , Previous: circular creation, Up: circular

5.4.2 Adding elements to a circular

— Function: void ucl_circular_insert (ucl_circular_t self, ucl_node_t link_p)

Insert an element at the current position. To do this the user's code has to allocate a new circular link structure, store the value into it and hand a pointer to the node to this function.

The old current link becomes the next link.

Example of link insertion (the link has no value):

     ucl_memory_allocator_t  A;
     ucl_circular_t  circ;
     ucl_node_t      link = NULL;
     
     A.alloc(A.data, &link, sizeof(ucl_node_tag_t));
     ucl_circular_insert(circ, link);


Next: , Previous: circular adding, Up: circular

5.4.3 Removing elements from a circular

— Function: ucl_node_t ucl_circular_extract (ucl_circular_t self)

Extract the current link and return a pointer to it, or NULL if the list is empty. The new current element is the next in the forward direction.

Example of link deletion and memory release:

     ucl_memory_allocator_t  A;
     ucl_circular_t  circ;
     ucl_node_t      link;
     
     link = ucl_circular_extract(circ);
     if (NULL != link)
       A.alloc(A.data, &link, 0);


Next: , Previous: circular removing, Up: circular

5.4.4 Moving the cursor

— Function: void ucl_circular_forward (ucl_circular_t self, int times)

Move forwards the current position, times is the forward offset: it can be a positive or negative integer. If the container is empty, or the offset is zero, nothing happens.

— Function: void ucl_circular_backward (ucl_circular_t self, int times)

A wrapper for ucl_circular_forward(): move backwards the current position, times is the backward offset. If the container is empty, or the offset is zero, nothing happens.


Next: , Previous: circular moving, Up: circular

5.4.5 Searching elements

— Function: void ucl_circular_set_compar (ucl_circular_t this, ucl_comparison_t compar)

Register the function to be used to compare elements.

— Function: ucl_node_t ucl_circular_find (ucl_circular_t self, ucl_value_t val)

Move the current position to the first forward element whose value is equal to val; return a pointer to the link, or NULL if the value was not found.

While performing the search, the selected comparison function is invoked with val as second argument and a pointer to the current link as third argument:

          ucl_comparison_t compar = self.compar;
          ucl_node_t   link  = ...;
          ucl_value_t  inner = { .pointer = link };
          
          compar.func(compar.data, val, inner);


Previous: circular search, Up: circular

5.4.6 Various operations on a circular

— Function: size_t ucl_circular_size (ucl_circular_t self)

Return the number of elements in the container.

— Function: ucl_node_t ucl_circular_current (ucl_circular_t self)

Return a pointer to the current link, or NULL if the container is empty.


Next: , Previous: circular, Up: containers

5.5 The graph structure

A UCL graph is a network of (not so) little data structures; the elements of the graph are nodes and links.


Next: , Up: graph

5.5.1 How it's done

UCL does not enforce the use of a container to collect graph node structures: it is responsibility of the user to put nodes somewhere. For convenience: the node structure has a “next node” field that allows us to put nodes into a simply linked list, but it is not mandatory to use it.

Each node references two doubly linked lists of links: one for outgoing links and one for incoming links.

                      ------
         NULL  ------| node |-----  NULL
           ^  |       ------      |  ^
           |  v                   v  |
      -----------               ------------
     | in link 0 |             | out link 0 |
      -----------               ------------
          |^                         |^
          v|                         v|
      -----------               ------------
     | in link 1 |             | out link 1 |
      -----------               ------------
          |^                         |^
          v|                         v|
      -----------               ------------
     | in link 2 |             | out link 2 |
      -----------               ------------
          |                          |
          v                          v
        NULL                        NULL

Each link has references of both the source and destination nodes and is part of two doubly linked lists: one of outgoing links of the source node, one of incoming links of the destination node.

         ------------------          -----------------
        | prev output link |        | prev input link |
         ------------------          -----------------
                        |^            ^|
                        ||            ||
                        | ---      --- |
                         --- |    | ---
                            ||    ||
                            v|    |v
      -------------       ------------       -----------
     | source node |<----|    link    |---->| dest node |
      -------------       ------------       -----------
                            |^    ^|
                            ||    ||
                         --- |    | ---
                        | ---      --- |
                        ||            ||
                        v|            |v
         ------------------          -----------------
        | next output link |        | next input link |
         ------------------          -----------------


Next: , Previous: graph overview, Up: graph

5.5.2 Graph type definitions

Both node and link structures should be allocated using an equivalent of calloc(), or reset to zero before being inserted in a graph.

— Struct Typedef: ucl_graph_node_tag_t
— Pointer Typedef: ucl_graph_node_t

Structure type and pointer to structure type for nodes. They should be treated as opaque even if it is not.

— Struct Typedef: ucl_graph_link_tag_t
— Pointer Typedef: ucl_graph_link_t

Structure type and pointer to structure type for links. They should be treated as opaque even if it is not.


Next: , Previous: graph types, Up: graph

5.5.3 Inserting links and nodes

— Function: void ucl_graph_link (src_node, link, dst_node)

Insert a link between two nodes. The source and destination node structures cannot be exchanged: the link is directed. Arguments:

ucl_graph_node_t src_node
pointer to the source node structure;
ucl_graph_link_t link
pointer to the link structure;
ucl_graph_node_t dst_node
pointer to the destination node structure.

Usage example:

          ucl_memory_allocator_t  A;
          ucl_graph_node_t        src = NULL, dst = NULL;
          ucl_graph_link_t        lnk = NULL;
          
          A.alloc(A.data, &src, sizeof(ucl_graph_node_tag_t));
          A.alloc(A.data, &dst, sizeof(ucl_graph_node_tag_t));
          A.alloc(A.data, &lnk, sizeof(ucl_graph_link_tag_t));
          
          ucl_graph_link(src, lnk, dst);
— Function: ucl_bool_t ucl_graph_nodes_are_linked (ucl_graph_node_t src, ucl_graph_node_t dst)

Return true if there is a link between src and dst, with source src and destination dst.

— Function: ucl_bool_t ucl_graph_nodes_doubly_linked (ucl_graph_node_t A, ucl_graph_node_t B)

Return true if there are two links between A and B, one from A to B and one from B to A.

— Function: ucl_bool_t ucl_graph_nodes_are_connected (ucl_graph_node_t A, ucl_graph_node_t B)

Return true if there is a link between A and B, no matter the direction.


Next: , Previous: graph insert, Up: graph

5.5.4 Extracting links and nodes

— Function: void ucl_graph_unlink (ucl_graph_link_t L)

Remove a link from the graph. After this function has been called, it is safe to free the memory of the link.

To erase a node from a graph we have to remove all the links between it and the other nodes. To do it in the case of structures allocated with a UCL memory allocator:

     ucl_memory_allocator_t  A;
     ucl_graph_node_t        N;
     ucl_graph_link_t        L;
     
     for (L = ucl_graph_output_link(N); L;
          L = ucl_graph_output_link(N))
       {
         ucl_graph_unlink(L);
         A.alloc(A.data, &L, 0);
       }
     
     for (L = ucl_graph_input_link(N); L;
          L = ucl_graph_input_link(N))
       {
         ucl_graph_unlink(L);
         A.alloc(A.data, &L, 0);
       }
     
     A.alloc(A.data, &N, 0);
— Macro: UCL_GRAPH_FIRST_INPUT_LINK_LOOP (node, link)
— Macro: UCL_GRAPH_FIRST_OUTPUT_LINK_LOOP (node, link)

Loop over the first input or output link until it is NULL. These macros do the same loops described above; with them the extraction code looks like this:

          ucl_memory_allocator_t  A;
          ucl_graph_node_t        N;
          ucl_graph_link_t        L;
          
          UCL_GRAPH_FIRST_INPUT_LINK_LOOP(N, L) {
            ucl_graph_unlink(L);
            A.alloc(A.data, &L, 0);
          }
          
          UCL_GRAPH_FIRST_OUTPUT_LINK_LOOP(N, L) {
            ucl_graph_unlink(L);
            A.alloc(A.data, &L, 0);
          }
          
          A.alloc(A.data, &N, 0);
— Function: void ucl_graph_erase_node_destroy_links (ucl_graph_node_t node, ucl_callback_t destructor)

Erase a node from a graph finalising all the links; the erasure code looks like this:

          ucl_graph_node_t        N;
          ucl_callback_t          destructor;
          
          ucl_graph_erase_node_destroy_links(N, destructor);
          A.alloc(A.data, &N, 0);

and we can implement:

          ucl_value_t
          destructor_fun (ucl_value_t dummy, ucl_graph_link_t L)
          {
            A.alloc(A.data, &L, 0);
          }
          ucl_callback_t destructor = {
            .data = ucl_value_null,
            .func = destructor_fun
          };

The node structure itself is not finalised: its link fields are set to NULL, the value field is left untouched, the structure memory is not freed.


Next: , Previous: graph extract, Up: graph

5.5.5 Merging links

Merging means to replace two links with one that represents the whole path; before merging the scenario is:

      --------     ---------     --------     ----------     ------
     | source |<--| in link |-->| middle |<--| out link |-->| dest |
     |  node  |    ---------    |  node  |    ----------    | node |
      --------                   --------                    ------

merging can be done upon the input or the output link; after merging upon the input link:

      --------     ---------     ------
     | source |<--| in link |-->| dest |
     |  node  |    ---------    | node |
      --------                   ------

after merging upon the output link:

      --------     ----------     ------
     | source |<--| out link |-->| dest |
     |  node  |    ----------    | node |
      --------                    ------
— Function: void ucl_graph_merge_upon_input_link (ucl_graph_link_t in, ucl_graph_link_t out)
— Function: void ucl_graph_merge_upon_output_link (ucl_graph_link_t in, ucl_graph_link_t out)

Merge two links; in references the link incoming to the middle node; out references the link outgoing from the middle node.

Merging is meaningful if in and out are connected to the same node, but these functions do not check for this.

The middle node is excluded from the path: if other links connect the node to the graph nothing needs to be done, but if merging the links removes the last links between the node and the graph: the node must be finalised.


Next: , Previous: graph merge, Up: graph

5.5.6 Accessing values

— Function: void ucl_graph_node_set_value (ucl_graph_node_t * p, ucl_value_t newval)
— Function: void ucl_graph_link_set_value (ucl_graph_link_t * p, ucl_value_t newval)

Store a new value in the structure.

— Function: ucl_value_t ucl_graph_node_get_value (ucl_graph_node_t * p)
— Function: ucl_value_t ucl_graph_link_get_value (ucl_graph_link_t * p)

Return the current value in the structure.

— Function: void ucl_graph_node_set_mark (ucl_graph_node_t * p, ucl_value_t mark)
— Function: ucl_value_t ucl_graph_node_get_mark (ucl_graph_link_t * p)

Set/get the mark value, a field of ucl_value_t type.


Next: , Previous: graph value, Up: graph

5.5.7 Link iterators

— Macro: UCL_GRAPH_OUTPUT_LINKS_LOOP (node, link)
— Macro: UCL_GRAPH_INPUT_LINKS_LOOP (node, link)

Iterate over the outgoing or ingoing links of node using link as iterator in a for () loop.

Example of iteration over outgoing links:

          ucl_graph_node_t        N;
          ucl_graph_link_t        L;
          
          UCL_GRAPH_OUTPUT_LINKS_LOOP(N, L) {
            do_something_with(L);
          }

example of iteration over incoming links:

          ucl_graph_node_t        N;
          ucl_graph_link_t        L;
          
          UCL_GRAPH_INPUT_LINKS_LOOP(N, L) {
            do_something_with(L);
          }
Finding first and last links
— Function: ucl_graph_link_t ucl_graph_input_link (ucl_graph_node_t N)
— Function: ucl_graph_link_t ucl_graph_output_link (ucl_graph_node_t N)

Return a pointer to the first incoming or outgoing link of N.

— Function: ucl_graph_link_t ucl_graph_last_output_link (ucl_graph_link_t L)
— Function: ucl_graph_link_t ucl_graph_last_input_link (ucl_graph_link_t L)

Traverse toward the end the list of incoming or outgoing links, starting at L. Return the last link.

— Function: ucl_graph_link_t ucl_graph_first_output_link (ucl_graph_link_t L)
— Function: ucl_graph_link_t ucl_graph_first_input_link (ucl_graph_link_t L)

Traverse toward the beginning the list of incoming or outgoing links, starting at L. Return the first link.

Finding previous and next links
— Function: ucl_graph_link_t ucl_graph_prev_input_link (ucl_graph_link_t L)
— Function: ucl_graph_link_t ucl_graph_prev_output_link (ucl_graph_link_t L)

Return a pointer to the previous link in the chain. The return value is NULL if L is the first link.

— Function: ucl_graph_link_t ucl_graph_next_input_link (ucl_graph_link_t L)
— Function: ucl_graph_link_t ucl_graph_next_output_link (ucl_graph_link_t L)

Return a pointer to the next link in the chain. The return value is NULL if L is the last link.


Next: , Previous: graph link iter, Up: graph

5.5.8 Various operations on a graph

— Function: size_t ucl_graph_number_of_input_links (ucl_graph_node_t N)
— Function: size_t ucl_graph_number_of_output_links (ucl_graph_node_t N)

Return the number of incoming or outgoing links.


Previous: graph ops, Up: graph

5.5.9 Depth first search

Depth first search (DFS) is an iteration over the nodes of a graph that starts from a selected node and visits a node only once; the result of the iteration is a string of nodes. The iteration is analogous to the preorder iteration in trees (the worm that always turns right in the labyrinth).

The iteration may not touch all the nodes:

UCL implements two types of DFS: one that honors the direction of the links; one that does not.


Next: , Up: graph dfs
5.5.9.1 DFS example

Given the following connected graph:

      -- A ---> B ---> C
     |   |      |
     |   |       ------
     |   |             |
     |   |             v
     |    ----> D <--- E
     |          ^
     v          |
     F ---------

we see that we can partition the nodes in two sets:

     one = { A, F }  two = { B, C, E, D }

there are no links going from partition two to partition one; the directed DFS starting at node B is:

     B, C, E, D

nodes in partition one are not touched; while the undirected DFS starting at node B is:

     B, C, E, D, F, A

all the nodes are touched.

We note that:

  1. if the number of nodes touched by the directed DFS equals the number of nodes in the graph: the graph is connected;
  2. the iteration goes “deep” inside a graph and then steps back in search of new ramifications;
  3. if every time the iterator does a step we increment a counter: by saving the values of counter when entering a node and leaving a node, we can infer properties of the graph.


Next: , Previous: graph dfs example, Up: graph dfs
5.5.9.2 DFS related type defintions

The DFS is implemented as a recursive process that puts touched nodes on a stack. The stack is the result of the iteration. A DFS is not reentrant because nodes are marked by setting a field in ucl_graph_node_t structures: while a DFS is performed the graph must be locked for mutual exclusion.

Also, do not modify a graph while a DFS is running: the result is undefined.

— Struct Typedef: ucl_graph_dfs_tag_t
— One Element Array: ucl_graph_dfs_t

Hold the result of a DFS, both directed and not. This structure must be handled as opaque.

— Struct Typedef: ucl_graph_dfs_item_t

Represent a node touched by the iteration. Public fields:

ucl_graph_node_t node
pointer to the node;
size_t in_counter
the value of the counter when the node was entered;
size_t out_counter
the value of the counter when the node was left.

The initial value of the counters is zero; the root node of the DFS is recognisable because it has in_counter = 0.


Previous: graph dfs types, Up: graph dfs
5.5.9.3 DFS programming interface
— Function: void ucl_graph_dfs_initialise_handle (ucl_graph_dfs_t S)

Initialise an already allocated search handle.

— Function: void ucl_graph_dfs_finalise_handle (ucl_graph_dfs_t S)

Finalise a search handle. All the memory is released. A DFS must always be finalised with a call to this function.

— Function: void ucl_graph_dfs_directed (ucl_graph_dfs_t S, ucl_graph_node_t root)

Perform a directed DFS over a graph starting from root; store the result into S.

— Function: void ucl_graph_dfs (ucl_graph_dfs_t S, ucl_graph_node_t root)

Perform a non–directed DFS over a graph starting from root; store the result into S.

Example:

     ucl_graph_dfs_t         S;
     ucl_vector_t            visited_nodes;
     
     ucl_graph_initialise_dfs_handle(S, visited_nodes);
     {
       ucl_iterator_t          I;
       ucl_graph_node_t *      root;
     
       ucl_graph_dfs_directed(S, root);
       for (ucl_vector_iterator_forward(visited_nodes, I);
            ucl_iterator_more(I); ucl_iterator_next(I))
         {
           ucl_graph_dfs_item_t *  item;
     
           item = ucl_iterator_ptr(I);
           do_something_with(item);
         }
     }
     ucl_graph_dfs_finalise_handle(S);


Next: , Previous: graph, Up: containers

5.6 The hash table structure

A hash table is a structure that maps keys to values in a way that allows the search operation to be performed with constant time for all the keys.

The hash was inspired by the book on C++ by Bjarne Stroustrup and the hash structure in the TCL (Tool Command Language) source code, by John Ousterhout and others (http://www.tcl.tk/ for more about TCL). However, no code comes from TCL.


Next: , Up: hash

5.6.1 How it is done

A UCL vector of pointers is allocated by the constructor; each pointer, called “bucket” in this document, can be NULL (empty bucket) or referencing an entry structure. Entry structures are chained in a linked list.

                 buckets
     
                  ----         -----     -----
                 |  o-+------>|entry|-->|entry|
                 |----|        -----     -----
     empty  .....|NULL|
     buckets  .  |----|        -----
              .  |  o-+------>|entry|
              .  |----|        -----    -----
              .  |  o-+--------------->|entry|
              .  |----|                 -----
               ..|NULL|
                  ----

The UCL way of managing a vector is to allocate a block of memory, with hysteresis, and consider a sub–block of it as “in use”, that is: as holding the collected data. When the hash table is constructed all the slots are marked as used, even when the bucket is set to NULL. Reallocations can cause some of the slots to be unused, but if we never reallocate the vector all the memory is used to hold buckets.

Elements insertion and deletion

When inserting a new entry in the table, the hash function converts the keys to integers in the range [0, number_of_buckets), selecting a bucket; then the bucket is examined:

It's obvious how the extraction operation works.

If the keys are such that the hash function distributes entries uniformly over all the buckets, the time spent to find an entry is (more or less) constant.

Resizing

Enlarging or restricting the hash table means enlarging or restricting the vector of buckets. This happens with rules similar, but not equal, to the ones for the ucl_vector_t structure; the differences are:

Enlarging and restricting changes the number of buckets, so it requires a rehashing of all the entries in the table: this is expensive.


Next: , Previous: hash intro, Up: hash

5.6.2 Hash table types definitions

— Struct Typedef: ucl_hash_table_tag_t
— One Element Array: ucl_hash_table_t

The base structure. The vector of buckets is available as the field ucl_vector_t buckets.

The UCL hash container collects entries of type ucl_node_tag_t, which hold no custom data; we have to at least associate a key to each node, doing something like this:

     typedef struct entry_tag_t {
       ucl_node_tag_t        node;
       ucl_value_t           key;
     } entry_tag_t;
     
     typedef entry_tag_t *        entry_t;
     
     static ucl_value_t
     entry_key (ucl_value_t context UCL_UNUSED, void * L_)
     {
       entry_t    L = L_;
       return L->key;
     }
     
     static const ucl_node_getkey_t getkey = {
       .data = { .pointer = NULL },
       .func = entry_key
     };

and then use getkey as last argument to ucl_hash_initialise(); we can use the key extractor directly like this:

     entry_t         L;
     ucl_value_t     K;
     
     K = getkey.func(getkey.data, L);


Next: , Previous: hash types, Up: hash

5.6.3 Creating and destroying hash tables

The construction of a hash table is split in two steps, to allow custom configuration of the vector of buckets. A simple construction, using the default values, for a table using strings as keys goes like this:

     ucl_vector_config_t C;
     ucl_vector_t        V;
     ucl_hash_table_t    H;
     ucl_node_getkey_t   getkey;
     
     ucl_vector_initialise_config_hash(C);
     ucl_vector_alloc(V, C);
     ucl_hash_initialise(H, V, ucl_compare_string, ucl_hash_string,
                         getkey);

when finalising a hash table we have to release the UCL vector explicitly, but only after having extracted and released all the table entries; when using a UCL memory allocator, it goes like this:

     ucl_memory_allocator_t  A;
     ucl_vector_t            V;
     ucl_hash_table_t        H;
     entry_t                 E;
     
     while ((E = ucl_hash_first(H)))
       {
         ucl_hash_extract(H, E);
         A.alloc(A.data, &E, 0);
       }
     ucl_vector_free(V);

the hash table structure does not need finalisation.

— Function: void ucl_hash_initialise (ucl_hash_t self, ucl_vector_t buckets, ucl_comparison_t compar, ucl_hash_t hash, ucl_node_getkey_t getkey)

Initialise the hash table referenced by self. The UCL vector of buckets, already initialised, becomes part of the hash table state.

compar is the function+context used to compare keys.

hash is the function+context used to compute the hash value of keys; typedefs hash for details.

getkey is the function+context used to extract the key from an entry structures; typedefs nodes for details.


Next: , Previous: hash creation, Up: hash

5.6.4 Adding elements to a hash table

— Function: void ucl_hash_insert (ucl_hash_table_t H, void * E)

Insert a new entry in the table. The entry structure must be allocated and filled with key and value by the user's code; the pointer E is internally cast to ucl_node_t.

Inserting an entry with a key that already exists in the table will work, but future invocations of ucl_hash_find() will return one or the other: nobody knows which one. To avoid collision of keys, we have to check the existence of a key with ucl_hash_find() before attempting to insert a new entry.

Example:

          ucl_memory_allocator_t  A;
          ucl_hash_table_t        H;
          entry_t                 E;
          ucl_value_t             K;
          
          K = ...
          E = ucl_hash_find(H, K);
          if (NULL == E)
            {
              A.alloc(A.data, &E, sizeof(entry_t));
              E->key = K;
              ucl_hash_insert(H, E);
            }


Next: , Previous: hash insertion, Up: hash

5.6.5 Removing elements from a hash table

— Function: void ucl_hash_extract (ucl_hash_table_t H, void * E)

Extract an entry from the table. E, a pointer to the entry to be removed, must be the return value of a previous invocation to ucl_hash_find(); the pointer E is internally cast to ucl_node_t. The entry structure is neither destroyed nor freed, just extracted.

Example:

          ucl_memory_allocator_t  A;
          ucl_hash_t              H;
          entry_t                 E;
          ucl_value_t             K;
          
          E = ucl_hash_find(H, K);
          if (NULL != E)
            {
              ucl_hash_extract(H, E);
              A.alloc(A.data, &E, 0);
            }


Next: , Previous: hash deletion, Up: hash

5.6.6 Various operations on a hash table

— Function: void * ucl_hash_find (const ucl_hash_table_t H, const ucl_value_t K)

Search in the table an entry associated with the selected key. Return a pointer to the entry or NULL if the key was not found; the returned pointer can be safely cast to ucl_node_t.

— Function: void * ucl_hash_first (const ucl_hash_table_t H)

Return a pointer to the first entry in the table: the first link in the list of the first non–NULL bucket. If the table is empty: return NULL; the returned pointer can be safely cast to ucl_node_t.

— Function: size_t ucl_hash_size (const ucl_hash_table_t H)

Return the number of entries in the table.

— Function: size_t ucl_hash_number_of_buckets (const ucl_hash_table_t H)

Return the number of buckets.

— Function: size_t ucl_hash_number_of_used_buckets (const ucl_hash_table_t H)

Return the number of used buckets.

— Function: size_t ucl_hash_bucket_chain_length (const ucl_hash_table_t this, ucl_index_t position)

Return the number of entries in the chain refereces by bucket at position. position must be a valid bucket index: a non–negative integer in the range [0, ucl_hash_number_of_buckets(this)).

— Function: double ucl_hash_average_search_distance (const ucl_hash_table_t this)

Return the average number of entries per bucket.


Next: , Previous: hash ops, Up: hash

5.6.7 Resizing a hash table

At present the hash table is not enlarged automatically. The decision is delegated to the user's code.

— Function: void ucl_hash_enlarge (ucl_hash_table_t H)

Enlarge the table using the underlying UCL vector module. This is an expensive operation because it requires rehashing all the entries. If an error occurs reallocating the vector: the table is not corrupted.

— Function: void ucl_hash_restrict (ucl_hash_table_t H)

Restrict the table using the underlying UCL vector module. This is an expensive operation because it requires rehashing all the entries. If an error occurs reallocating the vector: the table is not corrupted.


Next: , Previous: hash resizing, Up: hash

5.6.8 Visiting elements in the table

— Function: void ucl_hash_iterator (const ucl_hash_table_t H, ucl_iterator_t I)

Initialise the table iterator. The iterator pointer references the entries in the table. The order in which the entries are visited is unknown.

Example:

          ucl_hash_table_t  H;
          ucl_iterator_t    I;
          entry_t           E;
          
          for (ucl_hash_iterator(H, I);
               ucl_iterator_more(I);
               ucl_iterator_next(I))
            {
              E = ucl_iterator_ptr(I);
            }


Previous: hash iterator, Up: hash

5.6.9 Provided hash function

— Variable: ucl_hash_t ucl_hash_string

Function and context required to hash strings. The function is ucl_hash_string_fun().

— Function: size_t ucl_hash_string_fun (ucl_value_t unused, const ucl_value_t K)

Return an unsigned integer representing the hash value for the string in K; the chars member of K must be a pointer to a NULL–terminated string of characters, typedefs value for details.

The hashing algorithm comes from a C++ book by Bjarne Stroustrup (references).


Next: , Previous: heap, Up: containers

5.7 The linked list structure

The UCL list is a way of chaining ucl_node_tag_t structures in a doubly linked list; all the functions from the btree and tree modules can be used upon lists.


Next: , Up: list

5.7.1 How it is done

A UCL list is a chain of ucl_node_tag_t structures in which the bro and dad fields are involved:

                ----  bro   ----  bro   ----  bro
     NULL <----| N1 |----->| N2 |----->| N3 |----> NULL
           dad  ---- <----  ---- <----  ----
                      dad         dad

it is equivalent to a level of brothers in the UCL tree module; the son field can be set to NULL, or used to reference a nested list, or used to reference some other value. The brother of a node is called cdr, the son of a node is called car.

NOTE We use the terms car and cdr to refer to the son and bro of a node, but notice that their meaning in the context of the UCL is different from their meaning in the context of Lisp languages.

Going forwards in a list chain means to follow the bro pointers; going backwards in a list chain means to follow the dad pointers.


Next: , Previous: list overview, Up: list

5.7.2 Constructing lists

Structures of type ucl_node_tag_t must be allocated and released by the user code. The fields of a node structure must be set to NULL when they are not used as reference for another node.

All the following functions return and accept as arguments void * values; they are internally cast to ucl_node_t.

— Function: void ucl_list_set_car (void * N, void * M)

If N is non–NULL: set M as son of N; if M is non–NULL: set N as dad of M. btree typedefs for the meaning of this.

— Function: void ucl_list_set_cdr (void * N, void * P)

If N is non–NULL: set M as bro of N; if M is non–NULL: set N as dad of M. btree typedefs for the meaning of this.

For example, to build the hierarchy:

      -----    -----    -------
     | one |--| two |--| three |-- NULL
      -----    -----    -------

using the UCL memory allocator:

     ucl_memory_allocator_t  A;
     ucl_node_t              one, two, three;
     
     one   = ucl_malloc(ucl_memory_allocator, UCL_NODE_SIZE);
     two   = ucl_malloc(ucl_memory_allocator, UCL_NODE_SIZE);
     three = ucl_malloc(ucl_memory_allocator, UCL_NODE_SIZE);
     
     ucl_list_set_cdr(one, two);
     ucl_list_set_cdr(two, three);

remember that the UCL default allocator sets to zero every newly allocated block, so the fields in the allocated nodes are automatically set to NULL.


Next: , Previous: list cons, Up: list

5.7.3 Visiting a list

All the following functions return and accept as arguments void * values; they are internally cast to ucl_node_t. btree typedefs for the meaning of the fields of ucl_node_tag_t.

— Function: void * ucl_list_car (void * N)

Return the son of N.

— Function: void * ucl_list_cdr (void * N)

Return the bro of N.

— Function: void * ucl_list_prev (void * N)

Return the dad of N.

— Function: void * ucl_list_first (void * N)

Return the first element of the list.

— Function: void * ucl_list_last (void * N)

Return the last element of the list.

— Function: void * ucl_list_ref (void * N, ucl_index_t position)

Assuming N references the first node in a list: return a pointer to the link at position (zero based), or NULL if the index is out of range.

When using the following operations, it is impossible to distinguish between a NULL representing a legitimate return value and a NULL representing a return from an invalid operation; we have to take care of applying these operations only when they are legitimate.

— Function: void * ucl_list_caar (void * N)

Apply twice the car operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_cadr (void * N)

Apply the cdr operator, then the car operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_cdar (void * N)

Apply the car operator, then the cdr operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_cddr (void * N)

Apply twice the cdr operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_caaar (void * N)

Apply the car operator three times. Return NULL if the operation is invalid.

— Function: void * ucl_list_caadr (void * N)

Apply the cdr operator, then the car operator twice. Return NULL if the operation is invalid.

— Function: void * ucl_list_cadar (void * N)

Apply the car operator, then the cdr operator, then the car operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_caddr (void * N)

Apply the cdr operator twice, then the car operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_cdaar (void * N)

Apply the car operator twice, then the cdr operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_cdadr (void * N)

Apply the cdr operator, then the car operator, then the cdr operator. Return NULL if the operation is invalid.

— Function: void * ucl_list_cddar (void * N)

Apply the car operator, then the cdr operator twice. Return NULL if the operation is invalid.

— Function: void * ucl_list_cdddr (void * N)

Apply the cdr operator three times. Return NULL if the operation is invalid.


Next: , Previous: list visit, Up: list

5.7.4 Removing elements from a list

All the following functions return and accept as arguments void * values; they are internally cast to ucl_node_t. btree typedefs for the meaning of the fields of ucl_node_tag_t.

— Function: void * ucl_list_remove (void * N)

Remove N from its chain; return N itself.

— Function: void * ucl_list_popfront (void * N, void ** new_first)

Remove an element at the beginning of the list of which N is an element. Return a pointer to the removed element; store in new_first a pointer to the new first element of the list.

— Function: void * ucl_list_popback (void * N)

Remove an element at the end of the list of which N is an element.


Next: , Previous: list deletion, Up: list

5.7.5 Various operations on a list

All the following functions return and accept as arguments void * values; they are internally cast to ucl_node_t. btree typedefs for the meaning of the fields of ucl_node_tag_t.

— Function: size_t ucl_list_length (void * N)

Return the count of elements in the list from N towards the end.

— Function: void ucl_list_for_each (ucl_callback_t cb, void * N)

Apply the callback to N and all its brothers up to the end of the list.

— Function: void ucl_list_map (void * P, ucl_callback_t cb, void * Q)

Apply the callback to P and Q, and all their brothers up to the end of the P list. Q is meant to be the source value and P the destination value.

— Function: void * ucl_list_reverse (void * N)

Assuming N is the first element of a list: reverse the list and return it new first element.


Previous: list ops, Up: list

5.7.6 Iteration over a list

Example of forward iteration:

     ucl_node_t        N;
     
     while (N) {
       /* do something with N */
       N = ucl_list_cdr(N);
     }

example of backward iteration:

     ucl_node_t        N;
     
     while (N) {
       /* do something with N */
       N = ucl_list_prev(N);
     }


Next: , Previous: list, Up: containers

5.8 The map structure

The map container is an AVL tree; it can be used to implement an associative array.

The map/multimap idea was inspired by the book on C++ by Bjarne Stroustrup and by the STL C++ (Standard Template Library) by Stepanov and Lee.

The handling of nodes is influenced by the handling of elements in the TCL (Tool Command Language) hash table by John Ousterhout and others (http://www.tcl.tk/ for more about TCL).


Next: , Up: map

5.8.1 Introduction to operations and implementation

Maps are often used as associative arrays, that is: as collections of key/value pairs. The operations we want to do on a map are:

Clearly there are two sub–types of map container: the one that allows multiple values to be associated to the same key, and the one that does not. We call the first a multimap and the second a simple map.


Next: , Previous: map intro, Up: map

5.8.2 Type definitions for map

— Struct Typedef: ucl_map_tag_t
— Single Element Array Typedef: ucl_map_t

Base structure for the container. It must be allocated by the user's code.

The UCL map container collects nodes of type ucl_node_tag_t, which hold no custom data; we have to at least associate a key to each node, doing something like this:

     typedef struct link_tag_t {
       ucl_node_tag_t        node;
       ucl_value_t           key;
     } link_tag_t;
     
     typedef link_tag_t *        link_t;
     
     static ucl_value_t
     link_key (ucl_value_t context UCL_UNUSED, void * L_)
     {
       link_t    L = L_;
       return L->key;
     }
     
     static const ucl_node_getkey_t getkey = {
       .data = { .pointer = NULL },
       .func = link_key
     };

and then use getkey as last argument to ucl_map_initialise(); we can use the key extractor directly like this:

     link_t          L;
     ucl_value_t     K;
     
     K = getkey.func(getkey.data, L);


Next: , Previous: map types, Up: map

5.8.3 Creating and destroying maps

— Function: void ucl_map_initialise (ucl_map_t M, unsigned int flags, ucl_comparison_t keycmp, ucl_node_getkey_t getkey)

Initialise an already allocated map structure. flags configures the map behaviour; keycmp is the function+context used to compare keys; getkey is the function+context used to extract the key from nodes.

Map configuration flags can be zero or an ORed combination of:

UCL_ALLOW_MULTIPLE_OBJECTS
Allows more than one object to be associated to the same key, with this the map behaves like a multimap.

The map structure needs no destructor, but before releasing its memory block the user code has to extract all the nodes from the map.


Next: , Previous: map creation, Up: map

5.8.4 Adding elements to a map

The following functions accept void * as arguments and return values; internally these pointers are cast to ucl_node_t.

— Function: ucl_bool_t ucl_map_insert (ucl_map_t M, void * L)

Given an already allocated and constructed map link, insert it in the map.

An invocation to this function always inserts L into M if M is a multimap. If M is a simple map: L is inserted only if there is no link in M having key equal to the key of L.

The return value is true if the link has been inserted, or false if the link was not inserted.


Next: , Previous: map insertion, Up: map

5.8.5 Removing elements from a map

The following functions accept void * as arguments and return values; internally these pointers are cast to ucl_node_t.

— Function: void ucl_map_delete (ucl_map_t M, void * L)

Remove the node L from the referenced map. L must be the return value of a previous invocation to ucl_map_find(). This function only removes the link from the map, it's our responsibility to free the memory and resources associated to it.


Next: , Previous: map deletion, Up: map

5.8.6 Various operations on a map

The following functions accept void * as arguments and return values; internally these pointers are cast to ucl_node_t.

— Function: size_t ucl_map_count (const ucl_map_t M, const ucl_value_t key)

Return the number of elements with key; this is always 0 or 1 for simple maps.

— Function: void * ucl_map_find (const ucl_map_t M, const ucl_value_t key);

Return a pointer to the (first found) element associated with key. The return value is NULL if such an element does not exist.

For a multimap, this function returns a pointer to the first element with the selected key, so that the others can be found with repeated invocations of ucl_map_next().

— Function: ucl_bool_t ucl_map_find_node (const ucl_map_t M, void * N)

Return true if N is the pointer to a node in M, return false otherwise.

— Function: void * ucl_map_first (const ucl_map_t M)

Return a pointer to the element with lesser key in the map, or NULL if the map is empty.

— Function: void * ucl_map_last (const ucl_map_t M)

Return a pointer to the element with greater key in the map, or NULL if the map is empty.

— Function: void * ucl_map_next (const void * L)

Return a pointer to the element adjacent to the one referenced by L with greater key, or NULL if L has the greater key in the map.

— Function: void * ucl_map_prev (const void * L)

Return a pointer to the element adjacent to the one referenced by L with lesser key, or NULL if L has the lesser key in the map.

— Function: void * ucl_map_find_or_next (const ucl_map_t M, const ucl_value_t key)

Given a key find the element in the map associated with it, or the element with the lesser key greater than the selected one; if there are multiple links having key equal to key, select the rightmost one. Return a pointer to the requested link or NULL if all the keys in the map are lesser than the selected one.

— Function: void * ucl_map_find_or_prev (const ucl_map_t M, const ucl_value_t key)

Given a key find the element in the map associated with it, or the element with the greater key lesser than the selected one; if there are multiple links having key equal to key, select the leftmost one. Return a pointer to the requested link or NULL if all the keys in the map are greater than the selected one.

— Function: size_t ucl_map_size (const ucl_map_t M)

Return the number of elements in the map.

— Function: void * ucl_map_root (const ucl_map_t M)

Return a pointer to the current root node.

— Function: size_t ucl_map_depth (const ucl_map_t M)

Return the depth of the tree.


Next: , Previous: map ops, Up: map

5.8.7 Iteration over a map

The iteration is over the map links: ucl_iterator_ptr() returns a pointer to the current map link.

— Function: void ucl_map_iterator_inorder (const ucl_map_t M, ucl_iterator_t I)
— Function: void ucl_map_iterator_preorder (const ucl_map_t M, ucl_iterator_t I)
— Function: void ucl_map_iterator_postorder (const ucl_map_t M, ucl_iterator_t I)
— Function: void ucl_map_iterator_levelorder (const ucl_map_t M, ucl_iterator_t I)

Initalise an inorder, preorder, postorder or breadth first iteration. btree iteration for details.

— Function: void ucl_map_lower_bound (const ucl_map_t M, ucl_iterator_t I, ucl_value_t key)

Initialise an iteration over the elements with the selected key, starting with the first element.

— Function: void ucl_map_upper_bound (const ucl_map_t M, ucl_iterator_t I, ucl_value_t key)

Initialise an iteration over the elements with the selected key, starting with the last element.


Previous: map iterators, Up: map

5.8.8 Composing map iterators

It's possible to compose map iterators to implement set operations: the keys from a map are used as set elements. A set operation is implemented as an iterator that visits one by one the result of the operation itself.

The key values must be of the same data type. That means that the compare function used by both the maps must accept the same type of values and return the same values when called with the same arguments.

For all the set iterators, the arguments are:

ucl_iterator_t it1
pointer to an in–order iterator over set 1, already initialised;
ucl_iterator_t it2
pointer to an in–order iterator over set 2, already initialised;
ucl_iterator_t iter
pointer to the set iterator structure.

The input map iterators must be of in–order type: if the sequences are visited from the lesser to the greater key, the minimum amount of key comparison is performed.

If the sequences are not visited with the in–order iterator, the result is not defined.

The set iterators are used in the same fashion of all the other iterators in the UCL (iterators). The value retrieved with ucl_iterator_ptr() is the pointer to the referenced map link.

— Function: void ucl_map_iterator_union (it1, it2, iter)

Initialise the iteration over all the elements from both the sequences. Elements present in both sequences are included twice.

— Function: void ucl_map_iterator_intersection (it1, it2, iter)

Initialise the iteration over all the elements present in both the sequences. Elements included in only one sequence are discarded.

— Function: void ucl_map_iterator_complintersect (it1, it2, iter)

Initialise the iteration over all the elements present in only one of the two sequences.

— Function: void ucl_map_iterator_subtraction (it1, it2, iter)

Initialise the iteration over all the elements from sequence 1 that are not present in sequence 2.

Example:

     Sequence 1: 0 1 2 3 4 5 6
     Sequence 2: 4 5 6 7 8 9
     Union: 0 1 2 3 4 4 5 5 6 6 7 8 9
     Intersection: 4 5 6
     Complementary intersection: 0 1 2 3 7 8 9
     Subtraction: 0 1 2 3


Previous: map, Up: containers

5.9 The vector structure

The vector container is an implementation of array, with hysteresis in memory allocation.

NOTE This module was inspired by the book on C++ by Bjarne Stroustrup and by the STL C++ (Standard Template Library).
NOTE In the following documentation, when describing valid values for vector indexes, we denote a range of values with [min, max), where [ means inclusive bound and ( means exclusive bound.


Next: , Up: vector

5.9.1 How it's done

This container is heavyweight: its complexity is overkill for simple arrays with fixed size.

The vector structure can be allocated anywhere; the data area is always dynamically allocated and it is described by four pointers of type uint8_t *:

     first_allocated_slot    first_used_slot
     last_allocated_slot     last_used_slot

A slot is a section of the allocated memory that can hold an element; the dimension of the slots is configured at vector initialisation time. A free slot is a slot that does not contain an element; free slots can be present at the beginning and end of the allocated memory. A used slot is a slot that holds an element; used slots are always contiguous in the allocated memory.

Pointer usage charts

Pointers when some slot is used:

      free     used slots           free
     |'''''|.................|''''''''''''''''''''|
     |--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
     ^     ^              ^                    ^
     |     |              |                    last_allocated_slot
     |     |              |
     |     |              last_used_slot
     |     |
     |     first_used_slot
     |
     first_allocated_slot

pointers when the used area is attached to the beginning of the allocated memory:

           used slots           free
     |.................|''''''''''''''''''''''''''|
     |--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
     ^              ^                          ^
     |              |                          last_allocated_slot
     |              |
     |              last_used_slot
     |
     first_allocated_slot == first_used_slot

pointers when the used area is attached to the end of the allocated memory:

        free slots           used slots
     |''''''''''''''|.............................|
     |--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
     ^              ^                          ^
     |              |         last_allocated_slot == last_used_slot
     |              |
     |              first_used_slot
     |
     first_allocated_slot

pointers when the allocated memory is full (all the slots are used):

                      used slots
     |............................................|
     |--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
     ^                                         ^
     |                        last_allocated_slot == last_used_slot
     |
     |
     |
     first_allocated_slot == first_used_slot

pointers when only one slot is used:

           used
      free slot              free
     |'''''|..|'''''''''''''''''''''''''''''''''''|
     |--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
     ^     ^                                   ^
     |     |                                   last_allocated_slot
     |     |
     |     first_used_slot == last_used_slot
     |
     first_allocated_slot

pointers when the vector is empty and a non-zero pad area was configured:

       free pad           free slots
       area
     |'''''''''''|''''''''''''''''''''''''''''''''|
     |--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
     ^        ^  ^                             ^
     |        |  |                             last_allocated_slot
     |        |  first_used_slot
     |        |
     |        last_used_slot
     |
     first_allocated_slot

pointers when the vector is empty and a zero pad area was configured:

                         free slots
        |''''''''''''''''''''''''''''''''''''''''''''|
     |__|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|
     ^  ^                                         ^
     |  |                                         last_allocated_slot
     |  |
     |  first_allocated_slot == first_used_slot
     |
     last_used_slot
Pointers usage rules

The padding area, whose starting size can be configured, has the purpose of allowing fast insertion of elements at the beginning, with no reallocation of the memory block.


Next: , Previous: vector implementation, Up: vector

5.9.2 Type definitions

— Struct Typedef: ucl_vector_tag_t
— One Element Array Typedef: ucl_vector_t

The data type of the base structure; it must be allocated by the user code. vector memory for deatils on (re)allocation.

— Struct Typedef: ucl_vector_config_tag_t
— One Element Array Typedef: ucl_vector_config_t

Data structure used to configure a vector; it must be allocated by the user code; public fields description follows.

size_t slot_dimension
This is the array stride, which, in simple cases, is the size, in bytes, of the elements the vector will hold; it should be the result of the sizeof() operator applied to the data type, possibly normalised to a multiple of 4 or something.
size_t number_of_slots
The number of slots to allocate.
ucl_index_t step_up
The number of slots to add when reallocating the array to enlarge it, it must be a non–zero positive integer.
ucl_index_t step_down
The number of free slots that will trigger the reallocation of he array for restriction, it must be a non–zero positive integer.
ucl_index_t size_of_padding_area
The numer of slots to keep free, if possible, at the beginning of the array when moving elements (during insertion, deletion and reallocation), it must be non–negative integer.
ucl_comparison_t compar
Function and context used to compare elements; this function is used only by the sort operations, so this field can be left blank if no sort operations are required; typedefs compar for details.
ucl_memory_allocator_t allocator
The memory allocator to use for the data area; memory typedefs for details.

— Struct Typedef: ucl_vector_array_t

Holds an array of vectors. Public slots:

size_t number_of_vectors
the number of vectors in the array;
ucl_vector_tag_t ** vectors
array of pointers to vectors; this type implies no assumption upon the origin of the array memory, it can be statically or dynamically allocated, or it can be on the stack.

To declare an array of vectors we can do:

          #define NUMBER  1000
          
          ucl_vector_tag_t *    vectors[NUMBER];
          ucl_vector_array_t    array = {
            .number_of_vectors = NUMBER,
            .vectors           = vectors
          };


Next: , Previous: vector typedefs, Up: vector

5.9.3 Creating and destroying vectors

The construction of a new vector is a 3–step sequence: declaration, configuration, allocation:

     ucl_vector_config_t     C;
     ucl_vector_t            V;
     size_t  slot_dimension  = ...;
     size_t  number_of_slots = ...;
     
     ucl_vector_initialise_config(C, slot_dimension, number_of_slots);
     ucl_vector_alloc(V, C);

if we want to set custom values:

     ucl_vector_config_t     C;
     ucl_vector_t            V;
     size_t  slot_dimension  =   16;
     size_t  number_of_slots = 1024;
     
     ucl_vector_initialise_config(C, slot_dimension, number_of_slots);
     C->step_up              = 128;
     C->step_down            = 264;
     C->size_of_padding_area =  32;
     ucl_vector_alloc(V, C);
Configuration functions

After the invocation to the configuration functions, the user's code may override the default values by explicitly setting them before invoking the allocator function. All the functions select ucl_memory_alloc() as allocation function and set to zero the comparison structure.

— Function: void ucl_vector_initialise_config (ucl_vector_config_t C, size_t slot_dimension, size_t number_of_slots)

Initialise a vector configuration structure with default values.

— Function: void ucl_vector_initialise_config_buffer (ucl_vector_config_t C)

Initialise a vector configuration structure for a vector used as byte buffer.

— Function: void ucl_vector_initialise_config_hash (ucl_vector_config_t C)

Initialise a vector configuration structure for a vector used as hash table buckets collector.

— Function: void ucl_vector_initialise_config_dfs (ucl_vector_config_t C)

Initialise a vector configuration structure for a vector used as depth–first search data for the graph container.

Default values

The following are the default values ucl_vector_initialise_config() puts into the ucl_vector_config_t structure: a set of preprocessor symbols declared in ucl.h. The declarations allow overriding, they are in the form:

     #ifndef UCL_VECTOR_DEFAULT_STEP_UP
     #  define UCL_VECTOR_DEFAULT_STEP_UP     8
     #endif
— Macro: UCL_VECTOR_DEFAULT_STEP_UP 8

Default value for the step_up structure field.

— Macro: UCL_VECTOR_DEFAULT_STEP_DOWN 10

Default value for the step_down structure field.

— Macro: UCL_VECTOR_DEFAULT_PAD 3

Default value for the size_of_padding_area structure field.

Construction and destruction functions
— Function: void ucl_vector_alloc (ucl_vector_t V, ucl_vector_config_t C)

Allocate memory with the selected UCL allocator and initialise the fields of V.

If the step_up field holds a value greater than the step_down field: the step_down field is changed to step_up+1. vector memory for details.

— Function: void ucl_vector_free (ucl_vector_t V)

Release the memory allocate in V and set to zero all its fields.

— Function: ucl_bool_t ucl_vector_running (const ucl_vector_t V)

Return true if the vector has been constructed.

Inspection functions
— Function: size_t ucl_vector_number_of_step_up_slots (const ucl_vector_t V)

Return the number of stup up slots.

— Function: size_t ucl_vector_number_of_step_down_slots (const ucl_vector_t V)

Return the number of step down slots.

— Function: size_t ucl_vector_number_of_padding_slots (const ucl_vector_t V)

Return the number of padding slots.

Updating configuration functions

The following functions can be applied to an already constructed vector.

— Function: void ucl_vector_update_number_of_step_up_slots (ucl_vector_t V, size_t step_up)

Update the number of the step up slots.

— Function: void ucl_vector_update_number_of_step_down_slots (ucl_vector_t V, size_t step_down)

Update the number of the step down slots.

— Function: void ucl_vector_update_number_of_padding_slots (ucl_vector_t V, size_t padding)

Update the number of the padding slots.

— Function: void ucl_vector_set_compar (ucl_vector_t V, ucl_comparison_t compar)

Register the function+context used to compare elements.

Special functions
— Function: void ucl_vector_mark_all_slots_as_used (ucl_vector_t V)

Set the fields of V to describe a vector that uses all the allocated memory. This is for special vector usage.

— Function: void ucl_vector_mark_allocated_range_as_used (ucl_vector_t V, ucl_range_t range)

Mark a range of slots as used. This destroys the previous concept of used slots. Notice that range is relative to the allocated slots, not to the previously used slots.

— Function: void ucl_vector_reset (ucl_vector_t V)

Reset the internal fields so that the vector appears to be empty. The allocated slots memory is not touched.

— Function: void ucl_vector_clean (ucl_vector_t V)

Set all the allocated memory to null bytes, without touching anything else.

— Function: void ucl_vector_swallow_block (ucl_vector_t V, ucl_vector_config_t C, ucl_block_t block)

A replacement for ucl_vector_alloc() that takes an already allocated block as data area; it is mandatory for the size of the block to be an integer multiple of the slot's dimension. The vector is initialised to be full: all the slots are marked as used.

The responsibility of the block memory is transferred to the vector, so the block must be freed only by calling ucl_vector_free(); this means that the memory will be freed by the allocator registered in C.


Next: , Previous: vector creation, Up: vector

5.9.4 Converting indexes to pointers


Next: , Up: vector indexes
5.9.4.1 Index to pointer conversion
— Function: void * ucl_vector_index_to_slot (const ucl_vector_t V, ucl_index_t index)

Convert index into the corresponding pointer to a slot in the vector. Return a pointer to the selected slot, or NULL if the selected index is out of range. The range of valid values for index is [0, size), where size is the return value of ucl_vector_size().

Applying ucl_vector_enlarge() or ucl_vector_restrict() to V invalidates the return value of this function.

Example:

          ucl_vector_config_t     C;
          ucl_vector_t            V;
          int *                   P;
          int                     D;
          
          ucl_vector_initialise_config(C, sizeof(int), 1024);
          ucl_vector_alloc(V, C);
          fill_with_values(V);
          
          P = ucl_vector_index_to_slot(V, 13);
          if (P)
            D = *P;
          else
            error();
— Function: void * ucl_vector_index_to_new_slot (const ucl_vector_t V, ucl_index_t index)

Convert index into the corresponding pointer to a slot in the vector. This is different from ucl_vector_index_to_slot() in that the requested position can be one unit greater than the last position in the vector: that way the returned value can be used with ucl_vector_insert() to append an element to the end of the vector.

Return a pointer to the selected slot, or NULL if the selected index is out of range. The range of valid values for index is [0, size], where size is the return value of ucl_vector_size().

Applying ucl_vector_enlarge() or ucl_vector_restrict() to V invalidates the return value of this function. When adding a new slot: we have to make room for the new slot before attempting to convert the index to the slot's pointer.

Example:

          ucl_vector_config_t     C;
          ucl_vector_t            V;
          int *                   P;
          int                     D;
          
          ucl_vector_initialise_config(C, sizeof(int), 1024);
          ucl_vector_alloc(V, C);
          fill_with_values(V);
          
          ucl_vector_enlarge(V);
          P = ucl_vector_index_to_new_slot(V, 13);
          if (P)
            D = *P;
          else
            error();
— Function: void * ucl_vector_front (const ucl_vector_t V)

A wrapper for ucl_vector_index_to_slot() that returns a pointer to the first element in the array.

— Function: void * ucl_vector_back (const ucl_vector_t V)

A wrapper for ucl_vector_index_to_slot() that returns a pointer to the last element in the array.


Next: , Previous: vector indexes i2p, Up: vector indexes
5.9.4.2 Pointer to index conversion
— Function: ucl_index_t ucl_vector_last_index (const ucl_vector_t V)

Return the index of the last element.

— Function: ucl_index_t ucl_vector_slot_to_index (const ucl_vector_t V, const void * pointer_to_slot_p)

Return the index corresponding to a pointer to slot. It is the inverse of ucl_vector_index_to_slot().


Next: , Previous: vector indexes p2i, Up: vector indexes
5.9.4.3 Validating indexes
— Function: ucl_bool_t ucl_vector_pointer_is_valid_slot (const ucl_vector_t V, const void * pointer_to_slot_p)

Return true if the pointer is a valid slot pointer, else return false.

— Function: ucl_bool_t ucl_vector_index_is_valid (const ucl_vector_t V, ucl_index_t index)

Return true if index is a valid index for the vector.

— Function: ucl_bool_t ucl_vector_index_is_valid_new (const ucl_vector_t V, ucl_index_t index)

Return true if index is a valid index for a new slot of the vector.


Next: , Previous: vector indexes validation, Up: vector indexes
5.9.4.4 Range functions
— Function: ucl_bool_t ucl_vector_range_is_valid (const ucl_vector_t V, ucl_range_t R)

Return true if R, interpreted as inclusive range of indexes, is valid for V.

— Function: ucl_range_t ucl_vector_range (const ucl_vector_t V)

Return the inclusive range of indexes representing the whole vector.

— Function: ucl_range_t ucl_vector_range_from_position_to_end (const ucl_vector_t V, ucl_index_t position)

Return the inclusive range of indexes from position to the end of the vector. position must be a valid index for V.

Notice that to build the range of indexes from the beginning of a vector to a selected position we just need to do:

     ucl_range_t     range;
     
     ucl_range_set_min_max(range, 0, position);
— Function: ucl_range_t ucl_vector_range_from_end_to_position (const ucl_vector_t V, ucl_index_t position)

Return the inclusive range of indexes from the end of the vector to position. position must be greater or equal to the size of V.

The returned range of indexes is invalid for V, but it can be used to append new elements to it; to add slots from the end to index 15 included:

          ucl_vector_config_t     C;
          ucl_vector_t            V;
          int *                   P;
          ucl_range_t             R;
          ucl_index_t             i;
          
          ucl_vector_initialise_config(C, sizeof(int), 10);
          ucl_vector_alloc(V, C);
          fill_with_10_values(V);
          
          R = ucl_vector_range_from_end_to_position(V, 15);
          for (i=ucl_range_min(T); i<=ucl_range_max(R); ++i)
            {
              ucl_vector_enlarge(V);
              P = ucl_vector_index_to_new_slot(V, i);
              ...
            }
— Function: ucl_range_t ucl_vector_range_from_end_with_span (const ucl_vector_t V, size_t span)

Return the inclusive range of indexes from the end of the vector with span.

The returned range of indexes is invalid for V, but it can be used to append new elements to it; to add 5 slots to the end:

          ucl_vector_config_t     C;
          ucl_vector_t            V;
          int *                   P;
          ucl_range_t             R;
          ucl_index_t             i;
          
          ucl_vector_initialise_config(C, sizeof(int), 10);
          ucl_vector_alloc(V, C);
          fill_with_values(V);
          
          R = ucl_vector_range_from_end_with_span(V, 5);
          for (i=ucl_range_min(R); i<=ucl_range_max(R); ++i)
            {
              ucl_vector_enlarge(V);
              P = ucl_vector_index_to_new_slot(V, i);
            }

of course this is just an example, because it is much easiear to use ucl_vector_push_back().


Previous: vector indexes range, Up: vector indexes
5.9.4.5 Range/block conversion
— Function: ucl_block_t ucl_vector_block_from_range (const ucl_vector_t V, const ucl_range_t R)

Return a block referencing the slots selected by a range.

— Function: ucl_range_t ucl_vector_range_from_block (const ucl_vector_t V, const ucl_block_t B)

Return the range of slots referenced by a block.


Next: , Previous: vector indexes, Up: vector

5.9.5 Adding elements to a vector

— Function: void * ucl_vector_insert (ucl_vector_t V, void * target)

Insert an empty slot at a selected position. This function assumes that the array has a free slot to hold the new element: to make sure that this is true, a call to this function must be preceeded by a call to ucl_vector_enlarge().

The pointer to the slot must be the return value of a previous invocation to ucl_vector_index_to_new_slot().

This function tries to move less elements as possible to create an empty slot at the selected position. The return value is a pointer to the empty slot: it can be different from the value of the target argument.

— Function: void * ucl_vector_insert_sort (ucl_vector_t V, ucl_value_t data)

Find the position in the vector in which an element must be inserted to keep the array sorted and create a new slot there; the return value is a pointer to the empty slot.

This function assumes that:

  1. there's room in the vector to insert a new element;
  2. the array is sorted;
  3. a comparison function has been registered in V to be used to compare elements.

data must represent the element to be inserted, it's used as first argument to the comparison function. When a sequence of elements equal to data is present: the new slot is appended at its end.

The correct sequence of function calls required to insert a new element is: enlarge the vector, acquire the pointer, make a free slot, copy the value. Example of insertion:

     ucl_vector_t     vector;
     ucl_index_t      index;
     data_type_t      data;
     data_type_t *    ptr;
     
     ...
     
     data  = ...;
     index = ...;
     ucl_vector_enlarge(vector);
     ptr   = ucl_vector_index_to_new_slot(vector, index);
     ptr   = ucl_vector_insert(vector, ptr);
     *ptr  = data;

example of insert sort operation:

     ucl_vector_t     vector;
     ucl_index_t      index;
     data_type_t      data;
     data_type_t *    ptr;
     
     ...
     
     data  = ...;
     index = ...;
     ucl_vector_enlarge(vector);
     ptr   = ucl_vector_insert_sort(vector, &data);
     *ptr  = data;


Next: , Previous: vector adding, Up: vector

5.9.6 Removing elements from a vector

— Function: void ucl_vector_erase (ucl_vector_t V, void * slot)

Erase an element at a selected position: the slot is overwritten by moving less elements as possible. After the invocation: the pointer represented by slot is not guaranteed to be a pointer to a valid slot in the vector.

After the invocation of this function, it's possible to attempt a reallocation of the array to free some unused memory with a call to ucl_vector_restrict().

Example of data erasure:

     ucl_vector_t     V;
     ucl_index_t      index;
     data_type_t *    ptr;
     
     ...
     
     index = ...
     ptr   = ucl_vector_index_to_slot(V, index);
     ucl_vector_erase(V, ptr);
     ucl_vector_restrict(V);

example of data extraction:

     ucl_vector_t     V;
     ucl_index_t      index;
     data_type_t *    ptr;
     data_type_t      data;
     
     ...
     
     index = ...
     ptr   = ucl_vector_index_to_slot(V, index);
     data  = *ptr;
     ucl_vector_erase(V, ptr);
     ucl_vector_restrict(V);


Next: , Previous: vector removing, Up: vector

5.9.7 Various operations on a vector

Dimension inspection
— Function: size_t ucl_vector_size (const ucl_vector_t V)

Return a value representing the number of elements in the container.

— Function: size_t ucl_vector_slot_dimension (const ucl_vector_t V)

Return a value representing the size of the elements.

— Function: void * ucl_vector_increment_slot (const ucl_vector_t V, void * slot)

Interpret slot as a pointer to a slot of V and increment it so that it references the next element. This function does no bounds checking.

— Function: void * ucl_vector_decrement_slot (const ucl_vector_t V, void * slot)

Interpret slot as a pointer to a slot of V and decrement it so that it references the previous element. This function does no bounds checking.

Access to memory blocks
— Function: ucl_block_t ucl_vector_get_memory_block (const ucl_vector_t V)

Return a block referencing the allocated memory block.

— Function: ucl_block_t ucl_vector_get_data_block (const ucl_vector_t V)

Return a block referencing the data block: the used slots.

— Function: ucl_block_t ucl_vector_get_free_block_at_end (ucl_vector_t V, size_t count)

Return a block referencing count free slots at the end of the vector; the slots are still marked as free.

This function may haul the used slots inside the allocated memory, so slot pointers requested early will become invalid.

This function has to be called only if there are at least count free slots already allocated, see ucl_vector_enlarge_for_slots() (vector memory for details).

At present, blocks returned by this function cannot be converted to a range with ucl_vector_range_from_block().

— Function: ucl_block_t ucl_vector_get_free_block_at_beginning (ucl_vector_t V, size_t count)

Return a block referencing count free slots at the beginning of the vector; the slots are still marked as free.

This function may haul the used slots inside the allocated memory, so slot pointers requested early will become invalid.

This function has to be called only if there are at least count free slots already allocated, see ucl_vector_enlarge_for_slots() (vector memory for details).

At present, blocks returned by this function cannot be converted to a range with ucl_vector_range_from_block().

— Function: void ucl_vector_mark_as_used (ucl_vector_t V, ucl_block_t B)

Mark the range of free slots referenced by B as used. This function is meant to commit usage of blocks requested with ucl_vector_get_free_block_at_beginning() and ucl_vector_get_free_block_at_end().

B must be adjacent to the used slots inside the vector, its size must be an integer multiple of the slot dimension, its memory must be completely contained in the allocated vector memory.

Sorting
— Function: void ucl_vector_quick_sort (ucl_vector_t V)

Quick sort the vector using the C library function ucl_quicksort().

— Function: ucl_bool_t ucl_vector_sorted (ucl_vector_t V)

Return true if the vector is sorted. This function scans the whole vector, so it is slow.


Next: , Previous: vector ops, Up: vector

5.9.8 Finding elements

The functions described in this section search for an element in the vector, given a copy of the element to be found. The D argument represents the element to be found, it's used as first argument to the comparison function.

The return value is always a pointer to the found element in the array, or NULL if the element is not present.

— Function: void * ucl_vector_find (const ucl_vector_t V, const ucl_value_t D)

Find an element in the array with a linear search.

— Function: void * ucl_vector_binary_search (const ucl_vector_t V, const ucl_value_t D)

Find an element in the array with a binary search; this function assumes that the array is sorted.

— Function: void * ucl_vector_sort_find (const ucl_vector_t V, const ucl_value_t D)

Find an element in the array; this function assumes that the array is sorted. If there are few elements in the vector: a linear search is performed, else a binary search is used.


Next: , Previous: vector find, Up: vector

5.9.9 Iteration over a vector

It's easy to iterate over all the elements of a vector. Example of forward iteration:

     ucl_vector_t    V;
     data_type_t *   P;
     data_type_t *   end = ucl_vector_back(V);
     
     for (P = ucl_vector_front(V); P <= end; ++P)
       {
         ... *P ...
       }

example of backward iteration:

     ucl_vector_t    V;
     data_type_t *   P;
     data_type_t *   end = ucl_vector_front(V);
     
     for (P = ucl_vector_back(V); P >= end; --P)
       {
         ... *P ...
       }

nevertheless the following iterators are provided; iterators for details on iteration.

— Function: void ucl_vector_iterator_forward (const ucl_vector_t V, ucl_iterator_t I)

Initialise a forward iteration.

— Function: void ucl_vector_iterator_backward (const ucl_vector_t V, ucl_iterator_t I)

Initialise a backward iteration.

— Function: void ucl_vector_iterator_range_forward (const ucl_vector_t V, ucl_range_t R, ucl_iterator_t I)

Initialise a forward iteration over the inclusive range of elements selected by R. R must be a valid range for V, we can test this with ucl_vector_range_is_valid().

— Function: void ucl_vector_iterator_range_backward (const ucl_vector_t V, ucl_range_t R, ucl_iterator_t I)

Initialise a backward iteration over the inclusive range of elements selected by R. R must be a valid range for V, we can test this with ucl_vector_range_is_valid().


Next: , Previous: vector iteration, Up: vector

5.9.10 Allocating and freeing memory


Next: , Up: vector memory
5.9.10.1 Introduction to vector memory handling

The allocation policy for a vector container is ruled by the arguments stored into the configuration structure (vector creation). The rules are:

By default the UCL allocator is used (memory functions), but it is possible to register a vector–specific allocator.


Next: , Previous: vector memory intro, Up: vector memory
5.9.10.2 Enlarging allocated memory
— Function: void ucl_vector_enlarge (ucl_vector_t V)

To be used to make sure that at least one free slot exists.

Check if there are free slots in the allocated memory: if there are, nothing happens; else the array is reallocated and enlarged according to the reallocation rules.

An error reallocating memory does not corrupt the vector.

— Function: ucl_bool_t ucl_vector_will_enlarge (ucl_vector_t V)

Return true if the next call to ucl_vector_enlarge() will reallocate the vector.

— Function: size_t ucl_vector_enlarged_size (ucl_vector_t V)

Return the number of allocated slots after a reallocation for enlarging. This function returns a meaningful value only when ucl_vector_will_enlarge() returns true.

— Function: void ucl_vector_enlarge_for_slots (ucl_vector_t V, size_t required_free_slots)

To be used to make sure that there is room for at least the selected number of free slots.

Check if there are at least required_free_slots in the allocated memory: if there are, nothing happens; else the array is reallocated and enlarged to get enough room.

An error reallocating memory does not corrupt the vector.

— Function: void ucl_vector_enlarge_for_range (ucl_vector_t V, ucl_range_t R)

Make sure that there is enough memory to hold the inclusive range of indexes described by R. This works despite R being: already a valid range of indexes, completely beyond the upper index limits, across the current upper index limit.


Next: , Previous: vector memory enlarge, Up: vector memory
5.9.10.3 Restricting allocated memory
— Function: void ucl_vector_restrict (ucl_vector_t V)

Check if there are enough free slots in the allocated memory so that it's correct to restrict the array: if there aren't, nothing happens; else the array is reallocated and restricted according to the reallocation rules.

An error reallocating memory does not corrupt the vector.

— Function: ucl_bool_t ucl_vector_will_restrict (ucl_vector_t V)

Return true if the next call to ucl_vector_restrict() will reallocate the vector.

— Function: size_t ucl_vector_restricted_size (ucl_vector_t V)

Return the number of allocated slots after a reallocation for restricting. This function returns a meaningful value only when ucl_vector_will_restrict() returns true.


Previous: vector memory restrict, Up: vector memory
5.9.10.4 Miscellaneous memory functions
— Function: void ucl_vector_set_memory_to_zero (ucl_vector_t V)

Set all the slots to zero. This does not change the vector size: it is not like extracting all the elements.

— Function: size_t ucl_vector_number_of_free_slots (ucl_vector_t V)

Returns the number of allocated but currently unused slots. It is the number of elements that can be added without causing a memory reallocation.

— Function: void ucl_vector_register_allocator (ucl_vector_t V, ucl_memory_allocator_t A)

Register a new allocator.


Next: , Previous: vector memory, Up: vector

5.9.11 Using a vector as a priority queue

The vector structure provides all the functions required to implement a priority queue. This is a structure in which elements are associated with keys: when an element is added and the structure is kept sorted comparing its key with the keys of the elements already in the container.

Let's say we have declared a structure like this:

     typedef struct pair_t {
       key_t   key;
       val_t   val;
     } pair_t;

and a ucl_comparison_t function+context to compare keys.

If any time a pair_t must be inserted in the vector we use the ucl_vector_insert_sort() function to determine the insertion position, the elements will be kept sorted according to the key values and comparison algorithm.

Then ucl_vector_front() or ucl_vector_back() can be used to extract the element with lesser or greater key.


Previous: vector as pqueue, Up: vector

5.9.12 High level functions

The functions described in this section are built upon the basic ones; some of them invoke the enlarge/restrict memory functions.


Next: , Up: vector high
5.9.12.1 Stack and queue
— Function: void * ucl_vector_push_front (ucl_vector_t V)

Add a slot to the front of the vector and return a pointer to it.

This function invokes ucl_vector_enlarge().

— Function: void * ucl_vector_push_back (ucl_vector_t V)

Add a slot to the tail of the vector and return a pointer to it.

This function invokes ucl_vector_enlarge().

— Function: void ucl_vector_pop_front (ucl_vector_t V)

If the vector is not empty: erase the first slot, else do nothing.

This function invokes ucl_vector_restrict().

— Function: void ucl_vector_pop_back (ucl_vector_t V)

If the vector is not empty: erase the last slot, else do nothing.

This function invokes ucl_vector_restrict().

Notice that the “top” operations of the stack and queue are already implemented by ucl_vector_front() and ucl_vector_back().


Next: , Previous: vector high stack, Up: vector high
5.9.12.2 Appending data to a vector

In the following functions the dst vector must be an already allocated vector.

— Function: void ucl_vector_append_block (ucl_vector_t dst, const ucl_block_t B)

Append a block to the vector by copying data from B with memcpy(). The size of the block must be an integer multiple of the destination vector's slot dimension.

This function invokes ucl_vector_enlarge_for_slots().

— Function: void ucl_vector_append (ucl_vector_t dst, const ucl_vector_t src)

Append all the elements of src to the end of dst by copying data with memcpy(). If dst is empty: this operation is equivalent to duplicating src.

This function invokes ucl_vector_enlarge_for_slots().

— Function: void ucl_vector_append_range (ucl_vector_t dst, const ucl_vector_t src, ucl_range_t R)

Append the elements of src referenced by R to the end of dst by copying data with memcpy().

This function invokes ucl_vector_enlarge_for_slots().

— Function: void ucl_vector_append_more (ucl_vector_t dst, const ucl_vector_t src, ...)

Append elements from a set of vectors to the end of dst. The ... arguments are a list of ucl_vector_t values terminated by a NULL.

This function invokes ucl_vector_enlarge_for_slots().

Example:

          ucl_vector_t    dst, a, b, c, d;
          
          ...
          ucl_vector_append_more(dst, a, b, c, d, NULL);
— Function: void ucl_vector_append_more_from_array (ucl_vector_t dst, const ucl_vector_array_t * vectors)

Like ucl_vector_append_more() but takes source vectors from an array rather than from application parameters.


Next: , Previous: vector high append, Up: vector high
5.9.12.3 Inserting into a vector
— Function: void ucl_vector_insert_vector (ucl_vector_t dst, ucl_index_t offset, ucl_vector_t src)

Insert all the elements of src into dst at offset.

offset must be a valid value for ucl_vector_index_to_new_slot().

This function invokes ucl_vector_enlarge_for_slots().

— Function: void ucl_vector_insert_block (ucl_vector_t dst, ucl_index_t offset, const ucl_block_t B)

Insert the data referenced by B into dst at offset.

The size of B must be an integer multiple of the slot's dimension of dst. offset must be a valid value for ucl_vector_index_to_new_slot().

This function invokes ucl_vector_enlarge_for_slots().

— Function: void ucl_vector_insert_range (ucl_vector_t dst, ucl_index_t offset, const ucl_vector_t src, ucl_range_t R)

Insert the data referenced by the inclusive R of indexes from src into dst at offset.

The size of B must be an integer multiple of the slot's dimension of dst. offset must be a valid value for ucl_vector_index_to_new_slot().

This function invokes ucl_vector_enlarge_for_slots().


Next: , Previous: vector high insert, Up: vector high
5.9.12.4 Removing from a vector
— Function: void ucl_vector_erase_range (ucl_vector_t V, ucl_range_t R)

Erase all the elements in the selected range.

This function invokes ucl_vector_restrict().


Next: , Previous: vector high erase, Up: vector high
5.9.12.5 Setters and getters
— Function: void ucl_vector_copy_range (ucl_vector_t dst, ucl_index_t position, ucl_vector_t src, ucl_range_t src_range)

Copy slots referenced by src_range in src to position in dst; data in dst is overwritten.

position must be a valid index for dst. src_range must be valid for src. There must be enough slots after position in dst to hold the whole range from src.

— Function: void ucl_vector_set_block (ucl_vector_t dst, ucl_index_t position, ucl_block_t src)

Copy data from src into dst at position; data in dst is overwritten.

position must be a valid index for dst and enough slots must exist after it to accept the whole src block. The length of src must be an integer multiple of the slot's dimension in dst.

— Function: void ucl_vector_get_block (ucl_block_t dst, ucl_index_t position, ucl_vector_t src)

Copy data from src at position into dst, overwriting data.

position must be a valid index for dst and there must be enough slots in dst to fill the block. The length of src must be an integer multiple of the slot's dimension in dst.


Next: , Previous: vector high access, Up: vector high
5.9.12.6 Comparing vectors
— Function: int ucl_vector_compare_range (ucl_vector_t a, ucl_range_t range_a, ucl_vector_t b, ucl_range_t range_b)

Compare two ranges of elements in two vectors, element by element, using the comparison function of a. If the size of the ranges is not equal: only a number of elements equal to the lesser size is compared. The comparison stops at the first pair of elements for which the comparison function returns non–zero.

Works somewhat like strcmp(). Return:

0
if all the compared elements are equal;
+1
if, for the last compared pair, the element from a is greater than the last element from b;
-1
if, for the last compared pair, the element from a is lesser than the last element from b.

a can be equal to b.

— Function: ucl_bool_t ucl_vector_equal_range (ucl_vector_t a, ucl_range_t range_a, ucl_vector_t b, ucl_range_t range_b)

Wrapper for ucl_vector_compare_range() that returns true if the two ranges are equal.

— Function: int ucl_vector_compare (ucl_vector_t a, ucl_vector_t b)

Wrapper for ucl_vector_compare_range() that compares the whole vectors.

— Function: ucl_bool_t ucl_vector_equal (ucl_vector_t a, ucl_vector_t b)

Wrapper for ucl_vector_compare(): return true if the vectors are equal.


Previous: vector high compare, Up: vector high
5.9.12.7 Applying functions

The functions described in this section allow us to apply a function, in the form of a callback (typedefs callback), to each element in a vector or to each element in a range over a vector. The “for each” kind leaves to the callback the responsibility to produce a result, while the “map” kind produces a vector holding processed elements.

— Function: void ucl_vector_for_each (ucl_callback_t cb, ucl_vector_t V)

Apply the callback cb to each element in the vector V. The callback function is invoked with a pointer to the element's slot as custom value.

Example of callback that sums the values in a vector:

          void
          callback (ucl_value_t state, ucl_value_t custom)
          {
            int * accumulator_p   = state.ptr;
            int * slot            = custom.ptr;
          
            *accumulator_p += *slot;
          }
          
          int             accumulator = 0;
          ucl_callback_t  cb = {
            .func = callback,
            .data = { .ptr = &accumulator }
          };
          
          ucl_vector_t    V;
          ucl_vector_for_each(cb, V);

with this setup the operation is like a “fold”.

— Function: void ucl_vector_for_each_in_range (ucl_callback_t cb, ucl_range_t R, ucl_vector_t V)

Like ucl_vector_for_each(), but apply the callback only to the elements selected by the inclusive R.

Example of callback that sums the values in a vector's range:

          void
          callback (ucl_value_t state, ucl_value_t custom)
          {
            int * accumulator_p   = state.ptr;
            int * slot            = custom.ptr;
          
            *accumulator_p += *slot;
          }
          
          int             accumulator = 0;
          ucl_callback_t  cb = {
            .func = callback,
            .data = { .ptr = &accumulator }
          };
          ucl_range_t     range;
          
          ucl_vector_t    V;
          ucl_range_set_min_max(range, 3, 8);
          ucl_vector_for_each_in_range(cb, range, V);
— Function: void ucl_vector_for_each_multiple (ucl_callback_t cb, ucl_vector_t V, ...)

Like ucl_vector_for_each(), but apply the callback to an array of pointers to slots from the vectors used as arguments.

This function must be invoked with a list of ucl_vector_t arguments ended by a NULL.

The callback function is invoked with a pointer to a ucl_array_of_pointers_t structure as custom value:

ucl_value_t data
the t_unsigned_int field is set to the index of the slot currently visited;
size_t number_of_slots
the number of slots which is equal to the number of vectors used as arguments;
void ** slots
a pointer to an array of pointers to the slots.

The iteration stops when the end of the shortest vector is found.

Example:

          static void
          callback (ucl_value_t state, ucl_value_t custom)
          {
            int *                         sums    = state.ptr;
            ucl_array_of_pointers_t *     slots   = custom.ptr;
            int **                        values  = (int **)slots->slots;
          
            for (size_t i=0; i<slots->number_of_slots; ++i)
              sums[slots->data.unum] += *values[i];
          }
          
          int            sums[5] = { 0, 0, 0, 0, 0 };
          ucl_callback_t cb = {
            .func = callback,
            .data = { .ptr = &sums }
          };
          
          ucl_vector_t   A, B, C;
          ucl_vector_for_each_multiple(cb, A, B, C, NULL);
— Function: void ucl_vector_for_each_multiple_from_array (ucl_callback_t cb, ucl_vector_array_t * vectors)

Like ucl_vector_for_each_multiple() but the vectors are given in an array rather than a list of arguments.

— Function: void ucl_vector_map (ucl_vector_t R, ucl_callback_t cb, ucl_vector_t V)

Apply the callback cb to each element in the vector V and store the result in the vector R. New slots are added to R using ucl_vector_push_back().

The callback function is invoked with a pointer to a ucl_array_of_pointers_t structure as custom value:

ucl_value_t data
the t_unsigned_int field is set to the index of the slot currently visited;
size_t number_of_slots
the number of slots: always 2 for this function;
void ** slots
a pointer to an array of pointers to the slots; the first element (slots[0]) references the result slot, while the second element (slots[1]) references the operand slot.

Example of callback that negates the values:

          void
          callback (ucl_value_t state UCL_UNUSED, ucl_value_t custom)
          {
            ucl_array_of_pointers_t * slots   = custom.ptr;
            int *                     result  = slots.slots[0];
            int *                     operand = slots.slots[1];
          
            *result = - *operand;
          }
          
          ucl_callback_t  cb = {
            .func = callback,
            .data = { .ptr = NULL }
          };
          
          ucl_vector_t    result, operand;
          ucl_vector_map(result, cb, operand);
— Function: void ucl_vector_map_range (ucl_vector_t dst, ucl_callback_t cb, ucl_range_t R, ucl_vector_t src)

Like ucl_vector_map(), but apply the callback only to the elements selected by the inclusive R.

— Function: void ucl_vector_map_multiple (ucl_vector_t R, ucl_callback_t cb, ucl_vector_t first, ...)

Like ucl_vector_map(), but apply the callback to an array of pointers to slots from the vectors used as arguments.

The function must be invoked with a list of ucl_vector_t arguments ended by NULL.

The callback function is invoked with a pointer to a ucl_array_of_pointers_t structure as custom value:

ucl_value_t data
the t_unsigned_int field is set to the index of the slot currently visited;
size_t number_of_slots
the number of slots which is equal to 1 plus the number of vectors used as arguments;
void ** slots
a pointer to an array of pointers to the slots; the first element (slots[0]) references the result slots, while the following elements (slots[1], slots[2], ...) reference the operands.

The iteration stops when the end of the shortest operand vector is found.

Example of callback that computes the sum of vectors:

          static void
          callback (ucl_value_t state UCL_UNUSED, ucl_value_t custom)
          {
            ucl_array_of_pointers_t *  slots  = custom.ptr;
            int **                     values = (int **)slots->slots;
          
            *values[0] = 0;
            for (size_t i=1; i<slots->number_of_slots; ++i)
              *values[0] += *values[i];
          }
          
          ucl_callback_t  cb = {
            .func = callback,
            .data = { .ptr = NULL }
          };
          
          ucl_vector_t    R, A, B, C;
          ucl_vector_map_multiple(R, cb, A, B, C, NULL);
— Function: void ucl_vector_map_multiple_from_array (ucl_vector_t R, ucl_callback_t cb, ucl_vector_array_t * vectors)

Like ucl_vector_map_multiple() but the vectors are given in an array rather than a list of arguments.


Next: , Previous: containers, Up: Top

6 Container iteration

Each container has its iteration constructors that must be invoked explicitly, but the functions used to do the actual iterations and to access the objects are accessed through a set of macros.

— Struct Typedef: ucl_iterator_tag_t
— One–Element Array Typedef: ucl_iterator_t

Base structure for all the iterators.

— Function: ucl_bool_t ucl_iterator_more (ucl_iterator_t iterator)

Return true if there are more elements to iterate, false if the iteration is over.

— Function: void ucl_iterator_next (ucl_iterator_t iterator)

Advance the iteration.

— Function: void * ucl_iterator_ptr (ucl_iterator_t iterator)

Return a pointer referencing the current value. If the iteration is already over: return NULL.

6.1 Examples

Example of iterator usage:

     ucl_value_t       val;
     ucl_iterator_t    iterator;
     ucl_map_link_t *  link_p;
     
     ...
     
     for (ucl_map_iterator_inorder(this, iterator);
          ucl_iterator_more(iterator);
          ucl_iterator_next(iterator))
       {
         link_p = ucl_iterator_ptr(iterator);
         val = ucl_map_getval(link_p);
       }


Next: , Previous: iterators, Up: Top

7 Miscellaneous functions


Next: , Up: misc

7.1 Version functions

— Function: const char * ucl_version (void)

Return a pointer to a string representing the version number.

— Function: unsigned ucl_interface_major_version (void)

Return a number representing the library interface major version number.

— Function: unsigned ucl_interface_minor_version (void)

Return a number representing the library interface minor version number.


Next: , Previous: misc version, Up: misc

7.2 Comparison functions

All the following function have prototype matching ucl_comparison_fun_t; for all of them data is unused and the return value is: 0 if a equals b; 1 if a is greater than b; -1 if a is lesser than b.

— Function: int ucl_compare_int_fun (ucl_value_t data, const ucl_value_t a, const ucl_value_t b)

Compare the t_int fields of two values.

— Function: int ucl_compare_unsigned_int_fun (ucl_value_t data, const ucl_value_t a, const ucl_value_t b)

Compare the unum fields of two values.

— Function: int ucl_compare_string_fun (ucl_value_t data, const ucl_value_t a, const ucl_value_t b)

Wrapper for strcmp().

— Function: int ucl_compare_int_pointer_fun (ucl_value_t data, const ucl_value_t a, const ucl_value_t b)

Interpret the ptr fields of a and b as pointers of type int: compare the two referenced numbers by invoking ucl_compare_int().

— Variable: const ucl_comparison_t ucl_compare_int
— Variable: const ucl_comparison_t ucl_compare_unsigned_int
— Variable: const ucl_comparison_t ucl_compare_string
— Variable: const ucl_comparison_t ucl_compare_int_pointer

Statically allocated comparison structures which use the comparison functions described above.


Previous: misc compar, Up: misc

7.3 Sorting functions

— Function: void ucl_quicksort (void * array, size_t count, size_t size, ucl_comparison_t compar)

Like the standard qsort(), but makes use of the comparison function and context in compar. array is an array of count elements of size.

NOTE This is indeed the qsort() function from the GNU C Library version 2.4, modified to use compar.


Next: , Previous: Documentation License, Up: Top

Appendix A Bibliography and references

Ellis Horowitz, Sartaj Sahni and Susan Anderson–Freed. Strutture dati in C. McGraw–Hill, 1993.

Bjarne Stroustroup. C++. Addison-Wesley, 1997.


Next: , Previous: misc, Up: Top

Appendix B GNU General Public License

Version 3, 29 June 2007
     Copyright © 2007 Free Software Foundation, Inc. http://fsf.org/
     
     Everyone is permitted to copy and distribute verbatim copies of this
     license document, but changing it is not allowed.

Preamble

The GNU General Public License is a free, copyleft license for software and other kinds of works.

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program—to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.

Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS

  1. Definitions.

    “This License” refers to version 3 of the GNU General Public License.

    “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

    “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.

    To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.

    A “covered work” means either the unmodified Program or a work based on the Program.

    To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.

    To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

    An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.

  2. Source Code.

    The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

    A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.

    The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.

    The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.

    The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

    The Corresponding Source for a work in source code form is that same work.

  3. Basic Permissions.

    All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.

    You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.

    Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

  4. Protecting Users' Legal Rights From Anti-Circumvention Law.

    No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.

    When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.

  5. Conveying Verbatim Copies.

    You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.

    You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.

  6. Conveying Modified Source Versions.

    You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

    1. The work must carry prominent notices stating that you modified it, and giving a relevant date.
    2. The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
    3. You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
    4. If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.

    A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

  7. Conveying Non-Source Forms.

    You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

    1. Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
    2. Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
    3. Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
    4. Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
    5. Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.

    A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.

    A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.

    “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.

    If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).

    The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.

    Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.

  8. Additional Terms.

    “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.

    When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.

    Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

    1. Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
    2. Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
    3. Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
    4. Limiting the use for publicity purposes of names of licensors or authors of the material; or
    5. Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
    6. Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.

    All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.

    If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.

    Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

  9. Termination.

    You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

    However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

    Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

    Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.

  10. Acceptance Not Required for Having Copies.

    You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.

  11. Automatic Licensing of Downstream Recipients.

    Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.

    An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.

    You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.

  12. Patents.

    A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.

    A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.

    Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.

    In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.

    If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.

    If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.

    A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.

    Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.

  13. No Surrender of Others' Freedom.

    If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.

  14. Use with the GNU Affero General Public License.

    Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.

  15. Revised Versions of this License.

    The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

    Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.

    If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.

    Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.

  16. Disclaimer of Warranty.

    THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  17. Limitation of Liability.

    IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

  18. Interpretation of Sections 15 and 16.

    If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

     one line to give the program's name and a brief idea of what it does.
     Copyright (C) year name of author
     
     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation, either version 3 of the License, or (at
     your option) any later version.
     
     This program is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.
     
     You should have received a copy of the GNU General Public License
     along with this program.  If not, see http://www.gnu.org/licenses/.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:

     program Copyright (C) year name of author
     This program comes with ABSOLUTELY NO WARRANTY; for details type ‘show w’.
     This is free software, and you are welcome to redistribute it
     under certain conditions; type ‘show c’ for details.

The hypothetical commands ‘show w’ and ‘show c’ should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.

You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see http://www.gnu.org/licenses/.

The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read http://www.gnu.org/philosophy/why-not-lgpl.html.


Next: , Previous: Package License, Up: Top

Appendix C GNU Free Documentation License

Version 1.3, 3 November 2008
     Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.
     http://fsf.org/
     
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.
  1. PREAMBLE

    The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

    This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

    We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

  2. APPLICABILITY AND DEFINITIONS

    This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.

    A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

    A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

    The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.

    The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.

    A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”.

    Examples of suitable formats for Transparent copies include plain ascii without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.

    The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.

    The “publisher” means any person or entity that distributes copies of the Document to the public.

    A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition.

    The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

  3. VERBATIM COPYING

    You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

    You may also lend copies, under the same conditions stated above, and you may publicly display copies.

  4. COPYING IN QUANTITY

    If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

    If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

    If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

    It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

  5. MODIFICATIONS

    You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

    1. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
    2. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
    3. State on the Title page the name of the publisher of the Modified Version, as the publisher.
    4. Preserve all the copyright notices of the Document.
    5. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.
    6. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
    7. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.
    8. Include an unaltered copy of this License.
    9. Preserve the section Entitled “History”, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled “History” in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
    10. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the “History” section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
    11. For any section Entitled “Acknowledgements” or “Dedications”, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
    12. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
    13. Delete any section Entitled “Endorsements”. Such a section may not be included in the Modified Version.
    14. Do not retitle any existing section to be Entitled “Endorsements” or to conflict in title with any Invariant Section.
    15. Preserve any Warranty Disclaimers.

    If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

    You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

    You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

    The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.

  6. COMBINING DOCUMENTS

    You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.

    The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

    In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.”

  7. COLLECTIONS OF DOCUMENTS

    You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

    You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

  8. AGGREGATION WITH INDEPENDENT WORKS

    A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.

    If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

  9. TRANSLATION

    Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.

    If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

  10. TERMINATION

    You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.

    However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

    Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

    Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.

  11. FUTURE REVISIONS OF THIS LICENSE

    The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.

    Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document.

  12. RELICENSING

    “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A “Massive Multiauthor Collaboration” (or “MMC”) contained in the site means any set of copyrightable works thus published on the MMC site.

    “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.

    “Incorporate” means to publish or republish a Document, in whole or in part, as part of another Document.

    An MMC is “eligible for relicensing” if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.

    The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.

ADDENDUM: How to use this License for your documents

To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:

       Copyright (C)  year  your name.
       Permission is granted to copy, distribute and/or modify this document
       under the terms of the GNU Free Documentation License, Version 1.3
       or any later version published by the Free Software Foundation;
       with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
       Texts.  A copy of the license is included in the section entitled ``GNU
       Free Documentation License''.

If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with...Texts.” line with this:

         with the Invariant Sections being list their titles, with
         the Front-Cover Texts being list, and with the Back-Cover Texts
         being list.

If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.

If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.


Next: , Previous: references, Up: Top

Appendix D An entry for each concept


Next: , Previous: concept index, Up: Top

Appendix E An entry for each function


Next: , Previous: function index, Up: Top

Appendix F An entry for each type.


Previous: type index, Up: Top

Appendix G An entry for each variable.

Table of Contents