summaryrefslogtreecommitdiffstats
path: root/src/shared/format-table.c
blob: 4f4a84d7494e259726b4e52581e9fb90e9d4a85b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
/* SPDX-License-Identifier: LGPL-2.1+ */

#include <ctype.h>

#include "alloc-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-table.h"
#include "gunicode.h"
#include "memory-util.h"
#include "pager.h"
#include "parse-util.h"
#include "pretty-print.h"
#include "sort-util.h"
#include "string-util.h"
#include "terminal-util.h"
#include "time-util.h"
#include "utf8.h"
#include "util.h"

#define DEFAULT_WEIGHT 100

/*
   A few notes on implementation details:

 - TableCell is a 'fake' structure, it's just used as data type to pass references to specific cell positions in the
   table. It can be easily converted to an index number and back.

 - TableData is where the actual data is stored: it encapsulates the data and formatting for a specific cell. It's
   'pseudo-immutable' and ref-counted. When a cell's data's formatting is to be changed, we duplicate the object if the
   ref-counting is larger than 1. Note that TableData and its ref-counting is mostly not visible to the outside. The
   outside only sees Table and TableCell.

 - The Table object stores a simple one-dimensional array of references to TableData objects, one row after the
   previous one.

 - There's no special concept of a "row" or "column" in the table, and no special concept of the "header" row. It's all
   derived from the cell index: we know how many cells are to be stored in a row, and can determine the rest from
   that. The first row is always the header row. If header display is turned off we simply skip outputting the first
   row. Also, when sorting rows we always leave the first row where it is, as the header shouldn't move.

 - Note because there's no row and no column object some properties that might be appropriate as row/column properties
   are exposed as cell properties instead. For example, the "weight" of a column (which is used to determine where to
   add/remove space preferable when expanding/compressing tables horizontally) is actually made the "weight" of a
   cell. Given that we usually need it per-column though we will calculate the average across every cell of the column
   instead.

 - To make things easy, when cells are added without any explicit configured formatting, then we'll copy the formatting
   from the same cell in the previous cell. This is particularly useful for the "weight" of the cell (see above), as
   this means setting the weight of the cells of the header row will nicely propagate to all cells in the other rows.
*/

typedef struct TableData {
        unsigned n_ref;
        TableDataType type;

        size_t minimum_width;       /* minimum width for the column */
        size_t maximum_width;       /* maximum width for the column */
        unsigned weight;            /* the horizontal weight for this column, in case the table is expanded/compressed */
        unsigned ellipsize_percent; /* 0 … 100, where to place the ellipsis when compression is needed */
        unsigned align_percent;     /* 0 … 100, where to pad with spaces when expanding is needed. 0: left-aligned, 100: right-aligned */

        bool uppercase;             /* Uppercase string on display */

        const char *color;          /* ANSI color string to use for this cell. When written to terminal should not move cursor. Will automatically be reset after the cell */
        char *url;                  /* A URL to use for a clickable hyperlink */
        char *formatted;            /* A cached textual representation of the cell data, before ellipsation/alignment */

        union {
                uint8_t data[0];    /* data is generic array */
                bool boolean;
                usec_t timestamp;
                usec_t timespan;
                uint64_t size;
                char string[0];
                uint32_t uint32;
                uint64_t uint64;
                int percent;        /* we use 'int' as datatype for percent values in order to match the result of parse_percent() */
                /* … add more here as we start supporting more cell data types … */
        };
} TableData;

static size_t TABLE_CELL_TO_INDEX(TableCell *cell) {
        size_t i;

        assert(cell);

        i = PTR_TO_SIZE(cell);
        assert(i > 0);

        return i-1;
}

static TableCell* TABLE_INDEX_TO_CELL(size_t index) {
        assert(index != (size_t) -1);
        return SIZE_TO_PTR(index + 1);
}

struct Table {
        size_t n_columns;
        size_t n_cells;

        bool header;   /* Whether to show the header row? */
        size_t width;  /* If != (size_t) -1 the width to format this table in */

        TableData **data;
        size_t n_allocated;

        size_t *display_map;  /* List of columns to show (by their index). It's fine if columns are listed multiple times or not at all */
        size_t n_display_map;

        size_t *sort_map;     /* The columns to order rows by, in order of preference. */
        size_t n_sort_map;

        bool *reverse_map;
};

Table *table_new_raw(size_t n_columns) {
        _cleanup_(table_unrefp) Table *t = NULL;

        assert(n_columns > 0);

        t = new(Table, 1);
        if (!t)
                return NULL;

        *t = (struct Table) {
                .n_columns = n_columns,
                .header = true,
                .width = (size_t) -1,
        };

        return TAKE_PTR(t);
}

