From 549eb7f6f1595e2e8ea92eb354d0e0e1318bb73c Mon Sep 17 00:00:00 2001 From: gibkim <86421130+gibkim@users.noreply.github.com> Date: Sat, 5 Dec 2026 22:06:53 +0900 Subject: [PATCH] Write indentation in chunks when pretty-printing (#3701) Write the indentation from a static run of spaces or tabs, one chunk at a time, rather than one character at a time. This makes pretty-printing deeply nested input several times faster, especially with wider indentation such as `--indent 7`. Output is unchanged. --- src/jv_print.c | 16 ++++++++++++---- tests/shtest | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/jv_print.c b/src/jv_print.c index 568656dc..1c17e6d4 100644 --- a/src/jv_print.c +++ b/src/jv_print.c @@ -108,13 +108,21 @@ static void put_str(const char* s, FILE* fout, jv* strout, int T) { } static void put_indent(int n, int flags, FILE* fout, jv* strout, int T) { + static const char tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; + static const char spaces[] = " "; + const char *fill = spaces; + int fill_len = sizeof(spaces) - 1; if (flags & JV_PRINT_TAB) { - while (n--) - put_char('\t', fout, strout, T); + fill = tabs; + fill_len = sizeof(tabs) - 1; } else { n *= ((flags & (JV_PRINT_SPACE0 | JV_PRINT_SPACE1 | JV_PRINT_SPACE2)) >> 8); - while (n--) - put_char(' ', fout, strout, T); + } + // Write the indentation in chunks rather than one character at a time. + while (n > 0) { + int len = n < fill_len ? n : fill_len; + put_buf(fill, len, fout, strout, T); + n -= len; } } diff --git a/tests/shtest b/tests/shtest index 89984cfe..ceb1d965 100755 --- a/tests/shtest +++ b/tests/shtest @@ -1064,6 +1064,24 @@ printf '[\n {\n "a": 1\n }\n]\n' > $d/expected $JQ --indent 6 -n "[{a:1}]" > $d/out cmp $d/out $d/expected +# Indentation deeper than the chunks put_indent() writes at once +{ + for i in 0 1 2 3 4 5; do printf '%*s[\n' $((i * 7)) ''; done + printf '%*s1\n' 42 '' + for i in 5 4 3 2 1 0; do printf '%*s]\n' $((i * 7)) ''; done +} > $d/expected +$JQ --indent 7 -n "[[[[[[1]]]]]]" > $d/out +cmp $d/out $d/expected + +tabs() { i=0; while [ $i -lt $1 ]; do printf '\t'; i=$((i + 1)); done; } +{ + for n in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17; do tabs $n; printf '[\n'; done + tabs 18; printf '1\n' + for n in 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0; do tabs $n; printf ']\n'; done +} > $d/expected +$JQ --tab -n "[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]" > $d/out +cmp $d/out $d/expected + if ! $msys && ! $mingw; then # Test handling of timezones -- #2429, #2475 if ! r=$(TZ=Asia/Tokyo $JQ -rn '1731627341 | strflocaltime("%F %T %z %Z")') \