Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Contact Us
Online Help
Domain Status
Man Pages

Virtual Servers

Topology Map

Server Agreement
Year 2038

USA Flag



Man Pages

Manual Reference Pages  -  LIBUCL (3)


B]ucl_parser_new], B]ucl_parser_register_macro], B]ucl_parser_register_variable], B]ucl_parser_add_chunk], B]ucl_parser_add_string], B]ucl_parser_add_file], B]ucl_parser_get_object], B]ucl_parser_get_error], B]ucl_parser_free], B]ucl_pubkey_add], B]ucl_parser_set_filevars] - universal configuration library parser and utility functions


     Parser functions
     Emitting functions
     Conversion functions
     Generation functions
     Iteration functions
     Validation functions
     Utility functions
Parser Functions
     Parser usage example
Emitting Functions
Conversion Functions
Generation Functions
     Primitive objects generation
Iteration Functions
     Safe iterators API
Validation Functions


UCL library (libucl, -lucl)


C]#include <ucl.h>]


Libucl is a parser and C]C] API to parse and generate C]ucl] objects. Libucl consist of several groups of functions:

    Parser functions

Used to parse C]ucl] files and provide interface to extract C]ucl] object. Currently, C]libucl] can parse only full C]ucl] documents, for instance, it is impossible to parse a part of document and therefore it is impossible to use C]libucl] as a streaming parser. In future, this limitation can be removed.

    Emitting functions

Convert C]ucl] objects to some textual or binary representation. Currently, libucl supports the following exports:
[bu] C]JSON] - valid json format (can possibly lose some original data, such as implicit arrays)
[bu] C]Config] - human-readable configuration format (lossless)
[bu] C]YAML] - embedded yaml format (has the same limitations as C]json] output)

    Conversion functions

Help to convert C]ucl] objects to C types. These functions are used to convert C]ucl_object_t] to C primitive types, such as numbers, strings or boolean values.

    Generation functions

Allow creation of C]ucl] objects from C types and creating of complex C]ucl] objects, such as hashes or arrays from primitive C]ucl] objects, such as numbers or strings.

    Iteration functions

Iterate over C]ucl] complex objects or over a chain of values, for example when a key in an object has multiple values (that can be treated as implicit array or implicit consolidation).

    Validation functions

Validation functions are used to validate some object C]obj] using json-schema compatible object C]schema]. Both input and schema must be UCL objects to perform validation.

    Utility functions

Provide basic utilities to manage C]ucl] objects: creating, removing, retaining and releasing reference count and so on.


Parser functions operates with C]struct ucl_parser].


struct ucl_parser* ucl_parser_new (int flags);

Creates new parser with the specified flags:
[bu] C]UCL_PARSER_KEY_LOWERCASE] - lowercase keys parsed
[bu] C]UCL_PARSER_ZEROCOPY] - try to use zero-copy mode when reading files (in zero-copy mode text chunk being parsed without copying strings so it should exist till any object parsed is used)
[bu] C]UCL_PARSER_NO_TIME] - treat time values as strings without parsing them as floats


void ucl_parser_register_macro (struct ucl_parser *parser,
    const char *macro, ucl_macro_handler handler, void* ud);

Register new macro with name .C]macro] parsed by handler C]handler] that accepts opaque data pointer C]ud]. Macro handler should be of the following type:
bool (*ucl_macro_handler) (const unsigned char *data,
    size_t len, void* ud);‘

Handler function accepts macro text
C]data] of length C]len] and the opaque pointer C]ud]. If macro is parsed successfully the handler should return C]true]. C]false] indicates parsing failure and the parser can be terminated.


void ucl_parser_register_variable (struct ucl_parser *parser,
    const char *var, const char *value);

Register new variable $C]var] that should be replaced by the parser to the C]value] string.


bool ucl_parser_add_chunk (struct ucl_parser *parser,
    const unsigned char *data, size_t len);

Add new text chunk with C]data] of length C]len] to the parser. At the moment, C]libucl] parser is not a streamlined parser and chunk I]must] contain the I]valid] ucl object. For example, this object should be valid:
{ "var": "value" }

while this one won[aq]t be parsed correctly:
{ "var":

This limitation may possible be removed in future.


bool ucl_parser_add_string (struct ucl_parser *parser,
    const char *data, size_t len);

This function acts exactly like C]ucl_parser_add_chunk] does but if C]len] argument is zero, then the string C]data] must be zero-terminated and the actual length is calculated up to C]\0] character.


bool ucl_parser_add_file (struct ucl_parser *parser,
    const char *filename);

Load file C]filename] and parse it with the specified C]parser]. This function uses C]mmap] call to load file, therefore, it should not be C]shrunk] during parsing. Otherwise, C]libucl] can cause memory corruption and terminate the calling application. This function is also used by the internal handler of C]include] macro, hence, this macro has the same limitation.