Table *table_new_internal(const char *first_header, ...) {
        _cleanup_(table_unrefp) Table *t = NULL;
        size_t n_columns = 1;
        const char *h;
        va_list ap;
        int r;

        assert(first_header);

        va_start(ap, first_header);
        for (;;) {
                h = va_arg(ap, const char*);
                if (!h)
                        break;

                n_columns++;
        }
        va_end(ap);

        t = table_new_raw(n_columns);
        if (!t)
                return NULL;

        va_start(ap, first_header);
        for (h = first_header; h; h = va_arg(ap, const char*)) {
                TableCell *cell;

                r = table_add_cell(t, &cell, TABLE_STRING, h);
                if (r < 0) {
                        va_end(ap);
                        return NULL;
                }

                /* Make the table header uppercase */
                r = table_set_uppercase(t, cell, true);
                if (r < 0) {
                        va_end(ap);
                        return NULL;
                }
        }
        va_end(ap);

        assert(t->n_columns == t->n_cells);
        return TAKE_PTR(t);
}

static TableData *table_data_free(TableData *d) {
        assert(d);

        free(d->formatted);
        free(d->url);

        return mfree(d);
}

DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(TableData, table_data, table_data_free);
DEFINE_TRIVIAL_CLEANUP_FUNC(TableData*, table_data_unref);

Table *table_unref(Table *t) {
        size_t i;

        if (!t)
                return NULL;

        for (i = 0; i < t->n_cells; i++)
                table_data_unref(t->data[i]);

        free(t->data);
        free(t->display_map);
        free(t->sort_map);
        free(t->reverse_map);

        return mfree(t);
}

static size_t table_data_size(TableDataType type, const void *data) {

        switch (type) {

        case TABLE_EMPTY:
                return 0;

        case TABLE_STRING:
                return strlen(data) + 1;

        case TABLE_BOOLEAN:
                return sizeof(bool);

        case TABLE_TIMESTAMP:
        case TABLE_TIMESPAN:
                return sizeof(usec_t);

        case TABLE_SIZE:
        case TABLE_UINT64:
                return sizeof(uint64_t);

        case TABLE_UINT32:
                return sizeof(uint32_t);

        case TABLE_PERCENT:
                return sizeof(int);

        default:
                assert_not_reached("Uh? Unexpected cell type");
        }
}

static bool table_data_matches(
                TableData *d,
                TableDataType type,
                const void *data,
                size_t minimum_width,
                size_t maximum_width,
                unsigned weight,
                unsigned align_percent,
                unsigned ellipsize_percent) {

        size_t k, l;
        assert(d);

        if (d->type != type)
                return false;

        if (d->minimum_width != minimum_width)
                return false;

        if (d->maximum_width != maximum_width)
                return false;

        if (d->weight != weight)
                return false;

        if (d->align_percent != align_percent)
                return false;

        if (d->ellipsize_percent != ellipsize_percent)
                return false;

        /* If a color/url/uppercase flag is set, refuse to merge */
        if (d->color)
                return false;
        if (d->url)
                return false;
        if (d->uppercase)
                return false;

        k = table_data_size(type, data);
        l = table_data_size(d->type, d->data);

        if (k != l)
                return false;

        return memcmp_safe(data, d->data, l) == 0;
}

static TableData *table_data_new(
                TableDataType type,
                const void *data,
                size_t minimum_width,
                size_t maximum_width,
                unsigned weight,
                unsigned align_percent,
                unsigned ellipsize_percent) {

        size_t data_size;
        TableData *d;

        data_size = table_data_size(type, data);

        d = malloc0(offsetof(TableData, data) + data_size);
        if (!d)
                return NULL;

        d->n_ref = 1;
        d->type = type;
        d->minimum_width = minimum_width;
        d->maximum_width = maximum_width;
        d->weight = weight;
        d->align_percent = align_percent;
        d->ellipsize_percent = ellipsize_percent;
        memcpy_safe(d->data, data, data_size);

        return d;
}

int table_add_cell_full(
                Table *t,
                TableCell **ret_cell,
                TableDataType type,
                const void *data,
                size_t minimum_width,
                size_t maximum_width,
                unsigned weight,
                unsigned align_percent,
                unsigned ellipsize_percent) {

        _cleanup_(table_data_unrefp) TableData *d = NULL;
        TableData *p;

        assert(t);
        assert(type >= 0);
        assert(type < _TABLE_DATA_TYPE_MAX);

        /* Determine the cell adjacent to the current one, but one row up */
        if (t->n_cells >= t->n_columns)
                assert_se(p = t->data[t->n_cells - t->n_columns]);
        else
                p = NULL;

        /* If formatting parameters are left unspecified, copy from the previous row */
        if (minimum_width == (size_t) -1)
                minimum_width = p ? p->minimum_width : 1;

        if (weight == (unsigned) -1)
                weight = p ? p->weight : DEFAULT_WEIGHT;

        if (align_percent == (unsigned) -1)
                align_percent = p ? p->align_percent : 0;

        if (ellipsize_percent == (unsigned) -1)
                ellipsize_percent = p ? p->ellipsize_percent : 100;

        assert(align_percent <= 100);
        assert(ellipsize_percent <= 100);

        /* Small optimization: Pretty often adjacent cells in two subsequent lines have the same data and
         * formatting. Let's see if we can reuse the cell data and ref it once more. */

        if (p && table_data_matches(p, type, data, minimum_width, maximum_width, weight, align_percent, ellipsize_percent))
                d = table_data_ref(p);
        else {
                d = table_data_new(type, data, minimum_width, maximum_width, weight, align_percent, ellipsize_percent);
                if (!d)
                        return -ENOMEM;
        }

        if (!GREEDY_REALLOC(t->data, t->n_allocated, MAX(t->n_cells + 1, t->n_columns)))
                return -ENOMEM;

        if (ret_cell)
                *ret_cell = TABLE_INDEX_TO_CELL(t->n_cells);

        t->data[t->n_cells++] = TAKE_PTR(d);

        return 0;
}

