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