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

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

源代码1 项目: armeria   文件: Cookie.java
/**
 * Decodes the specified {@code "Set-Cookie"} header values into {@link Cookie}s.
 *
 * @param strict whether to validate the cookie names and values are in the valid scope defined in RFC 6265.
 * @param setCookieHeaders the {@code "Set-Cookie"} header values.
 * @return the decoded {@link Cookie}s.
 */
static Cookies fromSetCookieHeaders(boolean strict, String... setCookieHeaders) {
    requireNonNull(setCookieHeaders, "setCookieHeaders");
    if (setCookieHeaders.length == 0) {
        return Cookies.empty();
    }

    final ImmutableSet.Builder<Cookie> builder =
            ImmutableSet.builderWithExpectedSize(setCookieHeaders.length);
    for (String v : setCookieHeaders) {
        requireNonNull(v, "setCookieHeaders contains null.");
        final Cookie cookie = fromSetCookieHeader(strict, v);
        if (cookie != null) {
            builder.add(cookie);
        }
    }

    return Cookies.of(builder.build());
}
 
源代码2 项目: buck   文件: DefaultGraphTransformationEngine.java
private <UResultType extends ComputeResult, UKeyType extends ComputeKey<UResultType>>
    ImmutableSet<TaskType> computeDepsForKey(
        GraphComputationStage<UKeyType, UResultType> stage,
        UKeyType key,
        ImmutableMap.Builder<ComputeKey<?>, Future<ComputeResult>> depResults)
        throws Exception {

  ImmutableSet<? extends ComputeKey<?>> depKeys =
      stage
          .getTransformer()
          .discoverDeps(
              key, new DefaultComputationEnvironment(collectDeps(depResults.build())));

  // task that executes secondary deps, depending on the initial deps
  ImmutableSet.Builder<TaskType> depWorkBuilder =
      ImmutableSet.builderWithExpectedSize(depKeys.size());
  for (ComputeKey<?> depKey : depKeys) {
    TaskType task = convertKeyToTask(depKey);
    depResults.put(depKey, task.getResultFuture());
    depWorkBuilder.add(task);
  }
  return depWorkBuilder.build();
}
 
源代码3 项目: buck   文件: BuildFileManifestPojoizer.java
private ImmutableSet<Object> convertSetToPojo(Object object) {
  @SuppressWarnings("unchecked")
  Set<Object> set = (Set<Object>) object;

  boolean needConversion;
  ImmutableSet.Builder<Object> builder;
  if (set instanceof SortedSet) {
    needConversion = !(set instanceof ImmutableSortedSet);
    builder = new ImmutableSortedSet.Builder<>(((SortedSet<Object>) set).comparator());
  } else {
    needConversion = !(set instanceof ImmutableSet);
    builder = ImmutableSet.builderWithExpectedSize(set.size());
  }

  for (Object obj : set) {
    Object convertedObj = convertToPojo(obj);

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

    builder.add(convertedObj);
  }

  return needConversion ? builder.build() : (ImmutableSet<Object>) set;
}
 
@Override
public ImmutableSet<? extends ComputeKey<? extends ComputeResult>> discoverDeps(
    BuildPackagePathToUnconfiguredTargetNodePackageKey key, ComputationEnvironment env) {

  BuildFileManifest buildFileManifest =
      env.getDep(BuildPackagePathToBuildFileManifestKey.of(key.getPath()));
  ForwardRelativePath basePath = ForwardRelativePath.ofPath(key.getPath());

  ImmutableSet.Builder<BuildTargetToUnconfiguredTargetNodeKey> builder =
      ImmutableSet.builderWithExpectedSize(buildFileManifest.getTargets().size());

  for (String target : buildFileManifest.getTargets().keySet()) {
    BuildTargetToUnconfiguredTargetNodeKey depkey =
        ImmutableBuildTargetToUnconfiguredTargetNodeKey.of(
            UnconfiguredBuildTarget.of(
                cell.getCanonicalName(), BaseName.ofPath(basePath), target, FlavorSet.NO_FLAVORS),
            key.getPath());
    builder.add(depkey);
  }
  return builder.build();
}
 
