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