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.
This commit is contained in:
gibkim authored and GitHub committed 2026-12-05 22:06:53 +09:00
1 parent 50a35f7b41
commit 549eb7f6f1
2 files changed
+30 -4

No files matched your search

+12 -4
View File
@@ -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;
}
}
+18
View File
@@ -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")') \