ucl_object_t* ucl_parser_get_object (struct ucl_parser *parser);

If the C]ucl] data has been parsed correctly this function returns the top object for the parser. Otherwise, this function returns the C]NULL] pointer. The reference count for C]ucl] object returned is increased by one, therefore, a caller should decrease reference by using C]ucl_object_unref] to free object after usage.


const char *ucl_parser_get_error(struct ucl_parser *parser);

Returns the constant error string for the parser object. If no error occurred during parsing a C]NULL] object is returned. A caller should not try to free or modify this string.


void ucl_parser_free (struct ucl_parser *parser);

Frees memory occupied by the parser object. The reference count for top object is decreased as well, however if the function C]ucl_parser_get_object] was called previously then the top object won[aq]t be freed.


bool ucl_pubkey_add (struct ucl_parser *parser,
    const unsigned char *key, size_t len);

This function adds a public key from text blob C]key] of length C]len] to the C]parser] object. This public key should be in the C]PEM] format and can be used by C].includes] macro for checking signatures of files included. C]Openssl] support should be enabled to make this function working. If a key cannot be added (e.g. due to format error) or C]openssl] was not linked to C]libucl] then this function returns C]false].


bool ucl_parser_set_filevars (struct ucl_parser *parser,
    const char *filename, bool need_expand);

Add the standard file variables to the C]parser] based on the C]filename] specified:
[bu] C]$FILENAME] - a filename of C]ucl] input
[bu] C]$CURDIR] - a current directory of the input
For example, if a C]filename] param is C]../something.conf] then the variables will have the following values:
[bu] C]$FILENAME] - "../something.conf"
[bu] C]$CURDIR] - ".."
C]need_expand] parameter is C]true] then all relative paths are expanded using C]realpath] call. In this example if C]..] is C]/etc/dir] then variables will have these values:
[bu] C]$FILENAME] - "/etc/something.conf"
[bu] C]$CURDIR] - "/etc"

    Parser usage example

The following example loads, parses and extracts C]ucl] object from stdin using C]libucl] parser functions (the length of input is limited to 8K):
char inbuf[8192];
struct ucl_parser *parser = NULL;
int ret = 0, r = 0;
ucl_object_t *obj = NULL;
FILE *in;

in = stdin; parser = ucl_parser_new (0); while (!feof (in) && r < (int)sizeof (inbuf)) { r += fread (inbuf + r, 1, sizeof (inbuf) - r, in); } ucl_parser_add_chunk (parser, inbuf, r); fclose (in);

if (ucl_parser_get_error (parser)) { printf ("Error occurred: %s\n", ucl_parser_get_error (parser)); ret = 1; } else { obj = ucl_parser_get_object (parser); }

if (parser != NULL) { ucl_parser_free (parser); } if (obj != NULL) { ucl_object_unref (obj); } return ret; ]


Libucl can transform UCL objects to a number of tectual formats:
[bu] configuration (C]UCL_EMIT_CONFIG]) - nginx like human readable configuration file where implicit arrays are transformed to the duplicate keys
[bu] compact json: C]UCL_EMIT_JSON_COMPACT] - single line valid json without spaces
[bu] formatted json: C]UCL_EMIT_JSON] - pretty formatted JSON with newlines and spaces
[bu] compact yaml: C]UCL_EMIT_YAML] - compact YAML output
Moreover, libucl API allows to select a custom set of emitting functions allowing efficient and zero-copy output of libucl objects. Libucl uses the following structure to support this feature:
struct ucl_emitter_functions {
    /** Append a single character */
    int (*ucl_emitter_append_character) (unsigned char c, size_t nchars, void *ud);
    /** Append a string of a specified length */
    int (*ucl_emitter_append_len) (unsigned const char *str, size_t len, void *ud);
    /** Append a 64 bit integer */
    int (*ucl_emitter_append_int) (int64_t elt, void *ud);
    /** Append floating point element */
    int (*ucl_emitter_append_double) (double elt, void *ud);
    /** Opaque userdata pointer */
    void *ud;

This structure defines the following callbacks:
[bu] C]ucl_emitter_append_character] - a function that is called to append C]nchars] characters equal to C]c]
[bu] C]ucl_emitter_append_len] - used to append a string of length C]len] starting from pointer C]str]
[bu] C]ucl_emitter_append_int] - this function applies to integer numbers
[bu] C]ucl_emitter_append_double] - this function is intended to output floating point variable
The set of these functions could be used to output text formats of C]UCL] objects to different structures or streams.

Libucl provides the following functions for emitting UCL objects:


unsigned char *ucl_object_emit (const ucl_object_t *obj, enum ucl_emitter emit_type);

Allocate a string that is suitable to fit the underlying UCL object C]obj] and fill it with the textual representation of the object C]obj] according to style C]emit_type]. The caller should free the returned string after using.