int table_dup_cell(Table *t, TableCell *cell) {
        size_t i;

        assert(t);

        /* Add the data of the specified cell a second time as a new cell to the end. */

        i = TABLE_CELL_TO_INDEX(cell);
        if (i >= t->n_cells)
                return -ENXIO;

        if (!GREEDY_REALLOC(t->data, t->n_allocated, MAX(t->n_cells + 1, t->n_columns)))
                return -ENOMEM;

        t->data[t->n_cells++] = table_data_ref(t->data[i]);
        return 0;
}

static int table_dedup_cell(Table *t, TableCell *cell) {
        _cleanup_free_ char *curl = NULL;
        TableData *nd, *od;
        size_t i;

        assert(t);

        /* Helper call that ensures the specified cell's data object has a ref count of 1, which we can use before
         * changing a cell's formatting without effecting every other cell's formatting that shares the same data */

        i = TABLE_CELL_TO_INDEX(cell);
        if (i >= t->n_cells)
                return -ENXIO;

        assert_se(od = t->data[i]);
        if (od->n_ref == 1)
                return 0;

        assert(od->n_ref > 1);

        if (od->url) {
                curl = strdup(od->url);
                if (!curl)
                        return -ENOMEM;
        }

        nd = table_data_new(
                        od->type,
                        od->data,
                        od->minimum_width,
                        od->maximum_width,
                        od->weight,
                        od->align_percent,
                        od->ellipsize_percent);
        if (!nd)
                return -ENOMEM;

        nd->color = od->color;
        nd->url = TAKE_PTR(curl);
        nd->uppercase = od->uppercase;

        table_data_unref(od);
        t->data[i] = nd;

        assert(nd->n_ref == 1);

        return 1;
}

static TableData *table_get_data(Table *t, TableCell *cell) {
        size_t i;

        assert(t);
        assert(cell);

        /* Get the data object of the specified cell, or NULL if it doesn't exist */

        i = TABLE_CELL_TO_INDEX(cell);
        if (i >= t->n_cells)
                return NULL;

        assert(t->data[i]);
        assert(t->data[i]->n_ref > 0);

        return t->data[i];
}

int table_set_minimum_width(Table *t, TableCell *cell, size_t minimum_width) {
        int r;

        assert(t);
        assert(cell);

        if (minimum_width == (size_t) -1)
                minimum_width = 1;

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        table_get_data(t, cell)->minimum_width = minimum_width;
        return 0;
}

int table_set_maximum_width(Table *t, TableCell *cell, size_t maximum_width) {
        int r;

        assert(t);
        assert(cell);

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        table_get_data(t, cell)->maximum_width = maximum_width;
        return 0;
}

int table_set_weight(Table *t, TableCell *cell, unsigned weight) {
        int r;

        assert(t);
        assert(cell);

        if (weight == (unsigned) -1)
                weight = DEFAULT_WEIGHT;

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        table_get_data(t, cell)->weight = weight;
        return 0;
}

int table_set_align_percent(Table *t, TableCell *cell, unsigned percent) {
        int r;

        assert(t);
        assert(cell);

        if (percent == (unsigned) -1)
                percent = 0;

        assert(percent <= 100);

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        table_get_data(t, cell)->align_percent = percent;
        return 0;
}

int table_set_ellipsize_percent(Table *t, TableCell *cell, unsigned percent) {
        int r;

        assert(t);
        assert(cell);

        if (percent == (unsigned) -1)
                percent = 100;

        assert(percent <= 100);

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        table_get_data(t, cell)->ellipsize_percent = percent;
        return 0;
}

int table_set_color(Table *t, TableCell *cell, const char *color) {
        int r;

        assert(t);
        assert(cell);

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        table_get_data(t, cell)->color = empty_to_null(color);
        return 0;
}

int table_set_url(Table *t, TableCell *cell, const char *url) {
        _cleanup_free_ char *copy = NULL;
        int r;

        assert(t);
        assert(cell);

        if (url) {
                copy = strdup(url);
                if (!copy)
                        return -ENOMEM;
        }

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        return free_and_replace(table_get_data(t, cell)->url, copy);
}

int table_set_uppercase(Table *t, TableCell *cell, bool b) {
        TableData *d;
        int r;

        assert(t);
        assert(cell);

        r = table_dedup_cell(t, cell);
        if (r < 0)
                return r;

        assert_se(d = table_get_data(t, cell));

        if (d->uppercase == b)
                return 0;

        d->formatted = mfree(d->formatted);
        d->uppercase = b;
        return 1;
}

