Java Code Examples for com.google.common.collect.ImmutableList#builderWithExpectedSize()

The following examples show how to use com.google.common.collect.ImmutableList#builderWithExpectedSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProtoTruthMessageDifferencer.java    From curiostack with MIT License 6 votes vote down vote up
/**
 * Compares {@code actualList} and {@code expectedList}, two submessages corresponding to {@code
 * fieldDescriptor}. Uses {@code excludeNonRecursive}, {@code parentFieldPath}, and {@code
 * fieldScopeLogic} to compare the messages.
 *
 * @return A list in index order, containing the diff results for each message.
 */
private List<SingularField> compareRepeatedFieldByIndices(
    List<?> actualList,
    List<?> expectedList,
    boolean excludeNonRecursive,
    FieldDescriptor fieldDescriptor,
    FluentEqualityConfig config) {
  int maxSize = Math.max(actualList.size(), expectedList.size());
  ImmutableList.Builder<SingularField> builder = ImmutableList.builderWithExpectedSize(maxSize);
  for (int i = 0; i < maxSize; i++) {
    @NullableDecl Object actual = actualList.size() > i ? actualList.get(i) : null;
    @NullableDecl Object expected = expectedList.size() > i ? expectedList.get(i) : null;
    builder.add(
        compareSingularValue(
            actual,
            expected,
            /*defaultValue=*/ null,
            excludeNonRecursive,
            fieldDescriptor,
            indexedName(fieldDescriptor, i),
            config));
  }

  return builder.build();
}
 
Example 2
Source File: AbstractLithiumDataInput.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
    final QName qname = readQName();
    final int count = input.readInt();
    switch (count) {
        case 0:
            return NodeIdentifierWithPredicates.of(qname);
        case 1:
            return NodeIdentifierWithPredicates.of(qname, readQName(), readObject());
        default:
            // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
            final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
            final Object[] values = new Object[count];
            for (int i = 0; i < count; i++) {
                keys.add(readQName());
                values[i] = readObject();
            }

            return NodeIdentifierWithPredicates.of(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
                .instantiateWithValues(values));
    }
}
 
Example 3
Source File: NPathsRouteEntry.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private ImmutableList<AddPathBestPath> selectBest(final long localAs, final int size, final int limit) {
    // Scratch pool of offsets, we set them to true as we use them up.
    final boolean[] offsets = new boolean[size];
    final Builder<AddPathBestPath> builder = ImmutableList.builderWithExpectedSize(limit);

    // This ends up being (limit * size) traversals of offsets[], but that should be fine, as it is a dense array.
    // If this ever becomes a problem, we can optimize by having a AddPathSelector which remembers previous state,
    // so that we can rewind it. That will allow us to not only skip offset searches, but also recomputing the
    // (relatively) costly per-path state from scratch.
    for (int search = 0; search < limit; ++search) {
        final AddPathSelector selector = new AddPathSelector(localAs);
        for (int offset = 0; offset < size; ++offset) {
            if (!offsets[offset]) {
                processOffset(selector, offset);
            }
        }
        final AddPathBestPath result = selector.result();
        LOG.trace("Path {} selected {}", search, result);
        builder.add(result);

        offsets[result.getOffset()] = true;
    }

    return builder.build();
}
 
Example 4
Source File: LogOperation.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(final MessageFrame frame) {
  final Address address = frame.getRecipientAddress();

  final UInt256 dataLocation = UInt256.fromBytes(frame.popStackItem());
  final UInt256 numBytes = UInt256.fromBytes(frame.popStackItem());
  final Bytes data = frame.readMemory(dataLocation, numBytes);

  final ImmutableList.Builder<LogTopic> builder =
      ImmutableList.builderWithExpectedSize(numTopics);
  for (int i = 0; i < numTopics; i++) {
    builder.add(LogTopic.create(frame.popStackItem()));
  }

  frame.addLog(new Log(address, data, builder.build()));
}
 
