Skip to content
Myr

jv_print.c

This file

Path

src/jv_print.c

431 lines · 12.7 KiB · C

Last changed by

Improve performance of string output (#3643)Michiel van Slobbebefore adoptionb904884

History of this file

Take it

1#include <assert.h>2#include <stdio.h>3#include <float.h>4#include <string.h>56#include "jv.h"7#include "jv_dtoa.h"8#include "jv_dtoa_tsd.h"9#include "jv_unicode.h"10#include "jv_alloc.h"11#include "jv_private.h"12#include "util.h"1314#ifndef MAX_PRINT_DEPTH15#define MAX_PRINT_DEPTH (10000)16#endif1718#define ESC "\033"19#define COL(c) (ESC "[" c "m")20#define COLRESET (ESC "[0m")2122// Color table. See https://en.wikipedia.org/wiki/ANSI_escape_code#Colors23// for how to choose these. The order is same as jv_kind definition, and24// the last color is used for object keys.25#define DEFAULT_COLORS \26  {COL("0;90"),    COL("0;39"),      COL("0;39"),     COL("0;39"),\27   COL("0;32"),    COL("1;39"),      COL("1;39"),     COL("1;34")};28static const char *const default_colors[] = DEFAULT_COLORS;29static const char *colors[] = DEFAULT_COLORS;30#define COLORS_LEN (sizeof(colors) / sizeof(colors[0]))31#define FIELD_COLOR (colors[7])3233static char *colors_buf = NULL;34int jq_set_colors(const char *code_str) {35  if (code_str == NULL)36    return 1;3738  // the start of each color code in the env var, and the byte after the end of the last one39  const char *codes[COLORS_LEN + 1];40  size_t num_colors;41  // must be initialized before `goto default_colors`, used later to loop over every color42  size_t ci = 0;4344  for (num_colors = 0;; num_colors++) {45    codes[num_colors] = code_str;46    code_str += strspn(code_str, "0123456789;");47    if (code_str[0] == '\0' || num_colors + 1 >= COLORS_LEN) {48      break;49    } else if (code_str[0] != ':') {50      return 0; // invalid character51    }52    code_str++;53  }54  if (codes[num_colors] != code_str) {55    // count the last color and store its end (plus one byte for consistency with starts)56    // an empty last color would be ignored (for cases like "" and "0:")57    num_colors++;58    codes[num_colors] = code_str + 1;59  } else if (num_colors == 0) {60    if (colors_buf != NULL) {61      jv_mem_free(colors_buf);62      colors_buf = NULL;63    }64    goto default_colors;65  }6667  colors_buf = jv_mem_realloc(68    colors_buf,69    // add ESC '[' 'm' to each string70    // '\0' is already included in difference of codes71    codes[num_colors] - codes[0] + 3 * num_colors72  );73  char *cb = colors_buf;74  for (; ci < num_colors; ci++) {75    colors[ci] = cb;76    size_t len = codes[ci + 1] - 1 - codes[ci];7778    cb[0] = ESC[0];79    cb[1] = '[';80    memcpy(cb + 2, codes[ci], len);81    cb[2 + len] = 'm';82    cb[3 + len] = '\0';8384    cb += len + 4;85  }86  default_colors:87  for (; ci < COLORS_LEN; ci++)88    colors[ci] = default_colors[ci];89  return 1;90}9192static void put_buf(const char *s, int len, FILE *fout, jv *strout, int is_tty) {93  if (strout) {94    *strout = jv_string_append_buf(*strout, s, len);95  } else {96    if (len == -1)97      len = strlen(s);98    priv_fwrite(s, len, fout, is_tty); /* see util.h */99  }100}101102static void put_char(char c, FILE* fout, jv* strout, int T) {103  put_buf(&c, 1, fout, strout, T);104}105106static void put_str(const char* s, FILE* fout, jv* strout, int T) {107  put_buf(s, strlen(s), fout, strout, T);108}109110static void put_indent(int n, int flags, FILE* fout, jv* strout, int T) {111  if (flags & JV_PRINT_TAB) {112    while (n--)113      put_char('\t', fout, strout, T);114  } else {115    n *= ((flags & (JV_PRINT_SPACE0 | JV_PRINT_SPACE1 | JV_PRINT_SPACE2)) >> 8);116    while (n--)117      put_char(' ', fout, strout, T);118  }119}120121static void jvp_dump_string(jv str, int ascii_only, FILE* F, jv* S, int T) {122  assert(jv_get_kind(str) == JV_KIND_STRING);123  const char* i = jv_string_value(str);124  const char* end = i + jv_string_length_bytes(jv_copy(str));125  const char* cstart;126  int c = 0;127  char buf[32];128  put_char('"', F, S, T);129  while (i < end) {130    // Write each run of bytes that need no escaping with a single call.131    for (cstart = i; cstart < end; cstart++) {132      unsigned char b = *cstart;133      if (b < 0x20 || b == '"' || b == '\\' || b == 0x7F || (ascii_only && b >= 0x80))134        break;135    }136    if (cstart > i)137      put_buf(i, cstart - i, F, S, T);138    if (cstart == end)139      break;140    i = jvp_utf8_next(cstart, end, &c);141    assert(c != -1);142    int unicode_escape = 0;143    if (0x20 <= c && c <= 0x7E) {144      // printable ASCII145      if (c == '"' || c == '\\') {146        put_char('\\', F, S, T);147      }148      put_char(c, F, S, T);149    } else if (c < 0x20 || c == 0x7F) {150      // ASCII control character151      switch (c) {152      case '\b':153        put_char('\\', F, S, T);154        put_char('b', F, S, T);155        break;156      case '\t':157        put_char('\\', F, S, T);158        put_char('t', F, S, T);159        break;160      case '\r':161        put_char('\\', F, S, T);162        put_char('r', F, S, T);163        break;164      case '\n':165        put_char('\\', F, S, T);166        put_char('n', F, S, T);167        break;168      case '\f':169        put_char('\\', F, S, T);170        put_char('f', F, S, T);171        break;172      default:173        unicode_escape = 1;174        break;175      }176    } else {177      if (ascii_only) {178        unicode_escape = 1;179      } else {180        put_buf(cstart, i - cstart, F, S, T);181      }182    }183    if (unicode_escape) {184      if (c <= 0xffff) {185        snprintf(buf, sizeof(buf), "\\u%04x", c);186      } else {187        c -= 0x10000;188        snprintf(buf, sizeof(buf), "\\u%04x\\u%04x",189                0xD800 | ((c & 0xffc00) >> 10),190                0xDC00 | (c & 0x003ff));191      }192      put_str(buf, F, S, T);193    }194  }195  assert(c != -1);196  put_char('"', F, S, T);197}198199static void put_refcnt(struct dtoa_context* C, int refcnt, FILE *F, jv* S, int T){200  char buf[JVP_DTOA_FMT_MAX_LEN];201  put_char(' ', F, S, T);202  put_char('(', F, S, T);203  put_str(jvp_dtoa_fmt(C, buf, refcnt), F, S, T);204  put_char(')', F, S, T);205}206207static void jv_dump_term(struct dtoa_context* C, jv x, int flags, int indent, FILE* F, jv* S) {208  char buf[JVP_DTOA_FMT_MAX_LEN];209  const char* color = 0;210  double refcnt = (flags & JV_PRINT_REFCOUNT) ? jv_get_refcnt(x) - 1 : -1;211  if ((flags & JV_PRINT_COLOR) && jv_get_kind(x) != JV_KIND_INVALID) {212    color = colors[(int)jv_get_kind(x) - 1];213    put_str(color, F, S, flags & JV_PRINT_ISATTY);214  }215  if (indent > MAX_PRINT_DEPTH) {216    put_str("<skipped: too deep>", F, S, flags & JV_PRINT_ISATTY);217  } else switch (jv_get_kind(x)) {218  default:219  case JV_KIND_INVALID:220    if (flags & JV_PRINT_INVALID) {221      jv msg = jv_invalid_get_msg(jv_copy(x));222      if (jv_get_kind(msg) == JV_KIND_STRING) {223        put_str("<invalid:", F, S, flags & JV_PRINT_ISATTY);224        jvp_dump_string(msg, flags | JV_PRINT_ASCII, F, S, flags & JV_PRINT_ISATTY);225        put_char('>', F, S, flags & JV_PRINT_ISATTY);226      } else {227        put_str("<invalid>", F, S, flags & JV_PRINT_ISATTY);228      }229    } else {230      assert(0 && "Invalid value");231    }232    break;233  case JV_KIND_NULL:234    put_str("null", F, S, flags & JV_PRINT_ISATTY);235    break;236  case JV_KIND_FALSE:237    put_str("false", F, S, flags & JV_PRINT_ISATTY);238    break;239  case JV_KIND_TRUE:240    put_str("true", F, S, flags & JV_PRINT_ISATTY);241    break;242  case JV_KIND_NUMBER: {243    if (jvp_number_is_nan(x)) {244      jv_dump_term(C, jv_null(), flags, indent, F, S);245    } else {246#ifdef USE_DECNUM247      const char * literal_data = jv_number_get_literal(x);248      if (literal_data) {249        put_str(literal_data, F, S, flags & JV_PRINT_ISATTY);250      } else {251#endif252        double d = jv_number_value(x);253        if (d != d) {254          // JSON doesn't have NaN, so we'll render it as "null"255          put_str("null", F, S, flags & JV_PRINT_ISATTY);256        } else {257          // Normalise infinities to something we can print in valid JSON258          if (d > DBL_MAX) d = DBL_MAX;259          if (d < -DBL_MAX) d = -DBL_MAX;260          put_str(jvp_dtoa_fmt(C, buf, d), F, S, flags & JV_PRINT_ISATTY);261        }262      }263#ifdef USE_DECNUM264    }265#endif266    break;267  }268  case JV_KIND_STRING:269    jvp_dump_string(x, flags & JV_PRINT_ASCII, F, S, flags & JV_PRINT_ISATTY);270    if (flags & JV_PRINT_REFCOUNT)271      put_refcnt(C, refcnt, F, S, flags & JV_PRINT_ISATTY);272    break;273  case JV_KIND_ARRAY: {274    if (jv_array_length(jv_copy(x)) == 0) {275      put_str("[]", F, S, flags & JV_PRINT_ISATTY);276      break;277    }278    put_char('[', F, S, flags & JV_PRINT_ISATTY);279    jv_array_foreach(x, i, elem) {280      if (i!=0) {281        if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);282        put_char(',', F, S, flags & JV_PRINT_ISATTY);283      }284      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);285      if (flags & JV_PRINT_PRETTY) {286        put_char('\n', F, S, flags & JV_PRINT_ISATTY);287        put_indent(indent + 1, flags, F, S, flags & JV_PRINT_ISATTY);288      }289      jv_dump_term(C, elem, flags, indent + 1, F, S);290    }291    if (flags & JV_PRINT_PRETTY) {292      put_char('\n', F, S, flags & JV_PRINT_ISATTY);293      put_indent(indent, flags, F, S, flags & JV_PRINT_ISATTY);294    }295    if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);296    put_char(']', F, S, flags & JV_PRINT_ISATTY);297    if (flags & JV_PRINT_REFCOUNT)298      put_refcnt(C, refcnt, F, S, flags & JV_PRINT_ISATTY);299    break;300  }301  case JV_KIND_OBJECT: {302    if (jv_object_length(jv_copy(x)) == 0) {303      put_str("{}", F, S, flags & JV_PRINT_ISATTY);304      break;305    }306    put_char('{', F, S, flags & JV_PRINT_ISATTY);307    int first = 1;308    int i = 0;309    jv keyset = jv_null();310    while (1) {311      jv key, value;312      if (flags & JV_PRINT_SORTED) {313        if (first) {314          keyset = jv_keys(jv_copy(x));315          i = 0;316        } else {317          i++;318        }319        if (i >= jv_array_length(jv_copy(keyset))) {320          jv_free(keyset);321          break;322        }323        key = jv_array_get(jv_copy(keyset), i);324        value = jv_object_get(jv_copy(x), jv_copy(key));325      } else {326        if (first) {327          i = jv_object_iter(x);328        } else {329          i = jv_object_iter_next(x, i);330        }331        if (!jv_object_iter_valid(x, i)) break;332        key = jv_object_iter_key(x, i);333        value = jv_object_iter_value(x, i);334      }335336      if (!first) {337        if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);338        put_char(',', F, S, flags & JV_PRINT_ISATTY);339      }340      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);341      if (flags & JV_PRINT_PRETTY) {342        put_char('\n', F, S, flags & JV_PRINT_ISATTY);343        put_indent(indent + 1, flags, F, S, flags & JV_PRINT_ISATTY);344      }345346      first = 0;347      if (color) put_str(FIELD_COLOR, F, S, flags & JV_PRINT_ISATTY);348      jvp_dump_string(key, flags & JV_PRINT_ASCII, F, S, flags & JV_PRINT_ISATTY);349      jv_free(key);350      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);351352      if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);353      put_char(':', F, S, flags & JV_PRINT_ISATTY);354      if (color) put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);355      if (flags & JV_PRINT_PRETTY) {356        put_char(' ', F, S, flags & JV_PRINT_ISATTY);357      }358359      jv_dump_term(C, value, flags, indent + 1, F, S);360    }361    if (flags & JV_PRINT_PRETTY) {362      put_char('\n', F, S, flags & JV_PRINT_ISATTY);363      put_indent(indent, flags, F, S, flags & JV_PRINT_ISATTY);364    }365    if (color) put_str(color, F, S, flags & JV_PRINT_ISATTY);366    put_char('}', F, S, flags & JV_PRINT_ISATTY);367    if (flags & JV_PRINT_REFCOUNT)368      put_refcnt(C, refcnt, F, S, flags & JV_PRINT_ISATTY);369  }370  }371  jv_free(x);372  if (color) {373    put_str(COLRESET, F, S, flags & JV_PRINT_ISATTY);374  }375}376377void jv_dumpf(jv x, FILE *f, int flags) {378  jv_dump_term(tsd_dtoa_context_get(), x, flags, 0, f, 0);379}380381void jv_dump(jv x, int flags) {382  jv_dumpf(x, stdout, flags);383}384385/* This one is nice for use in debuggers */386void jv_show(jv x, int flags) {387  if (flags == -1)388    flags = JV_PRINT_PRETTY | JV_PRINT_COLOR | JV_PRINT_INDENT_FLAGS(2);389  jv_dumpf(jv_copy(x), stderr, flags | JV_PRINT_INVALID);390  fflush(stderr);391}392393jv jv_dump_string(jv x, int flags) {394  jv s = jv_string("");395  jv_dump_term(tsd_dtoa_context_get(), x, flags, 0, 0, &s);396  return s;397}398399char *jv_dump_string_trunc(jv x, char *outbuf, size_t bufsize) {400  assert(bufsize > 0);401  if (jv_get_kind(x) == JV_KIND_STRING &&402      (size_t)jv_string_length_bytes(jv_copy(x)) > bufsize) {403    x = jv_string_slice(x, 0, bufsize);404  }405  x = jv_dump_string(x, 0);406  const char *str = jv_string_value(x);407  const size_t len = strlen(str);408  if (len > bufsize - 1 && bufsize >= 8) {409    char delim = 0;410    switch (str[0]) {411    case '"': delim = '"'; break;412    case '[': delim = ']'; break;413    case '{': delim = '}'; break;414    }415    size_t l = bufsize - (delim ? 5 : 4);  // "...", delim (if any), '\0'416    const char *s = jvp_utf8_backtrack(str + l, str, NULL);417    if (s) l = s - str;418    memcpy(outbuf, str, l);419    outbuf[l++] = '.';420    outbuf[l++] = '.';421    outbuf[l++] = '.';422    if (delim) outbuf[l++] = delim;423    outbuf[l] = '\0';424  } else {425    size_t l = MIN(len, bufsize - 1);426    memcpy(outbuf, str, l);427    outbuf[l] = '\0';428  }429  jv_free(x);430  return outbuf;431}