源代码5 项目: buck   文件: OwnersReport.java
private ImmutableSet<RelPath> getAllBasePathsForPath(
    BuildFileTree buildFileTree, RelPath cellRelativePath) {
  if (rootCell
          .getBuckConfigView(ParserConfig.class)
          .getPackageBoundaryEnforcementPolicy(cellRelativePath.getPath())
      == ParserConfig.PackageBoundaryEnforcement.ENFORCE) {
    return buildFileTree
        .getBasePathOfAncestorTarget(cellRelativePath)
        .map(ImmutableSet::of)
        .orElse(ImmutableSet.of());
  }
  ImmutableSet.Builder<RelPath> resultBuilder =
      ImmutableSet.builderWithExpectedSize(cellRelativePath.getPath().getNameCount());
  for (int i = 1; i < cellRelativePath.getPath().getNameCount(); i++) {
    buildFileTree
        .getBasePathOfAncestorTarget(cellRelativePath.subpath(0, i))
        .ifPresent(resultBuilder::add);
  }
  return resultBuilder.build();
}
 
源代码6 项目: bgpcep   文件: AbstractOffsetMap.java
public final T with(final K key) {
    // TODO: we could make this faster if we had an array-backed Set and requiring
    //       the caller to give us the result of offsetOf() -- as that indicates
    //       where to insert the new routerId while maintaining the sorted nature
    //       of the array
    final Builder<K> builder = ImmutableSet.builderWithExpectedSize(size() + 1);
    builder.add(keys);
    builder.add(key);
    return instanceForKeys(builder.build());
}
 
源代码7 项目: buck   文件: RuleAnalysisLegacyBuildRuleView.java
private ImmutableSet<OutputLabel> getOutputLabelsSupplier() {
  DefaultInfo defaultInfo = providerInfoCollection.getDefaultInfo();
  ImmutableSet.Builder<OutputLabel> builder =
      ImmutableSet.builderWithExpectedSize(defaultInfo.namedOutputs().size() + 1);
  defaultInfo
      .namedOutputs()
      .keySet()
      .forEach(outputLabel -> builder.add(OutputLabel.of(outputLabel)));
  builder.add(OutputLabel.defaultLabel());
  return builder.build();
}
 
源代码8 项目: bazel   文件: LegacyIncludeScanner.java
private ImmutableSet<Artifact> prepare(SkyFunction.Environment env) throws InterruptedException {
  if (parser.getHints() != null) {
    Collection<Artifact> artifacts =
        parser.getHints().getPathLevelHintedInclusions(quoteIncludePaths, env);
    if (env.valuesMissing()) {
      throw new MissingDepException();
    }
    ImmutableSet.Builder<Artifact> pathHints;
    pathHints = ImmutableSet.builderWithExpectedSize(quoteIncludePaths.size());
    pathHints.addAll(Preconditions.checkNotNull(artifacts, quoteIncludePaths));
    return pathHints.build();
  }
  return ImmutableSet.of();
}
 
源代码9 项目: bazel   文件: ImmutableSetRuntimeCodec.java
@SuppressWarnings("unchecked") // Adding object to untyped builder.
@Override
public ImmutableSet deserialize(DeserializationContext context, CodedInputStream codedIn)
    throws SerializationException, IOException {
  int size = codedIn.readInt32();
  ImmutableSet.Builder builder = ImmutableSet.builderWithExpectedSize(size);
  for (int i = 0; i < size; i++) {
    // Don't inline so builder knows this is an object, not an array.
    Object item = context.deserialize(codedIn);
    builder.add(item);
  }
  return builder.build();
}
 
源代码10 项目: buck   文件: LeftComposingComputation.java
@Override
@SuppressWarnings("unchecked")
public ImmutableSet<? extends ComputeKey<? extends ComputeResult>> discoverDeps(
    ComposedKey<BaseKey, Result2> key, ComputationEnvironment env) throws Exception {
  ComposedResult<ComputeKey<Result1>, Result1> results =
      env.getDep(ComposedKey.of(key.getOriginKey(), baseIdentifier.getTargetResultClass()));

  ImmutableSet.Builder<ComputeKey<?>> depBuilder =
      ImmutableSet.builderWithExpectedSize(results.resultMap().size());
  for (Entry<ComputeKey<Result1>, Result1> result : results.resultMap().entrySet()) {
    depBuilder.addAll(composer.transitionWith((Key1) result.getKey(), result.getValue()));
  }
  return depBuilder.build();
}
 
