HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/format-table.c

107,089 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 518ef5bd25f38caccb277111a5696205a33034a4

Lines 2001–3000 of 3,252

        return 0;
}
 
static int table_data_requested_width_height(
                Table *table,
                TableData *d,
                size_t available_width,
                size_t *ret_width,
                size_t *ret_height,
                bool *have_soft) {
 
        _cleanup_free_ char *truncated = NULL, *buffer = NULL;
        bool truncation_applied = false;
        size_t width, height;
        bool soft = false;
        const char *t;
        int r;
 
        t = table_data_format_strip_ansi(
                        table,
                        d,
                        /* avoid_uppercasing= */ false,
                        available_width,
                        &soft,
                        &buffer);
        if (!t)
                return -ENOMEM;
 
        if (table->cell_height_max != SIZE_MAX) {
                r = string_truncate_lines(t, table->cell_height_max, &truncated);
                if (r < 0)
                        return r;
                if (r > 0)
                        truncation_applied = true;
 
                t = truncated;
        }
 
        r = console_width_height(t, &width, &height);
        if (r < 0)
                return r;
 
        if (d->maximum_width != SIZE_MAX && width > d->maximum_width)
                width = d->maximum_width;
 
        if (width < d->minimum_width)
                width = d->minimum_width;
 
        if (ret_width)
                *ret_width = width;
        if (ret_height)
                *ret_height = height;
        if (have_soft && soft)
                *have_soft = true;
 
        return truncation_applied;
}
 
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;
        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. Use the same helper the measuring pass uses, so that this
         * function cannot keep a second, more permissive idea of both validity and width of its own.
         * Note that our caller only gets here after utf8_console_width() succeeded on the very same
         * string, so the invalid case below should not be reachable in practice. */
        p = str;
        while (p < str + old_length) {
                int n = utf8_char_console_width(p);
                if (n < 0) {
                        /* Count an invalid sequence as one character of width one. Skip all of it, so
                         * that its continuation bytes are not charged a cell each of their own. */
                        p = utf8_next_char(p);
                        w++;
                        continue;
                }
 
                p = utf8_next_char(p);
                w += n;
        }
 
        /* 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 (size_t i = 0; i < lspace; i++)
                ret[i] = ' ';
        memcpy(ret + lspace, clickable ?: str, clickable_length);
        for (size_t i = lspace + clickable_length; i < space + clickable_length; i++)
                ret[i] = ' ';
 
        ret[space + clickable_length] = 0;
        return ret;
}
 
static bool table_data_isempty(const TableData *d) {
        assert(d);
 
        if (d->type == TABLE_EMPTY)
                return true;
 
        /* Let's also consider an empty strv as truly empty. */
        if (IN_SET(d->type, TABLE_STRV, TABLE_STRV_WRAPPED))
                return strv_isempty(d->strv);
 
        if (d->type == TABLE_JSON)
                return sd_json_variant_is_null(d->json);
 
        /* Note that an empty string we do not consider empty here! */
        return false;
}
 
static const char* table_data_color(const TableData *d) {
        assert(d);
 
        if (d->color)
                return d->color;
 
        /* Let's implicitly color all "empty" cells in grey, in case an "empty_string" is set that is not empty */
        if (table_data_isempty(d))
                return ansi_grey();
 
        if (d->type == TABLE_FIELD)
                return ansi_bright_blue();
 
        return NULL;
}
 
static const char* table_data_underline(const TableData *d) {
        assert(d);
 
        if (d->underline)
                return ansi_add_underline_grey();
 
        if (d->type == TABLE_HEADER)
                return ansi_add_underline();
 
        return NULL;
}
 
static const char* table_data_rgap_underline(const TableData *d) {
        assert(d);
 
        if (d->rgap_underline)
                return ansi_add_underline_grey();
 
        if (d->type == TABLE_HEADER)
                return ansi_add_underline();
 
        return NULL;
}
 