Example 5
Source File: BuildFileManifestPojoizer.java    From buck with Apache License 2.0 6 votes vote down vote up
private ImmutableList<Object> convertIterableToPojo(Object object) {
  @SuppressWarnings("unchecked")
  Iterable<Object> iterable = (Iterable<Object>) object;

  ImmutableList.Builder<Object> builder =
      iterable instanceof Collection
          ? ImmutableList.builderWithExpectedSize(((Collection<Object>) iterable).size())
          : ImmutableList.builder();

  boolean needConversion = !(iterable instanceof ImmutableList);
  for (Object obj : iterable) {
    Object convertedObj = convertToPojo(obj);

    if (!needConversion && convertedObj != obj) {
      needConversion = true;
    }

    builder.add(convertedObj);
  }

  return needConversion ? builder.build() : (ImmutableList<Object>) iterable;
}
 
Example 6
Source File: DefaultJavaLibraryBuildable.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableList<Step> getPipelinedBuildSteps(
    BuildContext buildContext,
    ProjectFilesystem filesystem,
    JavacPipelineState state,
    OutputPathResolver outputPathResolver,
    BuildCellRelativePathFactory buildCellPathFactory) {
  // TODO(cjhopman): unusedDependenciesFinder is broken.
  ImmutableList<Step> factoryBuildSteps =
      jarBuildStepsFactory.getPipelinedBuildStepsForLibraryJar(
          buildContext,
          filesystem,
          ModernBuildableSupport.getDerivedArtifactVerifier(buildTarget, filesystem, this),
          state,
          outputPathResolver.resolvePath(pathToClassHashesOutputPath));
  ImmutableList.Builder<Step> stepsBuilder =
      ImmutableList.builderWithExpectedSize(factoryBuildSteps.size() + 1);
  stepsBuilder.addAll(factoryBuildSteps);
  addMakeMissingOutputsStep(filesystem, outputPathResolver, stepsBuilder);
  return stepsBuilder.build();
}
 
Example 7
Source File: MultiArtifactCache.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Unit> store(ImmutableList<Pair<ArtifactInfo, BorrowablePath>> artifacts) {
  if (writableArtifactCaches.size() != 1) {
    ImmutableList.Builder<Pair<ArtifactInfo, BorrowablePath>> artifactTemporaryPaths =
        ImmutableList.builderWithExpectedSize(artifacts.size());
    for (int i = 0; i < artifacts.size(); i++) {
      artifactTemporaryPaths.add(
          new Pair<>(
              artifacts.get(i).getFirst(),
              BorrowablePath.notBorrowablePath(artifacts.get(i).getSecond().getPath())));
    }
    artifacts = artifactTemporaryPaths.build();
  }

  List<ListenableFuture<Unit>> storeFutures =
      Lists.newArrayListWithExpectedSize(writableArtifactCaches.size());
  for (ArtifactCache artifactCache : writableArtifactCaches) {
    storeFutures.add(artifactCache.store(artifacts));
  }

  // Aggregate future to ensure all store operations have completed.
  return Futures.transform(
      Futures.allAsList(storeFutures), Functions.constant(null), MoreExecutors.directExecutor());
}
 
Example 8
Source File: JsBundleDescription.java    From buck with Apache License 2.0 6 votes vote down vote up
private Iterable<BuildTarget> getLibraryDependencies(JsLibrary library) {
  ImmutableSortedSet<SourcePath> libraryDependencies = library.getLibraryDependencies();
  ImmutableList.Builder<BuildTarget> libraryTargets =
      ImmutableList.builderWithExpectedSize(libraryDependencies.size());
  for (SourcePath sourcePath : libraryDependencies) {
    Optional<BuildRule> rule = graphBuilder.getRule(sourcePath);
    if (rule.isPresent()) {
      libraryTargets.add(rule.get().getBuildTarget());
    } else {
      throw new HumanReadableException(
          "js_library %s has '%s' as a lib, but js_library can only have other "
              + "js_library targets as lib",
          library.getBuildTarget(), sourcePath);
    }
  }
  return libraryTargets.build();
}
 
Example 9
Source File: AbstractSkylarkFileParser.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Loads all extensions identified by corresponding {@link SkylarkImport}s. */
protected ImmutableList<ExtensionData> loadExtensions(
    Label containingLabel, ImmutableList<SkylarkImport> skylarkImports)
    throws BuildFileParseException, IOException, InterruptedException {
  Set<SkylarkImport> processed = new HashSet<>(skylarkImports.size());
  ImmutableList.Builder<ExtensionData> extensions =
      ImmutableList.builderWithExpectedSize(skylarkImports.size());
  // foreach is not used to avoid iterator overhead
  for (int i = 0; i < skylarkImports.size(); ++i) {
    SkylarkImport skylarkImport = skylarkImports.get(i);
    // sometimes users include the same extension multiple times...
    if (!processed.add(skylarkImport)) continue;
    try {
      extensions.add(loadExtension(ImmutableLoadImport.of(containingLabel, skylarkImport)));
    } catch (UncheckedExecutionException e) {
      propagateRootCause(e);
    }
  }
  return extensions.build();
}
 