源代码11 项目: bazel   文件: BuildConfigurationFunction.java
private Set<Fragment> getConfigurationFragments(BuildConfigurationValue.Key key)
    throws InvalidConfigurationException {
  BuildOptions options = defaultBuildOptions.applyDiff(key.getOptionsDiff());
  ImmutableSortedSet<Class<? extends Fragment>> fragmentClasses = key.getFragments();
  ImmutableSet.Builder<Fragment> fragments =
      ImmutableSet.builderWithExpectedSize(fragmentClasses.size());
  for (Class<? extends Fragment> fragmentClass : fragmentClasses) {
    BuildOptions trimmedOptions =
        options.trim(
            BuildConfiguration.getOptionsClasses(
                ImmutableList.of(fragmentClass), ruleClassProvider));
    Fragment fragment;
    FragmentKey fragmentKey = FragmentKey.create(trimmedOptions, fragmentClass);
    try {
      fragment = fragmentCache.get(fragmentKey);
    } catch (ExecutionException e) {
      Throwables.propagateIfPossible(e.getCause(), InvalidConfigurationException.class);
      throw new IllegalStateException(e);
    }
    if (fragment != NULL_MARKER) {
      fragments.add(fragment);
    } else {
      // NULL_MARKER is never GC'ed, so this entry will stay in cache forever unless we delete it
      // ourselves. Since it's a cheap computation we don't care about recomputing it.
      fragmentCache.invalidate(fragmentKey);
    }
  }
  return fragments.build();
}
 
源代码12 项目: bazel   文件: GroupedList.java
@SuppressWarnings("unchecked")
public Set<T> toSet() {
  ImmutableSet.Builder<T> builder = ImmutableSet.builderWithExpectedSize(numElements());
  for (Object obj : elements) {
    if (obj instanceof List) {
      builder.addAll((List<T>) obj);
    } else {
      builder.add((T) obj);
    }
  }
  return builder.build();
}
 
源代码13 项目: buck   文件: CxxConstructorArg.java
/** Checks that there are no files that appear both in srcs and platform_srcs */
default void checkDuplicateSources(SourcePathResolverAdapter sourcePathResolverAdapter) {
  ImmutableSet.Builder<SourcePath> platformSrcsBuilder =
      ImmutableSet.builderWithExpectedSize(
          getPlatformSrcs().getValues().stream().mapToInt(Set::size).sum());

  getPlatformSrcs().getValues().stream()
      .flatMap(Collection::stream)
      .map(SourceWithFlags::getSourcePath)
      .forEach(platformSrcsBuilder::add);

  ImmutableSet.Builder<SourcePath> srcsBuilder =
      ImmutableSet.builderWithExpectedSize(getSrcs().size());

  getSrcs().stream().map(SourceWithFlags::getSourcePath).forEach(srcsBuilder::add);

  Set<SourcePath> intersect = Sets.intersection(platformSrcsBuilder.build(), srcsBuilder.build());

  if (!intersect.isEmpty()) {
    throw new HumanReadableException(
        String.format(
                "Files may be listed in srcs or platform_srcs, but not both. The following %s both in srcs and platform_srcs: \n\n\t%s\n",
                intersect.size() > 1 ? "files are listed" : "file is listed",
                intersect.stream()
                    .map(sourcePathResolverAdapter::getRelativePath)
                    .map(Object::toString)
                    .collect(Collectors.joining("\n\t")))
            .replace("\n", System.lineSeparator()));
  }
}
 
