]> mj.ucw.cz Git - libucw.git/blob - ucw/table.h
Merge branch 'master' into dev-table
[libucw.git] / ucw / table.h
1 /*
2  *      UCW Library -- Table printer
3  *
4  *      (c) 2014 Robert Kessl <robert.kessl@economia.cz>
5  */
6
7 #ifndef _UCW_TABLE_H
8 #define _UCW_TABLE_H
9
10 #include <inttypes.h>
11
12 #include <ucw/fastbuf.h>
13 #include <ucw/mempool.h>
14 #include <ucw/xtypes.h>
15
16 // FIXME: update these macros
17 #ifdef CONFIG_UCW_CLEAN_ABI
18 #define table_append_bool ucw_table_append_bool
19 #define table_append_double ucw_table_append_double
20 #define table_append_int ucw_table_append_int
21 #define table_append_intmax ucw_table_append_intmax
22 #define table_append_printf ucw_table_append_printf
23 #define table_append_str ucw_table_append_str
24 #define table_append_u64 ucw_table_append_u64
25 #define table_append_uint ucw_table_append_uint
26 #define table_append_uintmax ucw_table_append_uintmax
27 #define table_cleanup ucw_table_cleanup
28 #define table_col_bool ucw_table_col_bool
29 #define table_col_bool_fmt ucw_table_col_bool_fmt
30 #define table_col_bool_name ucw_table_col_bool_name
31 #define table_col_double ucw_table_col_double
32 #define table_col_double_fmt ucw_table_col_double_fmt
33 #define table_col_double_name ucw_table_col_double_name
34 #define table_col_fbend ucw_table_col_fbend
35 #define table_col_fbstart ucw_table_col_fbstart
36 #define table_col_int ucw_table_col_int
37 #define table_col_int_fmt ucw_table_col_int_fmt
38 #define table_col_int_name ucw_table_col_int_name
39 #define table_col_intmax ucw_table_col_intmax
40 #define table_col_intmax_fmt ucw_table_col_intmax_fmt
41 #define table_col_intmax_name ucw_table_col_intmax_name
42 #define table_col_printf ucw_table_col_printf
43 #define table_col_s64 ucw_table_col_s64
44 #define table_col_s64_fmt ucw_table_col_s64_fmt
45 #define table_col_s64_name ucw_table_col_s64_name
46 #define table_col_str ucw_table_col_str
47 #define table_col_str_fmt ucw_table_col_str_fmt
48 #define table_col_str_name ucw_table_col_str_name
49 #define table_col_u64 ucw_table_col_u64
50 #define table_col_u64_fmt ucw_table_col_u64_fmt
51 #define table_col_u64_name ucw_table_col_u64_name
52 #define table_col_uint ucw_table_col_uint
53 #define table_col_uint_fmt ucw_table_col_uint_fmt
54 #define table_col_uint_name ucw_table_col_uint_name
55 #define table_col_uintmax ucw_table_col_uintmax
56 #define table_col_uintmax_fmt ucw_table_col_uintmax_fmt
57 #define table_col_uintmax_name ucw_table_col_uintmax_name
58 #define table_end ucw_table_end
59 #define table_end_row ucw_table_end_row
60 #define table_fmt_blockline ucw_table_fmt_blockline
61 #define table_fmt_human_readable ucw_table_fmt_human_readable
62 #define table_fmt_machine_readable ucw_table_fmt_machine_readable
63 #define table_get_col_idx ucw_table_get_col_idx
64 #define table_get_col_list ucw_table_get_col_list
65 #define table_init ucw_table_init
66 #define table_set_col_order ucw_table_set_col_order
67 #define table_set_col_order_by_name ucw_table_set_col_order_by_name
68 #define table_set_formatter ucw_table_set_formatter
69 #define table_set_gary_options ucw_table_set_gary_options
70 #define table_set_option ucw_table_set_option
71 #define table_set_option_value ucw_table_set_option_value
72 #define table_start ucw_table_start
73 #endif
74
75 /***
76  * Table definitions
77  * -----------------
78  ***/
79
80 // FIXME: update documentation according to the changes made in recent commits!
81
82 /** The COL_TYPE_ANY macro specifies a column type which can be filled with arbitrary type. **/
83
84 #define COL_TYPE_ANY      NULL
85
86 /** Justify cell contents to the left. **/
87 #define CELL_ALIGN_LEFT     (1U << 31)
88
89 // CELL_FLAG_MASK has 1's in bits used for column flags,
90 // CELL_WIDTH_MASK has 1's in bits used for column width.
91 #define CELL_FLAG_MASK  (CELL_ALIGN_LEFT)
92 #define CELL_WIDTH_MASK (~CELL_FLAG_MASK)
93
94 struct table;
95
96 enum table_option_state {
97   TABLE_OPT_PROCESSED,
98   TABLE_OPT_UNKNOWN,
99   TABLE_OPT_ERR
100 };
101
102 /**
103  * Definition of a single table column.
104  * Usually, this is generated using the `TABLE_COL_`'type' macros.
105  * Fields marked with `[*]` are user-accessible.
106  **/
107 struct table_column {
108   const char *name;             // [*] Name of the column displayed in table header
109   uint width;                   // [*] Width of the column (in characters) OR'ed with column flags
110   uint fmt;                     // [*] default format of the column
111   const struct xtype *type_def; // [*] pointer to xtype of this column
112
113   int (*set_col_instance_option)(struct table *tbl, uint col, const char *value, char **err);
114        // [*] process table option for a column instance
115 };
116
117 // FIXME: is it correct to have idx and col_def? idx is sufficient and in fact a duplicity of idx
118 // idx is used only for initialization and col_def is used in other cases
119 struct table_col_instance {
120   uint idx;                            // idx is a index into struct table::columns
121   const struct table_column *col_def;  // this is pointer to the column definition, located in the array struct table::columns
122   const char *cell_content;            // content of the cell of the current row
123   int next_column;                     // index of next column in linked list of columns of the same type
124   uint output_type;                    // format of this column
125 };
126
127 /**
128  * Definition of a table. Contains column definitions, and some per-table settings.
129  * Please use only fields marked with `[*]`.
130  **/
131 struct table_template {
132   const struct table_column *columns;       // [*] Definition of columns
133   struct table_col_instance *column_order;  // [*] Order of the columns in the print-out of the table
134   uint cols_to_output;                      // [*] Number of columns that are printed
135   const char *col_delimiter;                // [*] Delimiter that is placed between columns
136   // Back-end used for table formatting and its private data
137   const struct table_formatter *formatter; // FIXME: should be const?
138 };
139
140 /**
141  * Handle of a table. Contains column definitions, per-table settings
142  * and internal data. To change the table definition, please use only
143  * fields marked with `[*]`.
144  **/
145 struct table {
146   const struct table_column *columns;   // [*] Definition of columns
147   int column_count;                     // [*] Number of columns (calculated by table_init())
148   int *ll_headers;                      // headers of linked lists that connects column instances
149   struct mempool *pool;                 // Memory pool used for storing table data. Contains global state
150                                         // and data of the current row.
151   struct mempool_state pool_state;      // State of the pool after the table is initialized, i.e., before
152                                         // per-row data have been allocated.
153
154   struct table_col_instance *column_order;  // [*] Order of the columns in the print-out of the table
155   uint cols_to_output;                  // [*] Number of columns that are printed
156   const char *col_delimiter;            // [*] Delimiter that is placed between columns
157   uint print_header;                    // [*] 0 indicates that table header should not be printed
158
159   struct fastbuf *out;                  // [*] Fastbuffer to which the table is printed
160   int last_printed_col;                 // Index of the last column which was set. -1 indicates start of row.
161                                         // Used for example for appending to the current column.
162   int row_printing_started;             // Indicates that a row has been started. Duplicates last_printed_col, but harmlessly.
163   struct fbpool fb_col_out;             // Per-cell fastbuf, see table_col_fbstart()
164   int col_out;                          // Index of the column that is currently printed using fb_col_out
165
166   // Back-end used for table formatting and its private data
167   const struct table_formatter *formatter;
168   void *data;
169 };
170
171 /****
172  * In most cases, table descriptions are constructed using the following macros.
173  * See the examples above for more details.
174  *
175  *  * `TBL_COLUMNS` indicates the start of definition of columns
176  *  * `TBL_COL_`'type'`(name, width)` defines a column of a given type
177  *  * `TBL_COL_`'type'`_FMT(name, width, fmt)` defines a column with a custom format string
178  *  * `TBL_COL_END` ends the column definitions
179  *  * `TBL_COL_ORDER` specifies custom ordering of columns in the output
180  *  * `TBL_COL_DELIMITER` and `TBL_APPEND_DELIMITER` override default delimiters
181  *  * `TBL_FMT__HUMAN_READABLE` requests human-readable formatting (this is the default)
182  *  * `TBL_FMT_MACHINE_READABLE` requests machine-readable TSV output
183  *  * `TBL_FMT_BLOCKLINE` requests block formatting (each cell printed a pair of a key and value on its own line)
184  *
185  ***/
186
187 #define TBL_COL_STR(_name, _width)            { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_str }
188 #define TBL_COL_INT(_name, _width)            { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_int }
189 #define TBL_COL_S64(_name, _width)            { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_s64 }
190 #define TBL_COL_UINT(_name, _width)           { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_uint }
191 #define TBL_COL_U64(_name, _width)            { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_u64 }
192 #define TBL_COL_INTMAX(_name, _width)         { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_intmax }
193 #define TBL_COL_UINTMAX(_name, _width)        { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_uintmax }
194 #define TBL_COL_HEXUINT(_name, _width)        { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_uint }
195 #define TBL_COL_DOUBLE(_name, _width)         { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_double }
196 #define TBL_COL_BOOL(_name, _width)           { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = &xt_bool }
197 #define TBL_COL_ANY(_name, _width)            { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = COL_TYPE_ANY }
198 #define TBL_COL_CUSTOM(_name, _width, _xtype) { .name = _name, .width = _width, .fmt = XTYPE_FMT_DEFAULT, .type_def = _xtype }
199
200 #define TBL_COL_STR_FMT(_name, _width, _fmt)            { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_str }
201 #define TBL_COL_INT_FMT(_name, _width, _fmt)            { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_int }
202 #define TBL_COL_S64_FMT(_name, _width, _fmt)            { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_s64 }
203 #define TBL_COL_UINT_FMT(_name, _width, _fmt)           { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_uint }
204 #define TBL_COL_U64_FMT(_name, _width, _fmt)            { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_u64 }
205 #define TBL_COL_INTMAX_FMT(_name, _width, _fmt)         { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_intmax }
206 #define TBL_COL_UINTMAX_FMT(_name, _width, _fmt)        { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_uintmax }
207 #define TBL_COL_HEXUINT_FMT(_name, _width, _fmt)        { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_uint }
208 #define TBL_COL_BOOL_FMT(_name, _width, _fmt)           { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_bool }
209 #define TBL_COL_ANY_FMT(_name, _width, _fmt)            { .name = _name, .width = _width, .fmt = _fmt, .type_def = COL_TYPE_ANY }
210 #define TBL_COL_DOUBLE_FMT(_name, _width, _fmt)         { .name = _name, .width = _width, .fmt = _fmt, .type_def = &xt_double }
211
212 #define TBL_COL_END { .name = 0, .width = 0, .fmt = 0, .type_def = NULL }
213
214 #define TBL_COLUMNS  .columns = (struct table_column [])
215 #define TBL_COL_ORDER(order) .column_order = (struct table_col_instance *) order, .cols_to_output = ARRAY_SIZE(order)
216 #define TBL_COL_DELIMITER(_delimiter) .col_delimiter = _delimiter
217
218 /**
219  * These macros are used for definition of column order
220  **/
221 #define TBL_COL(_idx) { .idx = _idx, .output_type = XTYPE_FMT_DEFAULT, .next_column = -1 }
222 #define TBL_COL_FMT(_idx, _fmt) { .idx = _idx, .output_type = _fmt, .next_column = -1 }
223
224 #define TBL_FMT_HUMAN_READABLE     .formatter = &table_fmt_human_readable
225 #define TBL_FMT_BLOCKLINE          .formatter = &table_fmt_blockline
226 #define TBL_FMT_MACHINE_READABLE   .formatter = &table_fmt_machine_readable
227
228 /**
229  * The TBL_COL_ITER_START macro are used for iterating over all instances of a particular column in
230  * table _tbl.  _colidx is the column index in _tbl, _instptr is the pointer to the column instance
231  * (struct table_col_instance *), _idxval is the index of current column index. The variables are
232  * enclosed in a block, so they do not introduce variable name collisions.
233  *
234  * The TBL_COL_ITER_END macro must close the block started with TBL_COL_ITER_START.
235  **/
236 #define TBL_COL_ITER_START(_tbl, _colidx, _instptr, _idxval) { struct table_col_instance *_instptr = NULL; int _idxval = _tbl->ll_headers[_colidx]; \
237   for(_idxval = _tbl->ll_headers[_colidx], _instptr = _tbl->column_order + _idxval; _idxval != -1; _idxval = _tbl->column_order[_idxval].next_column, _instptr = _tbl->column_order + _idxval)
238
239 #define TBL_COL_ITER_END }
240
241 /**
242  * Creates a new table from a table template. The template should already contain
243  * the definitions of columns.
244  **/
245 struct table *table_init(const struct table_template *tbl_template);
246
247 /** Destroy a table definition, freeing all memory used by it. **/
248 void table_cleanup(struct table *tbl);
249
250 /**
251  * Start printing of a table. This is a prerequisite to setting of column values.
252  * After @table_start() is called, it is no longer possible to change parameters
253  * of the table by `table_set_`'something' nor by direct access to the table structure.
254  **/
255 void table_start(struct table *tbl, struct fastbuf *out);
256
257 /**
258  * This function must be called after all the rows of the current table are printed,
259  * making the table structure ready for the next table. You can call `table_set_`'something'
260  * between @table_end() and @table_start().
261  **/
262 void table_end(struct table *tbl);
263
264 /***
265  * Filling tables with data
266  * ------------------------
267  *
268  * For each column type, there are functions for filling of cells
269  * of the particular type:
270  *
271  *   * `table_col_`'type'`(table, idx, value)` sets the cell in column `idx`
272  *     to the `value`
273  *   * `table_col_`'type'`_fmt(table, idx, fmt, ...)` does the same with
274  *     a custom printf-like format string
275  *   * `table_col_`'type'`_name(table, name, value)` refers to the column
276  *     by its name instead of its index.
277  ***/
278
279
280 #define TABLE_COL_PROTO(_name, _type) void table_col_##_name(struct table *tbl, int col, _type val);
281
282 TABLE_COL_PROTO(int, int)
283 TABLE_COL_PROTO(uint, uint)
284 TABLE_COL_PROTO(double, double)
285 TABLE_COL_PROTO(intmax, intmax_t)
286 TABLE_COL_PROTO(uintmax, uintmax_t)
287 TABLE_COL_PROTO(s64, s64)
288 TABLE_COL_PROTO(u64, u64)
289 TABLE_COL_PROTO(bool, bool)
290
291 void table_col_str(struct table *tbl, int col, const char * val);
292
293 /** TABLE_COL_BODY macro enables easy definitions of bodies of table_col_<something> functions **/
294 #define TABLE_COL_BODY(_name, _type) void table_col_##_name(struct table *tbl, int col, _type val) {\
295     table_col_generic_format(tbl, col, (void*)&val, &xt_##_name);\
296   }
297
298 /**
299  * The table_col_generic_format performs all the checks necessary while filling cell with value,
300  * calls the format function from expected_type and stores its result as a cell value. The function
301  * guarantees that each column instance is printed with its format.
302  **/
303 void table_col_generic_format(struct table *tbl, int col, void *value, const struct xtype *expected_type);
304
305 /**
306  * Set a particular cell of the current row to a string formatted
307  * by sprintf(). This function can set a column of an arbitrary type.
308  **/
309 void table_col_printf(struct table *tbl, int col, const char *fmt, ...) FORMAT_CHECK(printf, 3, 4);
310
311 /**
312  * Alternatively, a string cell can be constructed as a stream.
313  * This function creates a fastbuf stream connected to the contents
314  * of the particular cell. Before you close the stream by @table_col_fbend(),
315  * no other operations with cells are allowed.
316  **/
317 struct fastbuf *table_col_fbstart(struct table *tbl, int col);
318
319 /**
320  * Close the stream that is used for printing of the current column.
321  **/
322 void table_col_fbend(struct table *tbl);
323
324 /**
325  * Called when all cells of the current row have their values filled in.
326  * It sends the completed row to the output stream.
327  **/
328 void table_end_row(struct table *tbl);
329
330 /**
331  * Resets data in current row.
332  **/
333 void table_reset_row(struct table *tbl);
334
335 /***
336  * Configuration functions
337  * -----------------------
338  ***/
339
340 /**
341  * Find the index of a column with name @col_name. Returns -1 if there is no such column.
342  **/
343 int table_get_col_idx(struct table *tbl, const char *col_name);
344
345
346 /**
347  * Sets a string argument to a column instance
348  **/
349 int table_set_col_opt_default(struct table *tbl, int col_idx, const char *col_arg, char ** err);
350
351 /**
352  * Returns a comma-and-space-separated list of column names, allocated from table's internal
353  * memory pool.
354  **/
355 const char *table_get_col_list(struct table *tbl);
356
357 /**
358  * Sets the order in which the columns are printed. The @col_order parameter is used until @table_end() or
359  * @table_cleanup() is called. The table stores only the pointer and the memory pointed to by @col_order is
360  * allocated and deallocated by the caller.
361  **/
362 void table_set_col_order(struct table *tbl, int *col_order, int col_order_size);
363
364 /**
365  * Returns 1 if col_idx will be printed, 0 otherwise.
366  **/
367 bool table_col_is_printed(struct table *tbl, uint col_idx);
368
369 /**
370  * Sets the order in which the columns are printed. The specification is a string with comma-separated column
371  * names. Returns NULL for success and an error message otherwise. The string is not referenced after
372  * this function returns.
373  *
374  * The format of the col_order string is the following:
375  * <col-order-string> := <col-def>[,<col-def>]*
376  *
377  * <col-def> := <col-name> '[' <col-opt> ']'
378  *
379  * <col-name> is a string that does not contain comma ',' or '[',']' brackets
380  *
381  * <col-opt> is currently only one string.
382  *
383  * FIXME In the future, we should allow <col-opt> to be a comma(,) separated list of identifiers
384  **/
385 const char *table_set_col_order_by_name(struct table *tbl, const char *col_order);
386
387 /**
388  * Sets table formatter. See below for the list of formatters.
389  **/
390 void table_set_formatter(struct table *tbl, const struct table_formatter *fmt);
391
392 /**
393  * Set a table option. All options have a key and a value. Currently,
394  * the following keys are defined (other keys can be accepted by formatters):
395  *
396  * [options="header"]
397  * |===================================================================================================
398  * | key        | value                         | meaning
399  * | `header`   | 0 or 1                        | set whether a table header should be printed
400  * | `noheader` | 'none'                        | equivalent to `header`=0
401  * | `cols`     | comma-separated column list   | set order of columns
402  * | `fmt`      | `human`/`machine`/`block`     | set table formatter to one of the built-in formatters
403  * | `col-delim`| string                        | set column delimiter
404 *  | `cells`    | string                        | set column format mode
405  * |===================================================================================================
406  **/
407 const char *table_set_option_value(struct table *tbl, const char *key, const char *value);
408
409 /**
410  * Sets a table option given as 'key'`:`'value' or 'key' (with no value).
411  **/
412 const char *table_set_option(struct table *tbl, const char *opt);
413
414 /**
415  * Sets several table option in 'key'`:`'value' form, stored in a growing array.
416  * This is frequently used for options given on the command line.
417  **/
418 const char *table_set_gary_options(struct table *tbl, char **gary_table_opts);
419
420 /***
421  * Formatters
422  * ----------
423  *
424  * Transformation of abstract cell data to the characters in the output stream
425  * is under control of a formatter (which serves as a back-end of the table printer).
426  * There are several built-in formatters, but you can define your own.
427  *
428  * A formatter is described by a structure, which contains pointers to several
429  * call-back functions, which are called by the table printer at specific occasions.
430  *
431  * The formatter can keep its internal state in the `data` field of `struct table`
432  * and allocate temporary data from the table's memory pool. Memory allocated in
433  * the `row_output` call-back is freed before the next row begins. Memory allocated
434  * between the beginning of `table_start` and the end of `table_end` is freed after
435  * `table_end`. Memory allocated by `process_option` when no table is started
436  * is kept until @table_cleanup().
437  ***/
438
439 /** Definition of a formatter back-end. **/
440 struct table_formatter {
441   void (*row_output)(struct table *tbl);        // [*] Function that outputs one row
442   void (*table_start)(struct table *tbl);       // [*] table_start callback (optional)
443   void (*table_end)(struct table *tbl);         // [*] table_end callback (optional)
444   bool (*process_option)(struct table *tbl, const char *key, const char *value, const char **err);
445         // [*] Process table option and possibly return an error message (optional)
446 };
447
448 /** Standard formatter for human-readable output. **/
449 extern const struct table_formatter table_fmt_human_readable;
450
451 /** Standard formatter for machine-readable output (tab-separated values). **/
452 extern const struct table_formatter table_fmt_machine_readable;
453
454 /**
455  * Standard formatter for block output. Each cell is output on its own line
456  * of the form `column_name: value`. Rows are separated by blank lines.
457  **/
458 extern const struct table_formatter table_fmt_blockline;
459
460 #endif