int table_update(Table *t, TableCell *cell, TableDataType type, const void *data) {
        _cleanup_free_ char *curl = NULL;
        TableData *nd, *od;
        size_t i;

        assert(t);
        assert(cell);

        i = TABLE_CELL_TO_INDEX(cell);
        if (i >= t->n_cells)
                return -ENXIO;

        assert_se(od = t->data[i]);

        if (od->url) {
                curl = strdup(od->url);
                if (!curl)
                        return -ENOMEM;
        }

        nd = table_data_new(
                        type,
                        data,
                        od->minimum_width,
                        od->maximum_width,
                        od->weight,
                        od->align_percent,
                        od->ellipsize_percent);
        if (!nd)
                return -ENOMEM;

        nd->color = od->color;
        nd->url = TAKE_PTR(curl);
        nd->uppercase = od->uppercase;

        table_data_unref(od);
        t->data[i] = nd;

        return 0;
}

int table_add_many_internal(Table *t, TableDataType first_type, ...) {
        TableDataType type;
        va_list ap;
        int r;

        assert(t);
        assert(first_type >= 0);
        assert(first_type < _TABLE_DATA_TYPE_MAX);

        type = first_type;

        va_start(ap, first_type);
        for (;;) {
                const void *data;
                union {
                        uint64_t size;
                        usec_t usec;
                        uint32_t uint32;
                        uint64_t uint64;
                        int percent;
                        bool b;
                } buffer;

                switch (type) {

                case TABLE_EMPTY:
                        data = NULL;
                        break;

                case TABLE_STRING:
                        data = va_arg(ap, const char *);
                        break;

                case TABLE_BOOLEAN:
                        buffer.b = va_arg(ap, int);
                        data = &buffer.b;
                        break;

                case TABLE_TIMESTAMP:
                case TABLE_TIMESPAN:
                        buffer.usec = va_arg(ap, usec_t);
                        data = &buffer.usec;
                        break;

                case TABLE_SIZE:
                        buffer.size = va_arg(ap, uint64_t);
                        data = &buffer.size;
                        break;

                case TABLE_UINT32:
                        buffer.uint32 = va_arg(ap, uint32_t);
                        data = &buffer.uint32;
                        break;

                case TABLE_UINT64:
                        buffer.uint64 = va_arg(ap, uint64_t);
                        data = &buffer.uint64;
                        break;

                case TABLE_PERCENT:
                        buffer.percent = va_arg(ap, int);
                        data = &buffer.percent;
                        break;

                case _TABLE_DATA_TYPE_MAX:
                        /* Used as end marker */
                        va_end(ap);
                        return 0;

                default:
                        assert_not_reached("Uh? Unexpected data type.");
                }

                r = table_add_cell(t, NULL, type, data);
                if (r < 0) {
                        va_end(ap);
                        return r;
                }

                type = va_arg(ap, TableDataType);
        }
}

void table_set_header(Table *t, bool b) {
        assert(t);

        t->header = b;
}

void table_set_width(Table *t, size_t width) {
        assert(t);

        t->width = width;
}

int table_set_display(Table *t, size_t first_column, ...) {
        size_t allocated, column;
        va_list ap;

        assert(t);

        allocated = t->n_display_map;
        column = first_column;

        va_start(ap, first_column);
        for (;;) {
                assert(column < t->n_columns);

                if (!GREEDY_REALLOC(t->display_map, allocated, MAX(t->n_columns, t->n_display_map+1))) {
                        va_end(ap);
                        return -ENOMEM;
                }

                t->display_map[t->n_display_map++] = column;

                column = va_arg(ap, size_t);
                if (column == (size_t) -1)
                        break;

        }
        va_end(ap);

        return 0;
}

int table_set_sort(Table *t, size_t first_column, ...) {
        size_t allocated, column;
        va_list ap;

        assert(t);

        allocated = t->n_sort_map;
        column = first_column;

        va_start(ap, first_column);
        for (;;) {
                assert(column < t->n_columns);

                if (!GREEDY_REALLOC(t->sort_map, allocated, MAX(t->n_columns, t->n_sort_map+1))) {
                        va_end(ap);
                        return -ENOMEM;
                }

                t->sort_map[t->n_sort_map++] = column;

                column = va_arg(ap, size_t);
                if (column == (size_t) -1)
                        break;
        }
        va_end(ap);

        return 0;
}

static int cell_data_compare(TableData *a, size_t index_a, TableData *b, size_t index_b) {
        assert(a);
        assert(b);

        if (a->type == b->type) {

                /* We only define ordering for cells of the same data type. If cells with different data types are
                 * compared we follow the order the cells were originally added in */

                switch (a->type) {

                case TABLE_STRING:
                        return strcmp(a->string, b->string);

                case TABLE_BOOLEAN:
                        if (!a->boolean && b->boolean)
                                return -1;
                        if (a->boolean && !b->boolean)
                                return 1;
                        return 0;

                case TABLE_TIMESTAMP:
                        return CMP(a->timestamp, b->timestamp);

                case TABLE_TIMESPAN:
                        return CMP(a->timespan, b->timespan);

                case TABLE_SIZE:
                        return CMP(a->size, b->size);

                case TABLE_UINT32:
                        return CMP(a->uint32, b->uint32);

                case TABLE_UINT64:
                        return CMP(a->uint64, b->uint64);

                case TABLE_PERCENT:
                        return CMP(a->percent, b->percent);

                default:
                        ;
                }
        }

        /* Generic fallback using the original order in which the cells where added. */
        return CMP(index_a, index_b);
}

