com.google.common.collect.ImmutableList#builderWithExpectedSize ( )源码实例Demo

下面列出了com.google.common.collect.ImmutableList#builderWithExpectedSize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: besu   文件: LogOperation.java
@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()));
}
 
源代码2 项目: molgenis   文件: QueryUtils.java
/**
 * 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;
}
 
源代码3 项目: buck   文件: AbstractSkylarkFileParser.java
/** 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();
}
 
源代码4 项目: buck   文件: JsBundleDescription.java
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();
}
 
源代码5 项目: buck   文件: MultiArtifactCache.java
@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());
}
 
源代码6 项目: buck   文件: DefaultJavaLibraryBuildable.java
@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();
}
 
源代码7 项目: buck   文件: BuildFileManifestPojoizer.java
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;
}
 
源代码8 项目: curiostack   文件: ProtoTruthMessageDifferencer.java
/**
 * 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();
}
 
源代码9 项目: bgpcep   文件: NPathsRouteEntry.java
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();
}
 
源代码10 项目: yangtools   文件: AbstractLithiumDataInput.java
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));
    }
}
 
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();
}
 
源代码12 项目: azure-cosmosdb-java   文件: RntbdResponseHeaders.java
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();
    }
 
源代码13 项目: buck   文件: RunInfoLegacyTool.java
@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();
}
 
源代码14 项目: curiostack   文件: FieldScopeLogic.java
@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());
}
 
源代码15 项目: bazel   文件: NestedSet.java
/**
 * 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();
}
 
源代码16 项目: buck   文件: MainRunner.java
/**
 * 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();
}
 
源代码17 项目: armeria   文件: Routers.java
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();
}
 
源代码18 项目: buck   文件: PythonDslProjectBuildFileParser.java
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();
}
 
源代码19 项目: bazel   文件: PackageIdentifierBatchingCallback.java
@GuardedBy("this")
private void reset() {
  packageIdentifiers = ImmutableList.builderWithExpectedSize(batchSize);
  bufferedPackageIds = 0;
}
 
源代码20 项目: yangtools   文件: YangInstanceIdentifier.java
/**
 * 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());
}