源代码14 项目: buck   文件: VisibilityPatterns.java
@SuppressWarnings("unchecked")
public static ImmutableSet<VisibilityPattern> createFromStringList(
    CellPathResolver cellNames,
    String paramName,
    @Nullable Object value,
    Path definingPath,
    Supplier<String> visibilityDefinerDescription) {
  if (value == null) {
    return ImmutableSet.of();
  }
  if (!(value instanceof List)) {
    throw new RuntimeException(
        String.format("Expected an array for %s but was %s", paramName, value));
  }
  List<String> originalPatterns = (List<String>) value;
  ImmutableSet.Builder<VisibilityPattern> patterns =
      ImmutableSet.builderWithExpectedSize(originalPatterns.size());
  for (String visibility : originalPatterns) {
    try {
      patterns.add(VisibilityPatternParser.parse(cellNames, definingPath, visibility));
    } catch (IllegalArgumentException e) {
      throw new HumanReadableException(
          e,
          "Bad visibility expression: %s listed %s in its %s argument, but only %s "
              + "or fully qualified target patterns are allowed (i.e. those starting with "
              + "// or a cell).",
          visibilityDefinerDescription.get(),
          visibility,
          paramName,
          VisibilityPatternParser.VISIBILITY_PUBLIC);
    }
  }
  return patterns.build();
}
 
源代码15 项目: buck   文件: BuildReport.java
/**
 * Returns a set of paths representing all outputs generated by the given {@code rule}, or null if
 * no outputs are available.
 *
 * <p>For rules that do not provide multiple outputs, the return value is null or a set of one
 * output. For rules with multiple outputs, the rule will provide at least the default output
 * group, so the return value is a set of zero or more outputs. Note that zero outputs in an
 * output group is valid.
 */
@Nullable
private ImmutableMap<OutputLabel, ImmutableSet<Path>> getMultipleOutputPaths(BuildRule rule) {
  if (rule instanceof HasMultipleOutputs) {
    HasMultipleOutputs multipleOutputsRule = (HasMultipleOutputs) rule;
    ProjectFilesystem projectFilesystem = rule.getProjectFilesystem();
    ImmutableSet<OutputLabel> outputLabels = multipleOutputsRule.getOutputLabels();
    ImmutableMap.Builder<OutputLabel, ImmutableSet<Path>> allPathsBuilder =
        ImmutableMap.builderWithExpectedSize(outputLabels.size());
    for (OutputLabel outputLabel : outputLabels) {
      ImmutableSortedSet<SourcePath> sourcePaths =
          multipleOutputsRule.getSourcePathToOutput(outputLabel);
      ImmutableSet.Builder<Path> pathBuilderForLabel =
          ImmutableSet.builderWithExpectedSize(sourcePaths.size());
      for (SourcePath sourcePath : sourcePaths) {
        pathBuilderForLabel.add(
            relativizeSourcePathToProjectRoot(projectFilesystem, sourcePath).getPath());
      }
      allPathsBuilder.put(outputLabel, pathBuilderForLabel.build());
    }
    return allPathsBuilder.build();
  }
  Path output = getRuleOutputPath(rule);
  if (output == null) {
    return null;
  }
  return ImmutableMap.of(OutputLabel.defaultLabel(), ImmutableSet.of(output));
}
 
源代码16 项目: buck   文件: DefaultDependencyFileRuleKeyFactory.java
/**
 * To optimize the common case where a path isn't part of the depfile, we create a set of
 * possible Paths that may be the pathToFile for a DependencyFileEntry.
 */
private ImmutableSet<Path> getDepfilePossiblePaths(
    ImmutableList<DependencyFileEntry> depFileEntries) {
  ImmutableSet.Builder<Path> builder =
      ImmutableSet.builderWithExpectedSize(depFileEntries.size());
  for (DependencyFileEntry entry : depFileEntries) {
    builder.add(entry.pathToFile());
  }
  return builder.build();
}
 
源代码17 项目: buck   文件: AbstractCommand.java
/**
 * Returns a set of {@link BuildTargetWithOutputs} instances by matching the given {@link
 * BuildTarget} instances with the given {@link TargetNodeSpec} instances, and applying any {@link
 * OutputLabel} instances to the matching {@link BuildTarget} instances. Applies the default label
 * if a given build target cannot find a matching spec.
 */
