]> mj.ucw.cz Git - libucw.git/blob - ucw/table-types.c
tableprinter: fix of size/timestamp printing
[libucw.git] / ucw / table-types.c
1 #include <ucw/lib.h>
2 #include <ucw/config.h>
3 #include <ucw/table-types.h>
4 #include <ucw/fastbuf.h>
5 #include <ucw/config.h>
6 #include <ucw/table.h>
7 #include <time.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 void table_col_size_name(struct table *tbl, const char *col_name, u64 val)
12 {
13   int col = table_get_col_idx(tbl, col_name);
14   table_col_size(tbl, col, val);
15 }
16
17 void table_col_size(struct table *tbl, int col, u64 val)
18 {
19   ASSERT_MSG(col < tbl->column_count && col >= 0, "Table column %d does not exist.", col);
20   ASSERT(tbl->columns[col].type == COL_TYPE_ANY || COL_TYPE_SIZE == tbl->columns[col].type);
21
22   tbl->last_printed_col = col;
23   tbl->row_printing_started = 1;
24
25   static u64 unit_div[] = {
26     [UNIT_BYTE] = (u64) 1,
27     [UNIT_KILOBYTE] = (u64) 1024LU,
28     [UNIT_MEGABYTE] = (u64) (1024LU * 1024LU),
29     [UNIT_GIGABYTE] = (u64) (1024LU * 1024LU * 1024LU),
30     [UNIT_TERABYTE] = (u64) (1024LU * 1024LU * 1024LU * 1024LU)
31   };
32
33   static const char *unit_suffix[] = {
34     [UNIT_BYTE] = "",
35     [UNIT_KILOBYTE] = "KB",
36     [UNIT_MEGABYTE] = "MB",
37     [UNIT_GIGABYTE] = "GB",
38     [UNIT_TERABYTE] = "TB"
39   };
40
41   // FIXME: do some rounding?
42   uint out_type = 0;
43   if(tbl->column_order[col].output_type == CELL_OUT_UNINITIALIZED) {
44     val = val / unit_div[UNIT_BYTE];
45     out_type = 0;
46   } else {
47     val = val / unit_div[tbl->column_order[col].output_type];
48     out_type = tbl->column_order[col].output_type;
49   }
50
51   table_col_printf(tbl, col, "%lu%s", val, unit_suffix[out_type]);
52 }
53
54 #define FORMAT_TIME_SIZE 20     // Minimum buffer size
55
56 void table_col_timestamp_name(struct table *tbl, const char * col_name, u64 val)
57 {
58   int col = table_get_col_idx(tbl, col_name);
59   table_col_size(tbl, col, val);
60 }
61
62 void table_col_timestamp(struct table *tbl, int col, u64 val)
63 {
64   ASSERT_MSG(col < tbl->column_count && col >= 0, "Table column %d does not exist.", col);
65   ASSERT(tbl->columns[col].type == COL_TYPE_ANY || COL_TYPE_TIMESTAMP == tbl->columns[col].type);
66
67   char formatted_time_buf[FORMAT_TIME_SIZE] = { 0 };
68
69   time_t tmp_time = (time_t)val;
70   struct tm t = *gmtime(&tmp_time);
71
72   switch (tbl->column_order[col].output_type) {
73   case TIMESTAMP_EPOCH:
74   case CELL_OUT_UNINITIALIZED:
75     sprintf(formatted_time_buf, "%lu", val);
76     break;
77   case TIMESTAMP_DATETIME:
78     strftime(formatted_time_buf, FORMAT_TIME_SIZE, "%F %T", &t);
79     break;
80   default:
81     abort();
82     break;
83   }
84
85   table_col_printf(tbl, col, "%s", formatted_time_buf);
86 }
87