static int table_data_compare(const size_t *a, const size_t *b, Table *t) {
        size_t i;
        int r;

        assert(t);
        assert(t->sort_map);

        /* Make sure the header stays at the beginning */
        if (*a < t->n_columns && *b < t->n_columns)
                return 0;
        if (*a < t->n_columns)
                return -1;
        if (*b < t->n_columns)
                return 1;

        /* Order other lines by the sorting map */
        for (i = 0; i < t->n_sort_map; i++) {
                TableData *d, *dd;

                d = t->data[*a + t->sort_map[i]];
                dd = t->data[*b + t->sort_map[i]];

                r = cell_data_compare(d, *a, dd, *b);
                if (r != 0)
                        return t->reverse_map && t->reverse_map[t->sort_map[i]] ? -r : r;
        }

        /* Order identical lines by the order there were originally added in */
        return CMP(*a, *b);
}

static const char *table_data_format(TableData *d) {
        assert(d);

        if (d->formatted)
                return d->formatted;

        switch (d->type) {
        case TABLE_EMPTY:
                return "";

        case TABLE_STRING:
                if (d->uppercase) {
                        char *p, *q;

                        d->formatted = new(char, strlen(d->string) + 1);
                        if (!d->formatted)
                                return NULL;

                        for (p = d->string, q = d->formatted; *p; p++, q++)
                                *q = (char) toupper((unsigned char) *p);
                        *q = 0;

                        return d->formatted;
                }

                return d->string;

        case TABLE_BOOLEAN:
                return yes_no(d->boolean);

        case TABLE_TIMESTAMP: {
                _cleanup_free_ char *p;

                p = new(char, FORMAT_TIMESTAMP_MAX);
                if (!p)
                        return NULL;

                if (!format_timestamp(p, FORMAT_TIMESTAMP_MAX, d->timestamp))
                        return "n/a";

                d->formatted = TAKE_PTR(p);
                break;
        }

        case TABLE_TIMESPAN: {
                _cleanup_free_ char *p;

                p = new(char, FORMAT_TIMESPAN_MAX);
                if (!p)
                        return NULL;

                if (!format_timespan(p, FORMAT_TIMESPAN_MAX, d->timespan, 0))
                        return "n/a";

                d->formatted = TAKE_PTR(p);
                break;
        }

        case TABLE_SIZE: {
                _cleanup_free_ char *p;

                p = new(char, FORMAT_BYTES_MAX);
                if (!p)
                        return NULL;

                if (!format_bytes(p, FORMAT_BYTES_MAX, d->size))
                        return "n/a";

                d->formatted = TAKE_PTR(p);
                break;
        }

        case TABLE_UINT32: {
                _cleanup_free_ char *p;

                p = new(char, DECIMAL_STR_WIDTH(d->uint32) + 1);
                if (!p)
                        return NULL;

                sprintf(p, "%" PRIu32, d->uint32);
                d->formatted = TAKE_PTR(p);
                break;
        }

        case TABLE_UINT64: {
                _cleanup_free_ char *p;

                p = new(char, DECIMAL_STR_WIDTH(d->uint64) + 1);
                if (!p)
                        return NULL;

                sprintf(p, "%" PRIu64, d->uint64);
                d->formatted = TAKE_PTR(p);
                break;
        }

        case TABLE_PERCENT: {
                _cleanup_free_ char *p;

                p = new(char, DECIMAL_STR_WIDTH(d->percent) + 2);
                if (!p)
                        return NULL;

                sprintf(p, "%i%%" , d->percent);
                d->formatted = TAKE_PTR(p);
                break;
        }

        default:
                assert_not_reached("Unexpected type?");
        }

        return d->formatted;
}

static int table_data_requested_width(TableData *d, size_t *ret) {
        const char *t;
        size_t l;

        t = table_data_format(d);
        if (!t)
                return -ENOMEM;

        l = utf8_console_width(t);
        if (l == (size_t) -1)
                return -EINVAL;

        if (d->maximum_width != (size_t) -1 && l > d->maximum_width)
                l = d->maximum_width;

        if (l < d->minimum_width)
                l = d->minimum_width;

        *ret = l;
        return 0;
}

