2 * UCW Library -- Table printer
4 * (c) 2014 Robert Kessl <robert.kessl@economia.cz>
8 #include <ucw/string.h>
9 #include <ucw/stkstring.h>
11 #include <ucw/table.h>
12 #include <ucw/strtonum.h>
17 /* Forward declarations */
19 static void table_update_ll(struct table *tbl);
21 /*** Management of tables ***/
23 static struct table *table_make_instance(const struct table_template *tbl_template)
25 struct mempool *pool = mp_new(4096);
26 struct table *new_inst = mp_alloc_zero(pool, sizeof(struct table)); // FIXME: update allocation to the weird schema made by pchar and mj?
28 new_inst->pool = mp_new(4096);
30 // initialize column definitions
31 int col_count = 0; // count the number of columns in the struct table
33 if(tbl_template->columns[col_count].name == NULL &&
34 tbl_template->columns[col_count].width == 0 &&
35 tbl_template->columns[col_count].type_def == COL_TYPE_ANY)
37 ASSERT(tbl_template->columns[col_count].name != NULL);
38 ASSERT(tbl_template->columns[col_count].width != 0);
42 new_inst->column_count = col_count;
44 new_inst->columns = mp_alloc_zero(new_inst->pool, sizeof(struct table_column) * new_inst->column_count);
45 memcpy(new_inst->columns, tbl_template->columns, sizeof(struct table_column) * new_inst->column_count);
47 // initialize column_order
48 if(tbl_template->column_order) {
49 new_inst->column_order = mp_alloc_zero(new_inst->pool, sizeof(struct table_col_instance) * tbl_template->cols_to_output);
50 memcpy(new_inst->column_order, tbl_template->column_order, sizeof(struct table_col_instance) * tbl_template->cols_to_output);
51 for(uint i = 0; i < new_inst->cols_to_output; i++) {
52 new_inst->column_order[i].cell_content = NULL;
53 int col_idx = new_inst->column_order[i].idx;
54 new_inst->column_order[i].col_def = new_inst->columns + col_idx;
55 new_inst->column_order[i].output_type = tbl_template->column_order[i].output_type;
58 new_inst->cols_to_output = tbl_template->cols_to_output;
61 new_inst->col_delimiter = tbl_template->col_delimiter;
62 new_inst->print_header = 1;
64 new_inst->last_printed_col = -1;
65 new_inst->row_printing_started = 0;
66 new_inst->col_out = -1;
67 new_inst->formatter = tbl_template->formatter;
68 new_inst->data = NULL;
72 struct table *table_init(const struct table_template *tbl_template)
74 struct table *tbl = table_make_instance(tbl_template);
77 tbl->formatter = &table_fmt_human_readable;
80 tbl->print_header = 1; // by default, print header
84 void table_cleanup(struct table *tbl)
87 memset(tbl, 0, sizeof(struct table));
90 // TODO: test default column order
91 static void table_make_default_column_order(struct table *tbl)
93 int *col_order_int = mp_alloc_zero(tbl->pool, sizeof(int) * tbl->column_count); // FIXME: use stack instead of memory pool
94 for(int i = 0; i < tbl->column_count; i++) {
97 table_set_col_order(tbl, col_order_int, tbl->column_count);
100 void table_start(struct table *tbl, struct fastbuf *out)
102 tbl->last_printed_col = -1;
103 tbl->row_printing_started = 0;
106 ASSERT_MSG(tbl->out, "Output fastbuf not specified.");
108 if(tbl->column_order == NULL) table_make_default_column_order(tbl);
110 // update linked lists
111 table_update_ll(tbl);
113 if(tbl->formatter->table_start != NULL) tbl->formatter->table_start(tbl);
115 mp_save(tbl->pool, &tbl->pool_state);
117 ASSERT_MSG(tbl->col_delimiter, "In-between column delimiter not specified.");
120 void table_end(struct table *tbl)
122 tbl->last_printed_col = -1;
123 tbl->row_printing_started = 0;
125 mp_restore(tbl->pool, &tbl->pool_state);
127 if(tbl->formatter->table_end) tbl->formatter->table_end(tbl);
130 /*** Configuration ***/
132 void table_set_formatter(struct table *tbl, struct table_formatter *fmt)
134 tbl->formatter = fmt;
137 int table_get_col_idx(struct table *tbl, const char *col_name)
139 for(int i = 0; i < tbl->column_count; i++) {
140 if(strcmp(tbl->columns[i].name, col_name) == 0) return i;
145 const char * table_get_col_list(struct table *tbl)
147 if(tbl->column_count == 0) return "";
149 char *tmp = mp_strdup(tbl->pool, tbl->columns[0].name);
151 for(int i = 1; i < tbl->column_count; i++) {
152 tmp = mp_printf_append(tbl->pool, tmp, ", %s", tbl->columns[i].name);
158 static void table_update_ll(struct table *tbl)
160 int cols_to_output = tbl->cols_to_output;
162 for(int i = 0; i < tbl->column_count; i++) {
163 tbl->columns[i].first_column = -1;
166 for(int i = 0; i < cols_to_output; i++) {
167 int idx = tbl->column_order[i].idx;
168 tbl->column_order[i].col_def = tbl->columns + idx;
171 for(int i = 0; i < cols_to_output; i++) {
172 int first = tbl->column_order[i].col_def->first_column;
173 tbl->column_order[i].col_def->first_column = i;
176 tbl->column_order[i].next_column = first;
178 tbl->column_order[i].next_column = -1;
183 void table_set_col_order(struct table *tbl, int *col_order, int cols_to_output)
185 for(int i = 0; i < cols_to_output; i++) {
186 ASSERT_MSG(col_order[i] >= 0 && col_order[i] < tbl->column_count, "Column %d does not exist (column number should be between 0 and %d)", col_order[i], tbl->column_count - 1);
189 tbl->cols_to_output = cols_to_output;
190 tbl->column_order = mp_alloc_zero(tbl->pool, sizeof(struct table_col_instance) * cols_to_output);
191 for(int i = 0; i < cols_to_output; i++) {
192 int col_idx = col_order[i];
193 tbl->column_order[i].idx = col_idx;
194 tbl->column_order[i].col_def = tbl->columns + col_idx;
195 tbl->column_order[i].cell_content = NULL;
196 tbl->column_order[i].output_type = XTYPE_FMT_DEFAULT;
198 table_update_ll(tbl);
201 bool table_col_is_printed(struct table *tbl, uint col_idx)
203 if(tbl->columns[col_idx].first_column == -1) return 0;
208 static char * table_parse_col_arg(char *col_def)
210 // FIXME: should be switched to str_sepsplit
211 char * left_br = strchr(col_def, '[');
212 if(left_br == NULL) return NULL;
215 char *right_br = strchr(left_br, ']');
221 * Setting options for basic table types (as defined in table.h)
223 bool table_set_col_opt_default(struct table *tbl, int col_idx, const char *col_arg, char **err)
225 struct table_column *col_def = tbl->column_order[col_idx].col_def;
227 if(col_def->type_def == COL_TYPE_DOUBLE) {
229 const char *tmp_err = str_to_uint(&precision, col_arg, NULL, 0);
231 *err = mp_printf(tbl->pool, "An error occured while parsing precision: %s", tmp_err);
234 tbl->column_order[col_idx].output_type = precision; // FIXME: shift the value of precision
238 *err = mp_printf(tbl->pool, "Invalid column format option: '%s' for column %d.", col_arg, col_idx);
243 * TODO: This function deliberately leaks memory. When it is called multiple times,
244 * previous column orders still remain allocated in the table's memory pool.
246 const char * table_set_col_order_by_name(struct table *tbl, const char *col_order_str)
248 if(col_order_str[0] == '*') {
249 int *col_order_int = alloca(sizeof(int) * tbl->column_count);
250 for(int i = 0; i < tbl->column_count; i++) {
251 col_order_int[i] = i;
253 table_set_col_order(tbl, col_order_int, tbl->column_count);
258 if(!col_order_str[0]) {
259 tbl->column_order = mp_alloc(tbl->pool, 0);
260 tbl->cols_to_output = 0;
264 char *tmp_col_order = stk_strdup(col_order_str);
267 for(int i = 0; col_order_str[i] != 0; i++) {
268 if(col_order_str[i] == ',') {
273 tbl->cols_to_output = col_count;
274 tbl->column_order = mp_alloc_zero(tbl->pool, sizeof(struct table_col_instance) * col_count);
276 int curr_col_idx = 0;
277 char *name_start = tmp_col_order;
279 char *next = strchr(name_start, ',');
284 char *arg = table_parse_col_arg(name_start); // this sets 0 on the '['
285 int col_idx = table_get_col_idx(tbl, name_start);
288 return mp_printf(tbl->pool, "Unknown table column '%s', possible column names are: %s.", name_start, table_get_col_list(tbl));
290 tbl->column_order[curr_col_idx].col_def = tbl->columns + col_idx;
291 tbl->column_order[curr_col_idx].idx = col_idx;
292 tbl->column_order[curr_col_idx].cell_content = NULL;
293 tbl->column_order[curr_col_idx].output_type = XTYPE_FMT_DEFAULT;
294 if(tbl->columns[col_idx].type_def && tbl->columns[col_idx].set_col_instance_option) {
296 tbl->columns[col_idx].set_col_instance_option(tbl, curr_col_idx, arg, &err);
297 if(err) return mp_printf(tbl->pool, "Error occured while setting column option: %s.", err);
304 table_update_ll(tbl);
309 /*** Table cells ***/
311 static void table_set_all_inst_content(struct table *tbl, int col_templ, const char *col_content)
313 TBL_COL_ITER_START(tbl, col_templ, curr_col_ptr, curr_col) {
314 //if( override == 0 ) {
315 //die("Error while setting content of all cells of a single type column, cell format should not be overriden.");
317 curr_col_ptr->cell_content = col_content;
321 void table_col_printf(struct table *tbl, int col, const char *fmt, ...)
323 ASSERT_MSG(col < tbl->column_count && col >= 0, "Table column %d does not exist.", col);
324 tbl->last_printed_col = col;
325 tbl->row_printing_started = 1;
328 char *cell_content = mp_vprintf(tbl->pool, fmt, args);
329 table_set_all_inst_content(tbl, col, cell_content);
333 #define TABLE_COL(_name_, _type_, _typeconst_) void table_col_##_name_(struct table *tbl, int col, _type_ val)\
335 enum xtype_fmt fmt = tbl->columns[col].fmt;\
336 table_col_##_name_##_fmt(tbl, col, fmt, val);\
339 #define TABLE_COL_STR(_name_, _type_, _typeconst_) void table_col_##_name_##_name(struct table *tbl, const char *col_name, _type_ val)\
341 int col = table_get_col_idx(tbl, col_name);\
342 table_col_##_name_(tbl, col, val);\
345 #define TABLE_COL_FMT(_name_, _type_, _typeconst_, _override) void table_col_##_name_##_fmt(struct table *tbl, int col, enum xtype_fmt fmt, _type_ val) \
347 ASSERT_MSG(col < tbl->column_count && col >= 0, "Table column %d does not exist.", col);\
348 ASSERT(tbl->columns[col].type_def == COL_TYPE_ANY || _typeconst_ == tbl->columns[col].type_def);\
349 tbl->last_printed_col = col;\
350 tbl->row_printing_started = 1;\
351 const char *cell_content = NULL;\
352 if(tbl->columns[col].type_def != COL_TYPE_ANY) cell_content = tbl->columns[col].type_def->format(&val, fmt, tbl->pool);\
353 else cell_content = (_typeconst_)->format(&val, fmt, tbl->pool); \
354 table_set_all_inst_content(tbl, col, cell_content);\
357 #define TABLE_COL_BODIES(_name_, _type_, _typeconst_, _override) TABLE_COL(_name_, _type_, _typeconst_); \
358 TABLE_COL_STR(_name_, _type_, _typeconst_);\
359 TABLE_COL_FMT(_name_, _type_, _typeconst_, _override);
361 TABLE_COL_BODIES(int, int, COL_TYPE_INT, 0)
362 TABLE_COL_BODIES(uint, uint, COL_TYPE_UINT, 0)
363 TABLE_COL_BODIES(str, const char *, COL_TYPE_STR, 1)
364 TABLE_COL_BODIES(intmax, intmax_t, COL_TYPE_INTMAX, 0)
365 TABLE_COL_BODIES(uintmax, uintmax_t, COL_TYPE_UINTMAX, 0)
366 TABLE_COL_BODIES(s64, s64, COL_TYPE_S64, 0)
367 TABLE_COL_BODIES(u64, u64, COL_TYPE_U64, 0)
368 TABLE_COL_BODIES(double, double, COL_TYPE_DOUBLE, 0)
369 //TABLE_COL_BODIES(bool, bool, COL_TYPE_BOOL, 0)
371 // column type double is a special case
372 //TABLE_COL(double, double, COL_TYPE_DOUBLE);
373 //TABLE_COL_STR(double, double, COL_TYPE_DOUBLE);
375 TABLE_COL(bool, bool, COL_TYPE_BOOL)
376 TABLE_COL_STR(bool, bool, COL_TYPE_BOOL)
377 TABLE_COL_FMT(bool, bool, COL_TYPE_BOOL, 0)
382 #undef TABLE_COL_BODIES
385 void table_reset_row(struct table *tbl)
387 for(uint i = 0; i < tbl->cols_to_output; i++) {
388 tbl->column_order[i].cell_content = NULL;
390 mp_restore(tbl->pool, &tbl->pool_state);
391 tbl->last_printed_col = -1;
392 tbl->row_printing_started = 0;
395 void table_end_row(struct table *tbl)
397 ASSERT(tbl->formatter->row_output);
398 if(tbl->row_printing_started == 0) return;
399 tbl->formatter->row_output(tbl);
400 table_reset_row(tbl);
403 /* Construction of a cell using a fastbuf */
405 struct fastbuf *table_col_fbstart(struct table *tbl, int col)
407 fbpool_init(&tbl->fb_col_out);
408 fbpool_start(&tbl->fb_col_out, tbl->pool, 1);
410 return &tbl->fb_col_out.fb;
413 void table_col_fbend(struct table *tbl)
415 char *cell_content = fbpool_end(&tbl->fb_col_out);
416 table_set_all_inst_content(tbl, tbl->col_out, cell_content);
420 /*** Option parsing ***/
422 const char *table_set_option_value(struct table *tbl, const char *key, const char *value)
424 // Options with no value
425 if(value == NULL || (value != NULL && strlen(value) == 0)) {
426 if(strcmp(key, "noheader") == 0) {
427 tbl->print_header = 0;
432 // Options with a value
434 if(strcmp(key, "header") == 0) {
436 return mp_printf(tbl->pool, "Invalid header parameter: '%s' has invalid value: '%s'.", key, value);
437 uint tmp = value[0] - '0';
439 return mp_printf(tbl->pool, "Invalid header parameter: '%s' has invalid value: '%s'.", key, value);
440 tbl->print_header = tmp;
442 } else if(strcmp(key, "cols") == 0) {
443 return table_set_col_order_by_name(tbl, value);
444 } else if(strcmp(key, "fmt") == 0) {
445 if(strcmp(value, "human") == 0) table_set_formatter(tbl, &table_fmt_human_readable);
446 else if(strcmp(value, "machine") == 0) table_set_formatter(tbl, &table_fmt_machine_readable);
447 else if(strcmp(value, "blockline") == 0) table_set_formatter(tbl, &table_fmt_blockline);
449 return "Invalid argument to output-type option.";
452 } else if(strcmp(key, "col-delim") == 0) {
453 char * d = mp_printf(tbl->pool, "%s", value);
454 tbl->col_delimiter = d;
460 if(tbl->formatter && tbl->formatter->process_option) {
461 const char *err = NULL;
462 if(tbl->formatter->process_option(tbl, key, value, &err)) {
467 // Unrecognized option
468 return mp_printf(tbl->pool, "Invalid option: '%s%s%s'.", key, (value ? ":" : ""), (value ? : ""));
471 const char *table_set_option(struct table *tbl, const char *opt)
473 char *key = stk_strdup(opt);
474 char *value = strchr(key, ':');
478 return table_set_option_value(tbl, key, value);
481 const char *table_set_gary_options(struct table *tbl, char **gary_table_opts)
483 for (uint i = 0; i < GARY_SIZE(gary_table_opts); i++) {
484 const char *rv = table_set_option(tbl, gary_table_opts[i]);
492 /*** Default formatter for human-readable output ***/
494 static void table_row_human_readable(struct table *tbl)
496 for(uint i = 0; i < tbl->cols_to_output; i++) {
497 struct table_column *col_def = tbl->column_order[i].col_def;
499 bputs(tbl->out, tbl->col_delimiter);
501 int col_width = col_def->width & CELL_WIDTH_MASK;
502 if(col_def->width & CELL_ALIGN_LEFT) col_width = -1 * col_width;
503 bprintf(tbl->out, "%*s", col_width, tbl->column_order[i].cell_content);
505 bputc(tbl->out, '\n');
508 static void table_write_header(struct table *tbl)
510 for(uint i = 0; i < tbl->cols_to_output; i++) {
511 struct table_column *col_def = tbl->column_order[i].col_def;
513 bputs(tbl->out, tbl->col_delimiter);
515 int col_width = col_def->width & CELL_WIDTH_MASK;
516 if(col_def->width & CELL_ALIGN_LEFT) col_width = -1 * col_width;
517 bprintf(tbl->out, "%*s", col_width, col_def->name);
519 bputc(tbl->out, '\n');
522 static void table_start_human_readable(struct table *tbl)
524 if(tbl->col_delimiter == NULL) {
525 tbl->col_delimiter = " ";
528 if(tbl->print_header != 0) {
529 table_write_header(tbl);
533 struct table_formatter table_fmt_human_readable = {
534 .row_output = table_row_human_readable,
535 .table_start = table_start_human_readable,
538 /*** Default formatter for machine-readable output ***/
540 static void table_row_machine_readable(struct table *tbl)
542 for(uint i = 0; i < tbl->cols_to_output; i++) {
544 bputs(tbl->out, tbl->col_delimiter);
546 bputs(tbl->out, tbl->column_order[i].cell_content);
548 bputc(tbl->out, '\n');
551 static void table_start_machine_readable(struct table *tbl)
553 if(tbl->col_delimiter == NULL) {
554 tbl->col_delimiter = "\t";
557 if(tbl->print_header != 0 && tbl->cols_to_output > 0) {
558 bputs(tbl->out, tbl->column_order[0].col_def->name);
559 for(uint i = 1; i < tbl->cols_to_output; i++) {
560 bputs(tbl->out, tbl->col_delimiter);
561 bputs(tbl->out, tbl->column_order[i].col_def->name);
563 bputc(tbl->out, '\n');
567 struct table_formatter table_fmt_machine_readable = {
568 .row_output = table_row_machine_readable,
569 .table_start = table_start_machine_readable,
573 /*** Blockline formatter ***/
575 static void table_row_blockline_output(struct table *tbl)
577 for(uint i = 0; i < tbl->cols_to_output; i++) {
578 struct table_column *col_def = tbl->column_order[i].col_def;
579 bprintf(tbl->out, "%s: %s\n", col_def->name, tbl->column_order[i].cell_content);
581 bputc(tbl->out, '\n');
584 static void table_start_blockline(struct table *tbl)
586 if(tbl->col_delimiter == NULL) {
587 tbl->col_delimiter = "\n";
591 struct table_formatter table_fmt_blockline = {
592 .row_output = table_row_blockline_output,
593 .table_start = table_start_blockline
602 enum test_table_cols {
603 test_col0_str, test_col1_int, test_col2_uint, test_col3_bool, test_col4_double
606 static struct table_col_instance test_column_order[] = { TBL_COL(test_col3_bool), TBL_COL(test_col4_double), TBL_COL(test_col2_uint), TBL_COL(test_col1_int), TBL_COL(test_col0_str) };
608 static struct table_template test_tbl = {
610 [test_col0_str] = TBL_COL_STR("col0_str", 20),
611 [test_col1_int] = TBL_COL_INT("col1_int", 8),
612 [test_col2_uint] = TBL_COL_UINT("col2_uint", 9),
613 [test_col3_bool] = TBL_COL_BOOL("col3_bool", 9),
614 [test_col4_double] = TBL_COL_DOUBLE("col4_double", 11, 2),
617 TBL_COL_ORDER(test_column_order),
618 TBL_OUTPUT_HUMAN_READABLE,
619 TBL_COL_DELIMITER("\t"),
623 * tests: table_set_nt, table_set_uint, table_set_bool, table_set_double, table_set_printf
625 static void do_print1(struct table *test_tbl)
627 table_col_str(test_tbl, test_col0_str, "sdsdf");
628 table_col_int(test_tbl, test_col1_int, -10);
629 table_col_int(test_tbl, test_col1_int, 10000);
630 table_col_uint(test_tbl, test_col2_uint, 10);
631 table_col_printf(test_tbl, test_col2_uint, "XXX-%u", 22222);
632 table_col_bool(test_tbl, test_col3_bool, 1);
633 table_col_double(test_tbl, test_col4_double, 1.5);
634 table_col_printf(test_tbl, test_col4_double, "AAA");
635 table_end_row(test_tbl);
637 table_col_str(test_tbl, test_col0_str, "test");
638 table_col_int(test_tbl, test_col1_int, -100);
639 table_col_uint(test_tbl, test_col2_uint, 100);
640 table_col_bool(test_tbl, test_col3_bool, 0);
641 table_col_printf(test_tbl, test_col4_double, "%.2lf", 1.5);
642 table_end_row(test_tbl);
645 static void test_simple1(struct fastbuf *out)
647 struct table *tbl = table_init(&test_tbl);
649 // print table with header
650 table_set_col_order_by_name(tbl, "col3_bool");
651 table_start(tbl, out);
655 // print the same table as in the previous case without header
656 table_set_col_order_by_name(tbl, "col0_str,col2_uint,col1_int,col3_bool");
657 table_start(tbl, out);
661 // this also tests whether there is need to call table_set_col_order_by_name after table_end was called
662 tbl->print_header = 0;
663 table_start(tbl, out);
666 tbl->print_header = 1;
668 table_set_col_order_by_name(tbl, "col3_bool");
669 table_start(tbl, out);
673 table_set_col_order_by_name(tbl, "col3_bool,col0_str");
674 table_start(tbl, out);
678 table_set_col_order_by_name(tbl, "col0_str,col3_bool,col2_uint");
679 table_start(tbl, out);
683 table_set_col_order_by_name(tbl, "col0_str,col3_bool,col2_uint,col0_str,col3_bool,col2_uint,col0_str,col3_bool,col2_uint");
684 table_start(tbl, out);
688 table_set_col_order_by_name(tbl, "col0_str,col1_int,col2_uint,col3_bool,col4_double");
689 table_start(tbl, out);
696 enum test_any_table_cols {
697 test_any_col0_int, test_any_col1_any
700 static struct table_col_instance test_any_column_order[] = { TBL_COL(test_any_col0_int), TBL_COL(test_any_col1_any) };
702 static struct table_template test_any_tbl = {
704 [test_any_col0_int] = TBL_COL_INT("col0_int", 8),
705 [test_any_col1_any] = TBL_COL_ANY("col1_any", 9),
708 TBL_COL_ORDER(test_any_column_order),
709 TBL_OUTPUT_HUMAN_READABLE,
710 TBL_COL_DELIMITER("\t"),
713 static void test_any_type(struct fastbuf *out)
715 struct table *tbl = table_init(&test_any_tbl);
717 table_start(tbl, out);
719 table_col_int(tbl, test_any_col0_int, -10);
720 table_col_int(tbl, test_any_col1_any, 10000);
723 table_col_int(tbl, test_any_col0_int, -10);
724 table_col_double(tbl, test_any_col1_any, 1.4);
727 table_col_printf(tbl, test_any_col0_int, "%d", 10);
728 table_col_double(tbl, test_any_col1_any, 1.4);
735 int main(int argc UNUSED, char **argv UNUSED)
738 out = bfdopen_shared(1, 4096);