Example 10
Source File: QueryUtils.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Same as {@link #getAttributePath(String, EntityType)} but adds an id attribute to the path is
 * the last element is a reference attribute.
 *
 * @param queryRuleField query rule field name, e.g. grandparent.parent.child
 * @param entityType entity type
 * @param expandLabelInsteadOfId expand with label attribute instead of id attribute
 * @return attribute path
 * @throws UnknownAttributeException if no attribute exists for a query rule field name part
 * @throws MolgenisQueryException if query rule field is an invalid attribute path
 */
public static List<Attribute> getAttributePathExpanded(
    String queryRuleField, EntityType entityType, boolean expandLabelInsteadOfId) {
  List<Attribute> attributePath = getAttributePath(queryRuleField, entityType);

  List<Attribute> expandedAttributePath;
  Attribute attribute = attributePath.get(attributePath.size() - 1);
  if (attribute.hasRefEntity()) {
    Attribute expandedAttribute;
    if (expandLabelInsteadOfId) {
      expandedAttribute = attribute.getRefEntity().getLabelAttribute();
    } else {
      expandedAttribute = attribute.getRefEntity().getIdAttribute();
    }

    @SuppressWarnings("UnstableApiUsage")
    Builder<Attribute> builder = ImmutableList.builderWithExpectedSize(attributePath.size() + 1);
    builder.addAll(attributePath);
    builder.add(expandedAttribute);

    expandedAttributePath = builder.build();
  } else {
    expandedAttributePath = attributePath;
  }
  return expandedAttributePath;
}
 
Example 11
Source File: RunInfoLegacyTool.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableList<String> getCommandPrefix(SourcePathResolverAdapter resolver) {
  RunInfo runInfo = getRunInfo();
  ImmutableList.Builder<String> command =
      ImmutableList.builderWithExpectedSize(runInfo.args().getEstimatedArgsCount());
  runInfo
      .args()
      .getArgsAndFormatStrings()
      .map(
          argAndFormat ->
              ArgFactory.from(
                  argAndFormat.getObject(), argAndFormat.getPostStringificationFormatString()))
      .forEach(arg -> arg.appendToCommandLine(command::add, resolver));
  return command.build();
}
 
Example 12
Source File: RntbdResponseHeaders.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
List<Map.Entry<String, String>> asList(final RntbdContext context, final UUID activityId) {

        final ImmutableList.Builder<Map.Entry<String, String>> builder = ImmutableList.builderWithExpectedSize(this.computeCount() + 2);
        builder.add(new Entry(HttpHeaders.SERVER_VERSION, context.serverVersion()));
        builder.add(new Entry(HttpHeaders.ACTIVITY_ID, activityId.toString()));

        this.collectEntries((token, toEntry) -> {
            if (token.isPresent()) {
                builder.add(toEntry.apply(token));
            }
        });

        return builder.build();
    }
 
Example 13
Source File: FieldScopeLogic.java    From curiostack with MIT License 5 votes vote down vote up
@Override
final FieldScopeLogic subScopeImpl(
    Descriptor rootDescriptor, FieldDescriptorOrUnknown fieldDescriptorOrUnknown) {
  ImmutableList.Builder<FieldScopeLogic> builder =
      ImmutableList.builderWithExpectedSize(elements.size());
  for (FieldScopeLogic elem : elements) {
    builder.add(elem.subScope(rootDescriptor, fieldDescriptorOrUnknown));
  }
  return newLogicOfSameType(builder.build());
}
 
Example 14
Source File: NestedSet.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of {@link #toList}. Uses one of three strategies based on the value of {@code
 * this.memo}: wrap our direct items in a list, call {@link #lockedExpand} to perform the initial
 * {@link #walk}, or call {@link #replay} if we have a nontrivial memo.
 */
private ImmutableList<E> expand(Object[] children) {
  // This value is only set in the constructor, so safe to test here with no lock.
  if (memo == NO_MEMO) {
    return ImmutableList.copyOf(new ArraySharingCollection<>(children));
  }
  CompactHashSet<E> members = lockedExpand(children);
  if (members != null) {
    return ImmutableList.copyOf(members);
  }
  ImmutableList.Builder<E> output =
      ImmutableList.builderWithExpectedSize(memoizedFlattenAndGetSize());
  replay(output, children, memo, 0);
  return output.build();
}
 
Example 15
Source File: MainRunner.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Filters out command line arguments that are provided by the python wrapper.
 *
 * <p>These arguments are generally not useful to users, and we do not want them showing up in
 * logging, as they are not provided by users and their values are not really actionable.
 */
private ImmutableList<String> filterArgsForLogging(ImmutableList<String> args) {
  ImmutableList.Builder<String> builder = ImmutableList.builderWithExpectedSize(args.size());
  for (int i = 0; i < args.size(); i++) {
    String arg = args.get(i);
    if (arg.equals(GlobalCliOptions.COMMAND_ARGS_FILE_LONG_ARG)) {
      // Skip --command-args-file and its argument. These are added by the python wrapper
      // and aren't useful to users.
      i++;
      continue;
    }
    builder.add(arg);
  }
  return builder.build();
}
 
Example 16
Source File: Routers.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static <V> List<Routed<V>> findAll(RoutingContext routingCtx, List<V> values,
                                           Function<V, Route> routeResolver) {
    final ImmutableList.Builder<Routed<V>> builder = ImmutableList.builderWithExpectedSize(values.size());

    for (V value : values) {
        final Route route = routeResolver.apply(value);
        final RoutingResult routingResult = route.apply(routingCtx);
        if (routingResult.isPresent()) {
            builder.add(Routed.of(route, routingResult, value));
        }
    }
    return builder.build();
}
 
Example 17
Source File: PythonDslProjectBuildFileParser.java    From buck with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<Object> convertToSelectableAttributesIfNeeded(
    List<Object> attributes) {
  ImmutableList.Builder<Object> convertedAttributes =
      ImmutableList.builderWithExpectedSize(attributes.size());
  for (Object attribute : attributes) {
    convertedAttributes.add(
        PythonDslProjectBuildFileParser.convertToSelectableAttributeIfNeeded(attribute));
  }
  return convertedAttributes.build();
}
 
Example 18
Source File: ClientContextImpl.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
private <T extends Interceptor> @NotNull ImmutableList<T> addInterceptor(
        final @NotNull ImmutableList<T> interceptors, final @NotNull T interceptor) {

    if (interceptors.isEmpty()) {
        return ImmutableList.of(interceptor);
    }
    final int priority = getExtensionPriority(interceptor);
    int low = 0;
    int high = interceptors.size() - 1;
    while (low <= high) {
        final int mid = low + high >>> 1;
        final T midInterceptor = interceptors.get(mid);
        final int midPriority = getExtensionPriority(midInterceptor);

        if (midPriority >= priority) {
            if (midPriority == priority && midInterceptor == interceptor) {
                return interceptors;
            }
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    final ImmutableList.Builder<T> builder = ImmutableList.builderWithExpectedSize(interceptors.size() + 1);
    for (int i = 0; i < low; i++) {
        builder.add(interceptors.get(i));
    }
    builder.add(interceptor);
    for (int i = low; i < interceptors.size(); i++) {
        builder.add(interceptors.get(i));
    }
    return builder.build();
}
 
Example 19
Source File: PackageIdentifierBatchingCallback.java    From bazel with Apache License 2.0 4 votes vote down vote up
@GuardedBy("this")
private void reset() {
  packageIdentifiers = ImmutableList.builderWithExpectedSize(batchSize);
  bufferedPackageIds = 0;
}
 
Example 20
Source File: YangInstanceIdentifier.java    From yangtools with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
 *
 * @param pathTowardsRoot Path towards root
 * @return A {@link YangInstanceIdentifier} instance
 * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
 */
public static @NonNull YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
    final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
        pathTowardsRoot.size());
    pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
    return YangInstanceIdentifier.create(builder.build());
}