static char *align_string_mem(const char *str, const char *url, size_t new_length, unsigned percent) {
        size_t w = 0, space, lspace, old_length, clickable_length;
        _cleanup_free_ char *clickable = NULL;
        const char *p;
        char *ret;
        size_t i;
        int r;

        /* As with ellipsize_mem(), 'old_length' is a byte size while 'new_length' is a width in character cells */

        assert(str);
        assert(percent <= 100);

        old_length = strlen(str);

        if (url) {
                r = terminal_urlify(url, str, &clickable);
                if (r < 0)
                        return NULL;

                clickable_length = strlen(clickable);
        } else
                clickable_length = old_length;

        /* Determine current width on screen */
        p = str;
        while (p < str + old_length) {
                char32_t c;

                if (utf8_encoded_to_unichar(p, &c) < 0) {
                        p++, w++; /* count invalid chars as 1 */
                        continue;
                }

                p = utf8_next_char(p);
                w += unichar_iswide(c) ? 2 : 1;
        }

        /* Already wider than the target, if so, don't do anything */
        if (w >= new_length)
                return clickable ? TAKE_PTR(clickable) : strdup(str);

        /* How much spaces shall we add? An how much on the left side? */
        space = new_length - w;
        lspace = space * percent / 100U;

        ret = new(char, space + clickable_length + 1);
        if (!ret)
                return NULL;

        for (i = 0; i < lspace; i++)
                ret[i] = ' ';
        memcpy(ret + lspace, clickable ?: str, clickable_length);
        for (i = lspace + clickable_length; i < space + clickable_length; i++)
                ret[i] = ' ';

        ret[space + clickable_length] = 0;
        return ret;
}