static int table_data_requested_width(Table *table, size_t column, size_t *ret) {
        size_t width = 0;
        int r;
 
        assert(table);
        assert(ret);
 
        for (size_t row = 0; row < table_get_rows(table); row++) {
                TableCell *cell = table_get_cell(table, row, column);
                if (!cell)
                        continue;
 
                TableData *data = table_get_data(table, cell);
                if (!data)
                        continue;
 
                size_t w;
 
                r = table_data_requested_width_height(
                                table, data, SIZE_MAX, &w, /* ret_height= */ NULL, /* have_soft= */ NULL);
                if (r < 0)
                        return r;
 
                width = MAX(width, w);
        }
 
        *ret = width;
        return 0;
}
 
int table_set_column_width(Table *t, size_t column, size_t width) {
        int r = 0;
 
        assert(t);
 
        for (size_t row = 0; row < table_get_rows(t); row++) {
                TableCell *cell = table_get_cell(t, row, column);
                if (!cell)
                        continue;
 
                RET_GATHER(r, table_set_minimum_width(t, cell, width));
        }
 
        return r;
}
 
int table_sync_all_column_widths(size_t column, Table **a) {
        size_t max = 0;
        int r;
 
        /* Make the specified column have the same width in the tables. */
 
        for (Table **t = a; t && *t; t++) {
                size_t w;
 
                r = table_data_requested_width(*t, column, &w);
                if (r < 0)
                        return log_error_errno(r, "Failed to query table column width: %m");
 
                max = MAX(max, w);
        }
 
        r = 0;
        for (Table **t = a; t && *t; t++)
                RET_GATHER(r, table_set_column_width(*t, column, max));
 
        return r;
}
 