protected ImmutableSet<BuildTargetWithOutputs> matchBuildTargetsWithLabelsFromSpecs(
    ImmutableList<TargetNodeSpec> specs, Set<BuildTarget> buildTargets) {
  HashMultimap<UnconfiguredBuildTarget, OutputLabel> buildTargetViewToOutputLabel =
      HashMultimap.create(specs.size(), 1);

  specs.stream()
      .filter(BuildTargetSpec.class::isInstance)
      .map(BuildTargetSpec.class::cast)
      .forEach(
          buildTargetSpec -> {
            buildTargetViewToOutputLabel.put(
                buildTargetSpec.getUnconfiguredBuildTarget(),
                buildTargetSpec.getUnconfiguredBuildTargetViewWithOutputs().getOutputLabel());
          });

  ImmutableSet.Builder<BuildTargetWithOutputs> builder =
      ImmutableSet.builderWithExpectedSize(buildTargets.size());
  for (BuildTarget target : buildTargets) {
    boolean mappedTarget = false;

    UnconfiguredBuildTarget targetView = target.getUnconfiguredBuildTarget();
    // HashMultimap creates an empty collection on 'get()' if key is missing, rather than
    // returning null
    if (buildTargetViewToOutputLabel.containsKey(targetView)) {
      buildTargetViewToOutputLabel
          .get(targetView)
          .forEach(outputLabel -> builder.add(BuildTargetWithOutputs.of(target, outputLabel)));
      mappedTarget = true;
    }

    // A target may not map to an output label if the build command wasn't invoked with a build
    // pattern that specifies a specific target
    if (!mappedTarget) {
      builder.add(BuildTargetWithOutputs.of(target, OutputLabel.defaultLabel()));
    }
  }
  return builder.build();
}
 
源代码18 项目: buck   文件: BuildCommand.java
@Value.Lazy
default ImmutableSet<BuildTarget> getBuildTargets() {
  ImmutableSet.Builder<BuildTarget> builder =
      ImmutableSet.builderWithExpectedSize(getBuildTargetWithOutputs().size());
  getBuildTargetWithOutputs()
      .forEach(targetWithOutputs -> builder.add(targetWithOutputs.getBuildTarget()));
  return builder.build();
}
 
源代码19 项目: buck   文件: BuckQueryEnvironment.java
public ImmutableSet<TargetNode<?>> getNodesFromQueryTargets(Collection<QueryBuildTarget> input)
    throws QueryException {
  ImmutableSet.Builder<TargetNode<?>> builder =
      ImmutableSet.builderWithExpectedSize(input.size());
  for (QueryBuildTarget target : input) {
    builder.add(getNode(target));
  }
  return builder.build();
}
 
源代码20 项目: buck   文件: BuckQueryEnvironment.java
@Override
public ImmutableSet<QueryFileTarget> getBuildFiles(Set<QueryBuildTarget> targets) {
  ProjectFilesystem cellFilesystem = rootCell.getFilesystem();
  AbsPath rootPath = cellFilesystem.getRootPath();

  ImmutableSet.Builder<QueryFileTarget> builder =
      ImmutableSet.builderWithExpectedSize(targets.size());
  for (QueryBuildTarget target : targets) {
    BuildTarget buildTarget = target.getBuildTarget();
    Cell cell = rootCell.getCell(buildTarget.getCell());
    BuildFileTree buildFileTree = Objects.requireNonNull(buildFileTrees.get(cell));
    Optional<RelPath> path =
        buildFileTree.getBasePathOfAncestorTarget(
            buildTarget
                .getCellRelativeBasePath()
                .getPath()
                .toRelPath(cellFilesystem.getFileSystem()));
    Preconditions.checkState(path.isPresent());

    RelPath buildFilePath =
        MorePaths.relativize(
            rootPath,
            cell.getFilesystem()
                .resolve(path.get())
                .resolve(cell.getBuckConfigView(ParserConfig.class).getBuildFileName()));
    Preconditions.checkState(cellFilesystem.exists(buildFilePath));
    SourcePath sourcePath = PathSourcePath.of(cell.getFilesystem(), buildFilePath);
    builder.add(QueryFileTarget.of(sourcePath));
  }
  return builder.build();
}