int table_print(Table *t, FILE *f) {
        size_t n_rows, *minimum_width, *maximum_width, display_columns, *requested_width,
                i, j, table_minimum_width, table_maximum_width, table_requested_width, table_effective_width,
                *width;
        _cleanup_free_ size_t *sorted = NULL;
        uint64_t *column_weight, weight_sum;
        int r;

        assert(t);

        if (!f)
                f = stdout;

        /* Ensure we have no incomplete rows */
        assert(t->n_cells % t->n_columns == 0);

        n_rows = t->n_cells / t->n_columns;
        assert(n_rows > 0); /* at least the header row must be complete */

        if (t->sort_map) {
                /* If sorting is requested, let's calculate an index table we use to lookup the actual index to display with. */

                sorted = new(size_t, n_rows);
                if (!sorted)
                        return -ENOMEM;

                for (i = 0; i < n_rows; i++)
                        sorted[i] = i * t->n_columns;

                typesafe_qsort_r(sorted, n_rows, table_data_compare, t);
        }

        if (t->display_map)
                display_columns = t->n_display_map;
        else
                display_columns = t->n_columns;

        assert(display_columns > 0);

        minimum_width = newa(size_t, display_columns);
        maximum_width = newa(size_t, display_columns);
        requested_width = newa(size_t, display_columns);
        width = newa(size_t, display_columns);
        column_weight = newa0(uint64_t, display_columns);

        for (j = 0; j < display_columns; j++) {
                minimum_width[j] = 1;
                maximum_width[j] = (size_t) -1;
                requested_width[j] = (size_t) -1;
        }

        /* First pass: determine column sizes */
        for (i = t->header ? 0 : 1; i < n_rows; i++) {
                TableData **row;

                /* Note that we don't care about ordering at this time, as we just want to determine column sizes,
                 * hence we don't care for sorted[] during the first pass. */
                row = t->data + i * t->n_columns;

                for (j = 0; j < display_columns; j++) {
                        TableData *d;
                        size_t req;

                        assert_se(d = row[t->display_map ? t->display_map[j] : j]);

                        r = table_data_requested_width(d, &req);
                        if (r < 0)
                                return r;

                        /* Determine the biggest width that any cell in this column would like to have */
                        if (requested_width[j] == (size_t) -1 ||
                            requested_width[j] < req)
                                requested_width[j] = req;

                        /* Determine the minimum width any cell in this column needs */
                        if (minimum_width[j] < d->minimum_width)
                                minimum_width[j] = d->minimum_width;

                        /* Determine the maximum width any cell in this column needs */
                        if (d->maximum_width != (size_t) -1 &&
                            (maximum_width[j] == (size_t) -1 ||
                             maximum_width[j] > d->maximum_width))
                                maximum_width[j] = d->maximum_width;

                        /* Determine the full columns weight */
                        column_weight[j] += d->weight;
                }
        }

        /* One space between each column */
        table_requested_width = table_minimum_width = table_maximum_width = display_columns - 1;

        /* Calculate the total weight for all columns, plus the minimum, maximum and requested width for the table. */
        weight_sum = 0;
        for (j = 0; j < display_columns; j++) {
                weight_sum += column_weight[j];

                table_minimum_width += minimum_width[j];

                if (maximum_width[j] == (size_t) -1)
                        table_maximum_width = (size_t) -1;
                else
                        table_maximum_width += maximum_width[j];

                table_requested_width += requested_width[j];
        }

        /* Calculate effective table width */
        if (t->width == (size_t) -1)
                table_effective_width = pager_have() ? table_requested_width : MIN(table_requested_width, columns());
        else
                table_effective_width = t->width;

        if (table_maximum_width != (size_t) -1 && table_effective_width > table_maximum_width)
                table_effective_width = table_maximum_width;

        if (table_effective_width < table_minimum_width)
                table_effective_width = table_minimum_width;

        if (table_effective_width >= table_requested_width) {
                size_t extra;

                /* We have extra room, let's distribute it among columns according to their weights. We first provide
                 * each column with what it asked for and the distribute the rest.  */

                extra = table_effective_width - table_requested_width;

                for (j = 0; j < display_columns; j++) {
                        size_t delta;

                        if (weight_sum == 0)
                                width[j] = requested_width[j] + extra / (display_columns - j); /* Avoid division by zero */
                        else
                                width[j] = requested_width[j] + (extra * column_weight[j]) / weight_sum;

                        if (maximum_width[j] != (size_t) -1 && width[j] > maximum_width[j])
                                width[j] = maximum_width[j];

                        if (width[j] < minimum_width[j])
                                width[j] = minimum_width[j];

                        assert(width[j] >= requested_width[j]);
                        delta = width[j] - requested_width[j];

                        /* Subtract what we just added from the rest */
                        if (extra > delta)
                                extra -= delta;
                        else
                                extra = 0;

                        assert(weight_sum >= column_weight[j]);
                        weight_sum -= column_weight[j];
                }

        } else {
                /* We need to compress the table, columns can't get what they asked for. We first provide each column
                 * with the minimum they need, and then distribute anything left. */
                bool finalize = false;
                size_t extra;

                extra = table_effective_width - table_minimum_width;

                for (j = 0; j < display_columns; j++)
                        width[j] = (size_t) -1;

                for (;;) {
                        bool restart = false;

                        for (j = 0; j < display_columns; j++) {
                                size_t delta, w;

                                /* Did this column already get something assigned? If so, let's skip to the next */
                                if (width[j] != (size_t) -1)
                                        continue;

                                if (weight_sum == 0)
                                        w = minimum_width[j] + extra / (display_columns - j); /* avoid division by zero */
                                else
                                        w = minimum_width[j] + (extra * column_weight[j]) / weight_sum;

                                if (w >= requested_width[j]) {
                                        /* Never give more than requested. If we hit a column like this, there's more
                                         * space to allocate to other columns which means we need to restart the
                                         * iteration. However, if we hit a column like this, let's assign it the space
                                         * it wanted for good early.*/

                                        w = requested_width[j];
                                        restart = true;

                                } else if (!finalize)
                                        continue;

                                width[j] = w;

                                assert(w >= minimum_width[j]);
                                delta = w - minimum_width[j];

                                assert(delta <= extra);
                                extra -= delta;

                                assert(weight_sum >= column_weight[j]);
                                weight_sum -= column_weight[j];

                                if (restart && !finalize)
                                        break;
                        }

                        if (finalize)
                                break;

                        if (!restart)
                                finalize = true;
                }
        }

        /* Second pass: show output */
        for (i = t->header ? 0 : 1; i < n_rows; i++) {
                TableData **row;

                if (sorted)
                        row = t->data + sorted[i];
                else
                        row = t->data + i * t->n_columns;

                for (j = 0; j < display_columns; j++) {
                        _cleanup_free_ char *buffer = NULL;
                        const char *field;
                        TableData *d;
                        size_t l;

                        assert_se(d = row[t->display_map ? t->display_map[j] : j]);

                        field = table_data_format(d);
                        if (!field)
                                return -ENOMEM;

                        l = utf8_console_width(field);
                        if (l > width[j]) {
                                /* Field is wider than allocated space. Let's ellipsize */

                                buffer = ellipsize(field, width[j], d->ellipsize_percent);
                                if (!buffer)
                                        return -ENOMEM;

                                field = buffer;

                        } else if (l < width[j]) {
                                /* Field is shorter than allocated space. Let's align with spaces */

                                buffer = align_string_mem(field, d->url, width[j], d->align_percent);
                                if (!buffer)
                                        return -ENOMEM;

                                field = buffer;
                        }

                        if (l >= width[j] && d->url) {
                                _cleanup_free_ char *clickable = NULL;

                                r = terminal_urlify(d->url, field, &clickable);
                                if (r < 0)
                                        return r;

                                free_and_replace(buffer, clickable);
                                field = buffer;
                        }

                        if (row == t->data) /* underline header line fully, including the column separator */
                                fputs(ansi_underline(), f);

                        if (j > 0)
                                fputc(' ', f); /* column separator */

                        if (d->color && colors_enabled()) {
                                if (row == t->data) /* first undo header underliner */
                                        fputs(ANSI_NORMAL, f);

                                fputs(d->color, f);
                        }

                        fputs(field, f);

                        if (colors_enabled() && (d->color || row == t->data))
                                fputs(ANSI_NORMAL, f);
                }

                fputc('\n', f);
        }

        return fflush_and_check(f);
}

int table_format(Table *t, char **ret) {
        _cleanup_fclose_ FILE *f = NULL;
        char *buf = NULL;
        size_t sz = 0;
        int r;

        f = open_memstream_unlocked(&buf, &sz);
        if (!f)
                return -ENOMEM;

        r = table_print(t, f);
        if (r < 0)
                return r;

        f = safe_fclose(f);

        *ret = buf;

        return 0;
}

size_t table_get_rows(Table *t) {
        if (!t)
                return 0;

        assert(t->n_columns > 0);
        return t->n_cells / t->n_columns;
}

size_t table_get_columns(Table *t) {
        if (!t)
                return 0;

        assert(t->n_columns > 0);
        return t->n_columns;
}