int table_print_full(Table *t, FILE *f, bool flush) {
        _cleanup_free_ size_t *sorted = NULL;
        int r;
 
        assert(t);
 
        if (!f)
                f = stdout;
 
        /* Ensure we have no incomplete rows */
        assert(t->n_cells % t->n_columns == 0);
 
        size_t 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 (size_t i = 0; i < n_rows; i++)
                        sorted[i] = i * t->n_columns;
 
                typesafe_qsort_r(sorted, n_rows, table_data_compare, t);
        }
 
        size_t display_columns = t->display_map ? t->n_display_map : t->n_columns;
        assert(display_columns > 0);
 
        size_t *minimum_width = newa(size_t, display_columns),
                *maximum_width = newa(size_t, display_columns),
                *requested_width = newa(size_t, display_columns),
                *width = NULL;
        uint64_t *column_weight = newa0(uint64_t, display_columns);
 
        for (size_t j = 0; j < display_columns; j++) {
                minimum_width[j] = 1;
                maximum_width[j] = SIZE_MAX;
        }
 
        for (unsigned pass = 0; pass < 2; pass++) {
                /* First pass: determine column sizes */
 
                for (size_t j = 0; j < display_columns; j++)
                        requested_width[j] = SIZE_MAX;
 
                bool any_soft = false;
 
                for (size_t 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 (size_t j = 0; j < display_columns; j++) {
                                TableData *d;
                                size_t req_width, req_height;
 
                                assert_se(d = row[t->display_map ? t->display_map[j] : j]);
 
                                r = table_data_requested_width_height(t, d,
                                                                      width ? width[j] : SIZE_MAX,
                                                                      &req_width, &req_height, &any_soft);
                                if (r < 0)
                                        return r;
                                if (r > 0) { /* Truncated because too many lines? */
                                        _cleanup_free_ char *last = NULL, *buffer = NULL;
                                        const char *field;
 
                                        /* If we are going to show only the first few lines of a cell that has
                                         * multiple make sure that we have enough space horizontally to show an
                                         * ellipsis. Hence, let's figure out the last line, and account for its
                                         * length plus ellipsis. */
 
                                        field = table_data_format_strip_ansi(
                                                        t,
                                                        d,
                                                        /* avoid_uppercasing= */ false,
                                                        width ? width[j] : SIZE_MAX,
                                                        &any_soft,
                                                        &buffer);
                                        if (!field)
                                                return -ENOMEM;
 
                                        assert_se(t->cell_height_max > 0);
                                        r = string_extract_line(field, t->cell_height_max-1, &last);
                                        if (r < 0)
                                                return r;
 
                                        req_width = MAX(req_width,
                                                        utf8_console_width(last) +
                                                        utf8_console_width(glyph(GLYPH_ELLIPSIS)));
                                }
 
                                /* Determine the biggest width that any cell in this column would like to have */
                                if (requested_width[j] == SIZE_MAX ||
                                    requested_width[j] < req_width)
                                        requested_width[j] = req_width;
 
                                /* 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_MAX &&
                                    (maximum_width[j] == SIZE_MAX ||
                                     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 */
                size_t table_requested_width, table_minimum_width, table_maximum_width, table_effective_width;
                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. */
                uint64_t weight_sum = 0;
                for (size_t j = 0; j < display_columns; j++) {
                        weight_sum += column_weight[j];
 
                        table_minimum_width += minimum_width[j];
 
                        if (maximum_width[j] == SIZE_MAX)
                                table_maximum_width = SIZE_MAX;
                        else
                                table_maximum_width += maximum_width[j];
 
                        table_requested_width += requested_width[j];
                }
 
                /* Calculate effective table width */
                if (t->width != 0 && t->width != SIZE_MAX)
                        table_effective_width = t->width;
                else if (t->width == 0 ||
                         ((pass > 0 || !any_soft) && (pager_have() || !isatty_safe(STDOUT_FILENO))))
                        table_effective_width = table_requested_width;
                else
                        table_effective_width = MIN(table_requested_width, columns());
 
                if (table_maximum_width != SIZE_MAX && 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 (!width)
                        width = newa(size_t, display_columns);
 
                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 (size_t 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_MAX && width[j] > maximum_width[j])
                                        width[j] = maximum_width[j];
 
                                if (width[j] < minimum_width[j])
                                        width[j] = minimum_width[j];
 
                                delta = LESS_BY(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];
                        }
 
                        break; /* Every column should be happy, no need to repeat calculations. */
                } 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 (size_t j = 0; j < display_columns; j++)
                                width[j] = SIZE_MAX;
 
                        for (;;) {
                                bool restart = false;
 
                                for (size_t 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_MAX)
                                                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;
                        }
 
                        if (!any_soft) /* Some columns got less than requested. If some cells were "soft",
                                        * let's try to reformat them with the new widths. Otherwise, let's
                                        * move on. */
                                break;
                }
        }
 
        /* Second pass: show output */
        for (size_t i = t->header ? 0 : 1; i < n_rows; i++) {
                size_t n_subline = 0;
                bool more_sublines;
                TableData **row;
 
                if (sorted)
                        row = t->data + sorted[i];
                else
                        row = t->data + i * t->n_columns;
 
                do {
                        const char *gap_color = NULL, *gap_underline = NULL;
                        more_sublines = false;
 
                        for (size_t j = 0; j < display_columns; j++) {
                                _cleanup_free_ char *buffer = NULL, *stripped_ansi_buffer = NULL, *extracted = NULL;
                                bool lines_truncated = false;
                                const char *field, *color = NULL, *underline = NULL;
                                TableData *d;
                                size_t l;
 
                                assert_se(d = row[t->display_map ? t->display_map[j] : j]);
 
                                if (colors_enabled())
                                        field = table_data_format(
                                                        t,
                                                        d,
                                                        /* avoid_uppercasing= */ false,
                                                        width[j],
                                                        /* have_soft= */ NULL);
                                else
                                        field = table_data_format_strip_ansi(
                                                        t,
                                                        d,
                                                        /* avoid_uppercasing= */ false,
                                                        width[j],
                                                        /* have_soft= */ NULL,
                                                        &stripped_ansi_buffer);
                                if (!field)
                                        return -ENOMEM;
 
                                r = string_extract_line(field, n_subline, &extracted);
                                if (r < 0)
                                        return r;
                                if (r > 0) {
                                        /* There are more lines to come */
                                        if ((t->cell_height_max == SIZE_MAX || n_subline + 1 < t->cell_height_max))
                                                more_sublines = true; /* There are more lines to come */
                                        else
                                                lines_truncated = true;
                                }
                                if (extracted)
                                        field = extracted;
 
                                l = utf8_console_width(field);
                                if (l > width[j]) {
                                        /* Field is wider than allocated space. Let's ellipsize */
 
                                        buffer = ellipsize(field, width[j], /* ellipsize at the end if we truncated coming lines, otherwise honour configuration */
                                                           lines_truncated ? 100 : d->ellipsize_percent);
                                        if (!buffer)
                                                return -ENOMEM;
 
                                        field = buffer;
                                } else {
                                        if (lines_truncated) {
                                                _cleanup_free_ char *padded = NULL;
 
                                                /* We truncated more lines of this cell, let's add an
                                                 * ellipsis. We first append it, but that might make our
                                                 * string grow above what we have space for, hence ellipsize
                                                 * right after. This will truncate the ellipsis and add a new
                                                 * one. */
 
                                                padded = strjoin(field, glyph(GLYPH_ELLIPSIS));
                                                if (!padded)
                                                        return -ENOMEM;
 
                                                buffer = ellipsize(padded, width[j], 100);
                                                if (!buffer)
                                                        return -ENOMEM;
 
                                                field = buffer;
                                                l = utf8_console_width(field);
                                        }
 
                                        if (l < width[j]) {
                                                _cleanup_free_ char *aligned = NULL;
                                                /* Field is shorter than allocated space. Let's align with spaces */
 
                                                aligned = align_string_mem(field, d->url, width[j], d->align_percent);
                                                if (!aligned)
                                                        return -ENOMEM;
 
                                                /* Drop trailing white spaces of last column when no cosmetics is set. */
                                                if (j == display_columns - 1 &&
                                                    (!colors_enabled() || !table_data_color(d)) &&
                                                    (!underline_enabled() || !table_data_underline(d)) &&
                                                    (!urlify_enabled() || !d->url))
                                                        delete_trailing_chars(aligned, NULL);
 
                                                free_and_replace(buffer, aligned);
                                                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 (colors_enabled() && gap_color)
                                        fputs(gap_color, f);
                                if (underline_enabled() && gap_underline)
                                        fputs(gap_underline, f);
 
                                if (j > 0)
                                        fputc(' ', f); /* column separator left of cell */
 
                                /* Undo gap color/underline */
                                if ((colors_enabled() && gap_color) ||
                                    (underline_enabled() && gap_underline))
                                        fputs(ANSI_NORMAL, f);
 
                                if (colors_enabled()) {
                                        color = table_data_color(d);
                                        if (color)
                                                fputs(color, f);
                                }
 
                                if (underline_enabled()) {
                                        underline = table_data_underline(d);
                                        if (underline)
                                                fputs(underline, f);
                                }
 
                                fputs(field, f);
 
                                /* Reset color afterwards if colors was set or the string to output contained ANSI sequences. */
                                if (color || underline || (d->type == TABLE_STRING_WITH_ANSI && colors_enabled()))
                                        fputs(ANSI_NORMAL, f);
 
                                gap_color = d->rgap_color;
                                gap_underline = table_data_rgap_underline(d);
                        }
 
                        fputc('\n', f);
                        n_subline++;
                } while (more_sublines);
        }
 
        if (!flush)
                return 0;
 
        return fflush_and_check(f);
}
 
int table_print_or_warn(Table *t) {
        int r;
 
        r = table_print(t);
        if (r < 0)
                return table_log_print_error(r);
        return 0;
}
 
int table_format(Table *t, char **ret) {
        _cleanup_(memstream_done) MemStream m = {};
        FILE *f;
        int r;
 
        assert(t);
        assert(ret);
 
        f = memstream_init(&m);
        if (!f)
                return -ENOMEM;
 
        r = table_print_full(t, f, /* flush= */ true);
        if (r < 0)
                return r;
 
        return memstream_finalize(&m, ret, NULL);
}
 
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;
}
 
