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