int table_set_reverse(Table *t, size_t column, bool b) {
        assert(t);
        assert(column < t->n_columns);

        if (!t->reverse_map) {
                if (!b)
                        return 0;

                t->reverse_map = new0(bool, t->n_columns);
                if (!t->reverse_map)
                        return -ENOMEM;
        }

        t->reverse_map[column] = b;
        return 0;
}

TableCell *table_get_cell(Table *t, size_t row, size_t column) {
        size_t i;

        assert(t);

        if (column >= t->n_columns)
                return NULL;

        i = row * t->n_columns + column;
        if (i >= t->n_cells)
                return NULL;

        return TABLE_INDEX_TO_CELL(i);
}

const void *table_get(Table *t, TableCell *cell) {
        TableData *d;

        assert(t);

        d = table_get_data(t, cell);
        if (!d)
                return NULL;

        return d->data;
}

const void* table_get_at(Table *t, size_t row, size_t column) {
        TableCell *cell;

        cell = table_get_cell(t, row, column);
        if (!cell)
                return NULL;

        return table_get(t, cell);
}

static int table_data_to_json(TableData *d, JsonVariant **ret) {

        switch (d->type) {

        case TABLE_EMPTY:
                return json_variant_new_null(ret);

        case TABLE_STRING:
                return json_variant_new_string(ret, d->string);

        case TABLE_BOOLEAN:
                return json_variant_new_boolean(ret, d->boolean);

        case TABLE_TIMESTAMP:
                if (d->timestamp == USEC_INFINITY)
                        return json_variant_new_null(ret);

                return json_variant_new_unsigned(ret, d->timestamp);

        case TABLE_TIMESPAN:
                if (d->timespan == USEC_INFINITY)
                        return json_variant_new_null(ret);

                return json_variant_new_unsigned(ret, d->timespan);

        case TABLE_SIZE:
                if (d->size == (size_t) -1)
                        return json_variant_new_null(ret);

                return json_variant_new_unsigned(ret, d->size);

        case TABLE_UINT32:
                return json_variant_new_unsigned(ret, d->uint32);

        case TABLE_UINT64:
                return json_variant_new_unsigned(ret, d->uint64);

        case TABLE_PERCENT:
                return json_variant_new_integer(ret, d->percent);

        default:
                return -EINVAL;
        }
}

int table_to_json(Table *t, JsonVariant **ret) {
        JsonVariant **rows = NULL, **elements = NULL;
        _cleanup_free_ size_t *sorted = NULL;
        size_t n_rows, i, j, display_columns;
        int r;

        assert(t);

        /* Ensure we have no incomplete rows */
        assert(t->n_cells % t->n_columns == 0);

        n_rows = t->n_cells / t->n_columns;
        assert(n_rows > 0); /* at least the header row must be complete */

        if (t->sort_map) {
                /* If sorting is requested, let's calculate an index table we use to lookup the actual index to display with. */

                sorted = new(size_t, n_rows);
                if (!sorted) {
                        r = -ENOMEM;
                        goto finish;
                }

                for (i = 0; i < n_rows; i++)
                        sorted[i] = i * t->n_columns;

                typesafe_qsort_r(sorted, n_rows, table_data_compare, t);
        }

        if (t->display_map)
                display_columns = t->n_display_map;
        else
                display_columns = t->n_columns;
        assert(display_columns > 0);

        elements = new0(JsonVariant*, display_columns * 2);
        if (!elements) {
                r = -ENOMEM;
                goto finish;
        }

        for (j = 0; j < display_columns; j++) {
                TableData *d;

                assert_se(d = t->data[t->display_map ? t->display_map[j] : j]);

                r = table_data_to_json(d, elements + j*2);
                if (r < 0)
                        goto finish;
        }

        rows = new0(JsonVariant*, n_rows-1);
        if (!rows) {
                r = -ENOMEM;
                goto finish;
        }

        for (i = 1; i < n_rows; i++) {
                TableData **row;

                if (sorted)
                        row = t->data + sorted[i];
                else
                        row = t->data + i * t->n_columns;

                for (j = 0; j < display_columns; j++) {
                        TableData *d;
                        size_t k;

                        assert_se(d = row[t->display_map ? t->display_map[j] : j]);

                        k = j*2+1;
                        elements[k] = json_variant_unref(elements[k]);

                        r = table_data_to_json(d, elements + k);
                        if (r < 0)
                                goto finish;
                }

                r = json_variant_new_object(rows + i - 1, elements, display_columns * 2);
                if (r < 0)
                        goto finish;
        }

        r = json_variant_new_array(ret, rows, n_rows - 1);

finish:
        if (rows) {
                json_variant_unref_many(rows, n_rows-1);
                free(rows);
        }

        if (elements) {
                json_variant_unref_many(elements, display_columns*2);
                free(elements);
        }

        return r;
}

int table_print_json(Table *t, FILE *f, JsonFormatFlags flags) {
        _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
        int r;

        assert(t);

        if (!f)
                f = stdout;

        r = table_to_json(t, &v);
        if (r < 0)
                return r;

        json_variant_dump(v, flags, f, NULL);

        return fflush_and_check(f);
}