size_t table_get_current_column(Table *t) {
        if (!t)
                return 0;
 
        assert(t->n_columns > 0);
        return t->n_cells % 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, sd_json_variant **ret) {
 
        switch (d->type) {
 
        case TABLE_EMPTY:
                return sd_json_variant_new_null(ret);
 
        case TABLE_STRING:
        case TABLE_PATH:
        case TABLE_PATH_BASENAME:
        case TABLE_FIELD:
        case TABLE_HEADER:
        case TABLE_VERSION:
                return sd_json_variant_new_string(ret, d->string);
 
        case TABLE_STRV:
        case TABLE_STRV_WRAPPED:
                return sd_json_variant_new_array_strv(ret, d->strv);
 
        case TABLE_BOOLEAN_CHECKMARK:
        case TABLE_BOOLEAN:
                return sd_json_variant_new_boolean(ret, d->boolean);
 
        case TABLE_TRISTATE:
                if (d->tristate < 0)
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_boolean(ret, d->tristate);
 
        case TABLE_TIMESTAMP:
        case TABLE_TIMESTAMP_UTC:
        case TABLE_TIMESTAMP_RELATIVE:
        case TABLE_TIMESTAMP_RELATIVE_MONOTONIC:
        case TABLE_TIMESTAMP_LEFT:
        case TABLE_TIMESTAMP_DATE:
                if (d->timestamp == USEC_INFINITY)
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_unsigned(ret, d->timestamp);
 
        case TABLE_TIMESPAN:
        case TABLE_TIMESPAN_MSEC:
        case TABLE_TIMESPAN_DAY:
                if (d->timespan == USEC_INFINITY)
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_unsigned(ret, d->timespan);
 
        case TABLE_SIZE:
        case TABLE_BPS:
                if (d->size == UINT64_MAX)
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_unsigned(ret, d->size);
 
        case TABLE_INT:
                return sd_json_variant_new_integer(ret, d->int_val);
 
        case TABLE_INT8:
                return sd_json_variant_new_integer(ret, d->int8);
 
        case TABLE_INT16:
                return sd_json_variant_new_integer(ret, d->int16);
 
        case TABLE_INT32:
                return sd_json_variant_new_integer(ret, d->int32);
 
        case TABLE_INT64:
                return sd_json_variant_new_integer(ret, d->int64);
 
        case TABLE_UINT:
                return sd_json_variant_new_unsigned(ret, d->uint_val);
 
        case TABLE_UINT8:
                return sd_json_variant_new_unsigned(ret, d->uint8);
 
        case TABLE_UINT16:
                return sd_json_variant_new_unsigned(ret, d->uint16);
 
        case TABLE_UINT32:
        case TABLE_UINT32_HEX:
        case TABLE_UINT32_HEX_0x:
                return sd_json_variant_new_unsigned(ret, d->uint32);
 
        case TABLE_UINT64:
        case TABLE_UINT64_HEX:
        case TABLE_UINT64_HEX_0x:
                return sd_json_variant_new_unsigned(ret, d->uint64);
 
        case TABLE_PERCENT:
                return sd_json_variant_new_integer(ret, d->percent);
 
        case TABLE_IFINDEX:
                if (d->ifindex <= 0)
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_integer(ret, d->ifindex);
 
        case TABLE_IN_ADDR:
                return sd_json_variant_new_array_bytes(ret, &d->address, FAMILY_ADDRESS_SIZE(AF_INET));
 
        case TABLE_IN6_ADDR:
                return sd_json_variant_new_array_bytes(ret, &d->address, FAMILY_ADDRESS_SIZE(AF_INET6));
 
        case TABLE_ID128:
                return sd_json_variant_new_id128(ret, d->id128);
 
        case TABLE_UUID:
                return sd_json_variant_new_uuid(ret, d->id128);
 
        case TABLE_UID:
                if (!uid_is_valid(d->uid))
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_integer(ret, d->uid);
 
        case TABLE_GID:
                if (!gid_is_valid(d->gid))
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_integer(ret, d->gid);
 
        case TABLE_PID:
                if (!pid_is_valid(d->pid))
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_integer(ret, d->pid);
 
        case TABLE_SIGNAL:
                if (!SIGNAL_VALID(d->int_val))
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_integer(ret, d->int_val);
 
        case TABLE_MODE:
        case TABLE_MODE_INODE_TYPE:
                if (d->mode == MODE_INVALID)
                        return sd_json_variant_new_null(ret);
 
                return sd_json_variant_new_unsigned(ret, d->mode);
 
        case TABLE_DEVNUM:
                if (devnum_is_zero(d->devnum))
                        return sd_json_variant_new_null(ret);
 
                return sd_json_build(ret, SD_JSON_BUILD_ARRAY(
                                                  SD_JSON_BUILD_UNSIGNED(major(d->devnum)),
                                                  SD_JSON_BUILD_UNSIGNED(minor(d->devnum))));
 
        case TABLE_JSON:
                if (!d->json)
                        return sd_json_variant_new_null(ret);
 
                if (ret)
                        *ret = sd_json_variant_ref(d->json);
 
                return 0;
 
        case TABLE_STRING_WITH_ANSI: {
                _cleanup_free_ char *s = strdup(d->string);
                if (!s)
                        return -ENOMEM;
 
                /* We strip the ANSI data when outputting to JSON */
                if (!strip_tab_ansi(&s, /* isz= */ NULL, /* highlight= */ NULL))
                        return -ENOMEM;
 
                return sd_json_variant_new_string(ret, s);
        }
 
        default:
                return -EINVAL;
        }
}
 