bool ucl_object_emit_full (const ucl_object_t *obj, enum ucl_emitter emit_type,
        struct ucl_emitter_functions *emitter);

This function is similar to the previous with the exception that it accepts the additional argument C]emitter] that defines the concrete set of output functions. This emit function could be useful for custom structures or streams emitters (including C++ ones, for example).


Conversion functions are used to convert UCL objects to primitive types, such as strings, numbers, or boolean values. There are two types of conversion functions:
[bu] safe: try to convert an ucl object to a primitive type and fail if such a conversion is not possible
[bu] unsafe: return primitive type without additional checks, if the object cannot be converted then some reasonable default is returned (NULL for strings and 0 for numbers)
Also there is a single C]ucl_object_tostring_forced] function that converts any UCL object (including compound types - arrays and objects) to a string representation. For objects, arrays, booleans and numeric types this function performs emitting to a compact json format actually.

Here is a list of all conversion functions:
[bu] C]ucl_object_toint] - returns C]int64_t] of UCL object
[bu] C]ucl_object_todouble] - returns C]double] of UCL object
[bu] C]ucl_object_toboolean] - returns C]bool] of UCL object
[bu] C]ucl_object_tostring] - returns C]const char *] of UCL object (this string is NULL terminated)
[bu] C]ucl_object_tolstring] - returns C]const char *] and C]size_t] len of UCL object (string does not need to be NULL terminated)
[bu] C]ucl_object_tostring_forced] - returns string representation of any UCL object
Strings returned by these pointers are associated with the UCL object and exist over its lifetime. A caller should not free this memory.


It is possible to generate UCL objects from C primitive types. Moreover, libucl allows creation and modifying complex UCL objects, such as arrays or associative objects.


ucl_object_t * ucl_object_new (void)

Creates new object of type C]UCL_NULL]. This object should be released by caller.


ucl_object_t * ucl_object_typed_new (unsigned int type)

Create an object of a specified type: - C]UCL_OBJECT] - UCL object - key/value pairs - C]UCL_ARRAY] - UCL array - C]UCL_INT] - integer number - C]UCL_FLOAT] - floating point number - C]UCL_STRING] - NULL terminated string - C]UCL_BOOLEAN] - boolean value - C]UCL_TIME] - time value (floating point number of seconds) - C]UCL_USERDATA] - opaque userdata pointer (may be used in macros) - C]UCL_NULL] - null value

This object should be released by caller.

    Primitive objects generation

Libucl provides the functions similar to inverse conversion functions called with the specific C type: - C]ucl_object_fromint] - converts C]int64_t] to UCL object - C]ucl_object_fromdouble] - converts C]double] to UCL object - C]ucl_object_fromboolean] - converts C]bool] to UCL object - C]ucl_object_fromstring] - converts C]const char *] to UCL object (this string should be NULL terminated) - C]ucl_object_fromlstring] - converts C]const char *] and C]size_t] len to UCL object (string does not need to be NULL terminated)

Also there is a function to generate UCL object from a string performing various parsing or conversion operations called C]ucl_object_fromstring_common].


ucl_object_t * ucl_object_fromstring_common (const char *str,
    size_t len, enum ucl_string_flags flags)

This function is used to convert a string C]str] of size C]len] to a UCL object applying C]flags] conversions. If C]len] is equal to zero then a C]str] is assumed as NULL-terminated. This function supports the following flags (a set of flags can be specified using logical C]OR] operation):
[bu] C]UCL_STRING_ESCAPE] - perform JSON escape
[bu] C]UCL_STRING_TRIM] - trim leading and trailing whitespaces
[bu] C]UCL_STRING_PARSE_BOOLEAN] - parse passed string and detect boolean
[bu] C]UCL_STRING_PARSE_INT] - parse passed string and detect integer number
[bu] C]UCL_STRING_PARSE_DOUBLE] - parse passed string and detect integer or float number
[bu] C]UCL_STRING_PARSE_TIME] - parse time values as floating point numbers
[bu] C]UCL_STRING_PARSE_NUMBER] - parse passed string and detect number (both float, integer and time types)
[bu] C]UCL_STRING_PARSE] - parse passed string (and detect booleans, numbers and time values)
[bu] C]UCL_STRING_PARSE_BYTES] - assume that numeric multipliers are in bytes notation, for example C]10k] means C]10*1024] and not C]10*1000] as assumed without this flag
If parsing operations fail then the resulting UCL object will be a C]UCL_STRING]. A caller should always check the type of the returned object and release it after using.


Iteration are used to iterate over UCL compound types: arrays and objects. Moreover, iterations could be performed over the keys with multiple values (implicit arrays). There are two types of iterators API: old and unsafe one via C]ucl_iterate_object] and the proposed interface of safe iterators.


