Skip to content

Commit

Permalink
Use an ImmutableList.Builder in StarlarkCustomCommandLine to avoid cr…
Browse files Browse the repository at this point in the history
…eating unnecessary garbage.

PiperOrigin-RevId: 505660708
Change-Id: I49708dfa601843b810f24076122ff5763e66f614
  • Loading branch information
tjgq authored and copybara-github committed Jan 30, 2023
1 parent 030de8a commit 18cc57c
Showing 1 changed file with 30 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ static VectorArg create(int features) {
}

private static void push(
List<Object> arguments, Builder arg, StarlarkSemantics starlarkSemantics) {
ImmutableListBuilderWithSize<Object> arguments,
Builder arg,
StarlarkSemantics starlarkSemantics) {
int features = 0;
features |= arg.mapEach != null ? HAS_MAP_EACH : 0;
features |= arg.nestedSet != null ? IS_NESTED_SET : 0;
Expand Down Expand Up @@ -590,7 +592,7 @@ static ScalarArg create(boolean hasFormat) {
return interner.intern(new ScalarArg(hasFormat));
}

private static void push(List<Object> arguments, Builder arg) {
private static void push(ImmutableListBuilderWithSize<Object> arguments, Builder arg) {
ScalarArg scalarArg = ScalarArg.create(arg.format != null);
arguments.add(scalarArg);
arguments.add(arg.object);
Expand Down Expand Up @@ -656,11 +658,33 @@ public int hashCode() {
}
}

/** A variant of {@link ImmutableList.Builder} that keeps track of the current size. */
private static class ImmutableListBuilderWithSize<T> {
final ImmutableList.Builder<T> builder = ImmutableList.builder();
int size = 0;

@CanIgnoreReturnValue
ImmutableListBuilderWithSize<T> add(T element) {
builder.add(element);
size++;
return this;
}

ImmutableList<T> build() {
return builder.build();
}

int size() {
return size;
}
}

static class Builder {
private final StarlarkSemantics starlarkSemantics;
private final List<Object> arguments = new ArrayList<>();
private final ImmutableListBuilderWithSize<Object> arguments =
new ImmutableListBuilderWithSize<>();
// Indexes in arguments list where individual args begin
private final List<Integer> argStartIndexes = new ArrayList<>();
private final ImmutableList.Builder<Integer> argStartIndexes = ImmutableList.builder();

public Builder(StarlarkSemantics starlarkSemantics) {
this.starlarkSemantics = starlarkSemantics;
Expand Down Expand Up @@ -692,10 +716,9 @@ Builder add(ScalarArg.Builder scalarArg) {

StarlarkCustomCommandLine build(boolean flagPerLine) {
if (flagPerLine) {
return new StarlarkCustomCommandLineWithIndexes(
ImmutableList.copyOf(arguments), ImmutableList.copyOf(argStartIndexes));
return new StarlarkCustomCommandLineWithIndexes(arguments.build(), argStartIndexes.build());
} else {
return new StarlarkCustomCommandLine(ImmutableList.copyOf(arguments));
return new StarlarkCustomCommandLine(arguments.build());
}
}
}
Expand Down

0 comments on commit 18cc57c

Please sign in to comment.