char* table_mangle_to_json_field_name(const char *str) {
        /* Tries to make a string more suitable as JSON field name. There are no strict rules defined what a
         * field name can be hence this is a bit vague and black magic. Here's what we do:
         *  - Convert spaces to underscores
         *  - Convert dashes to underscores (some JSON parsers don't like dealing with dashes)
         *  - Convert most other symbols to underscores (for similar reasons)
         *  - Make the first letter of each word lowercase (unless it looks like the whole word is uppercase)
         */
 
        bool new_word = true;
        char *c;
 
        assert(str);
 
        c = strdup(str);
        if (!c)
                return NULL;
 
        for (char *x = c; *x; x++) {
                if (!strchr(ALPHANUMERICAL, *x)) {
                        *x = '_';
                        new_word = true;
                        continue;
                }
 
                if (new_word) {
                        if (ascii_tolower(*(x + 1)) == *(x + 1)) /* Heuristic: if next char is upper-case
                                                                  * then we assume the whole word is all-caps
                                                                  * and avoid lowercasing it. */
                                *x = ascii_tolower(*x);
                        new_word = false;
                }
        }
 
        return c;
}
 
static int table_make_json_field_name(Table *t, TableData *d, char **ret) {
        _cleanup_free_ char *mangled = NULL, *buffer = NULL;
        const char *n;
 
        assert(t);
        assert(d);
        assert(ret);
 
        if (IN_SET(d->type, TABLE_HEADER, TABLE_FIELD))
                n = d->string;
        else {
                n = table_data_format_strip_ansi(
                                t,
                                d,