const ucl_object_t* ucl_iterate_object (const ucl_object_t *obj,
    ucl_object_iter_t *iter, bool expand_values);

This function accepts opaque iterator pointer C]iter]. In the first call this iterator I]must] be initialized to C]NULL]. Iterator is changed by this function call. C]ucl_iterate_object] returns the next UCL object in the compound object C]obj] or C]NULL] if all objects have been iterated. The reference count of the object returned is not increased, so a caller should not unref the object or modify its content (e.g. by inserting to another compound object). The object C]obj] should not be changed during the iteration process as well. C]expand_values] flag speicifies whether C]ucl_iterate_object] should expand keys with multiple values. The general rule is that if you need to iterate through the I]object] or I]explicit array], then you always need to set this flag to C]true]. However, if you get some key in the object and want to extract all its values then you should set C]expand_values] to C]false]. Mixing of iteration types is not permitted since the iterator is set according to the iteration type and cannot be reused. Here is an example of iteration over the objects using libucl API (assuming that C]top] is C]UCL_OBJECT] in this example):
ucl_object_iter_t it = NULL, it_obj = NULL;
const ucl_object_t *cur, *tmp;

/* Iterate over the object */ while ((obj = ucl_iterate_object (top, &it, true))) { printf ("key: \"%s\"\n", ucl_object_key (obj)); /* Iterate over the values of a key */ while ((cur = ucl_iterate_object (obj, &it_obj, false))) { printf ("value: \"%s\"\n", ucl_object_tostring_forced (cur)); } } ]

    Safe iterators API

Safe iterators are defined to clarify iterating over UCL objects and simplify flattening of UCL objects in non-trivial cases. For example, if there is an implicit array that contains another array and a boolean value it is extremely unclear how to iterate over such an object. Safe iterators are desinged to define two sorts of iteration:
1. Iteration over complex objects with expanding all values
2. Iteration over complex objects without expanding of values
The following example demonstrates the difference between these two types of iteration:
key = 1;
key = [2, 3, 4];

Iteration with expansion:

1, 2, 3, 4

Iteration without expansion:

1, [2, 3, 4] ]

UCL defines the following functions to manage safe iterators:
[bu] C]ucl_object_iterate_new] - creates new safe iterator
[bu] C]ucl_object_iterate_reset] - resets iterator to a new object
[bu] C]ucl_object_iterate_safe] - safely iterate the object inside iterator
[bu] C]ucl_object_iterate_free] - free memory associated with the safe iterator
Please note that unlike unsafe iterators, safe iterators I]must] be explicitly initialized and freed. An assert is likely generated if you use uninitialized or C]NULL] iterator in all safe iterators functions.
ucl_object_iter_t it;
const ucl_object_t *cur;

it = ucl_object_iterate_new (obj);

while ((cur = ucl_object_iterate_safe (it, true)) != NULL) { /* Do something */ }

/* Switch to another object */ it = ucl_object_iterate_reset (it, another_obj);

while ((cur = ucl_object_iterate_safe (it, true)) != NULL) { /* Do something else */ }

ucl_object_iterate_free (it); ]


Currently, there is only one validation function called C]ucl_object_validate]. It performs validation of object using the specified schema. This function is defined as following:


bool ucl_object_validate (const ucl_object_t *schema,
    const ucl_object_t *obj, struct ucl_schema_error *err);

This function uses ucl object C]schema], that must be valid in terms of C]json-schema] draft v4, to validate input object C]obj]. If this function returns C]true] then validation procedure has been succeed. Otherwise, C]false] is returned and C]err] is set to a specific value. If a caller sets C]err] to NULL then this function does not set any error just returning C]false]. Error is the structure defined as following:
struct ucl_schema_error {
    enum ucl_schema_error_code code;    /* error code */
    char msg[128];              /* error message */
    ucl_object_t *obj;          /* object where error occurred */

Caller may use C]code] field to get a numeric error code:
enum ucl_schema_error_code {
    UCL_SCHEMA_OK = 0,          /* no error */
    UCL_SCHEMA_TYPE_MISMATCH,   /* type of object is incorrect */
    UCL_SCHEMA_INVALID_SCHEMA,  /* schema is invalid */
    UCL_SCHEMA_MISSING_PROPERTY,/* missing properties */
    UCL_SCHEMA_CONSTRAINT,      /* constraint found */
    UCL_SCHEMA_MISSING_DEPENDENCY, /* missing dependency */
    UCL_SCHEMA_UNKNOWN          /* generic error */

C]msg] is a string description of an error and C]obj] is an object where error has occurred. Error object is not allocated by libucl, so there is no need to free it after validation (a static object should thus be used).


Vsevolod Stakhov <>.
Search for    or go to Top of page |  Section 3 |  Main Index

Libucl manual LIBUCL (3) 27 December, 2014

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with manServer 1.07.