Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,25 @@ public final class JavaOutput extends Output {
// never ends in whitespace: trailing tabs inside a comment were kept before, and only a second run removed them.
private StringBuilder spacesPending = new StringBuilder();

private static final int MAX_CACHED_SPACES = 100;
private static final String[] SPACES = new String[MAX_CACHED_SPACES + 1];

/** Returns an indentation string of the given number of spaces. */
static String spaces(int indent) {
if (indent <= 0) {
return "";
}
if (indent <= MAX_CACHED_SPACES) {
String result = SPACES[indent];
if (result == null) {
result = " ".repeat(indent);
SPACES[indent] = result;
}
return result;
}
return " ".repeat(indent);
}

/**
* {@code JavaOutput} constructor.
*
Expand Down Expand Up @@ -157,7 +176,7 @@ public void append(State state, String text, Range<Integer> range) {

@Override
public void indent(int indent) {
spacesPending.append(" ".repeat(indent));
spacesPending.append(spaces(indent));
}

/** Flush any incomplete last line, then add the EOF token into our data structures. */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* (c) Copyright 2026 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.javaformat.java;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

final class JavaOutputTest {

@Test
void cachesTheIndentationStrings() {
// Every output line used to get a fresh `" ".repeat(indent)`; the usual widths now come from a cache.
assertThat(JavaOutput.spaces(4)).isEqualTo(" ");
assertThat(JavaOutput.spaces(4)).isSameAs(JavaOutput.spaces(4));
assertThat(JavaOutput.spaces(100)).isSameAs(JavaOutput.spaces(100));
}

@Test
void returnsNoSpacesForZeroOrLess() {
assertThat(JavaOutput.spaces(0)).isEmpty();
assertThat(JavaOutput.spaces(-1)).isEmpty();
}

@Test
void buildsWidthsBeyondTheCache() {
assertThat(JavaOutput.spaces(104)).isEqualTo(" ".repeat(104));
}
}
Loading