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

The following examples show how to use com.google.common.collect.ImmutableSet#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: Cookie.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example 2
Source File: DefaultGraphTransformationEngine.java    From buck with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 3
Source File: OwnersReport.java    From buck with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 4
Source File: BuildFileManifestPojoizer.java    From buck with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: BuildPackagePathToUnconfiguredTargetNodePackageComputation.java    From buck with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 6
Source File: BuckQueryEnvironment.java    From buck with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 7
Source File: BuckQueryEnvironment.java    From buck with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 8
Source File: BuildCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
@Value.Lazy
default ImmutableSet<BuildTarget> getBuildTargets() {
  ImmutableSet.Builder<BuildTarget> builder =
      ImmutableSet.builderWithExpectedSize(getBuildTargetWithOutputs().size());
  getBuildTargetWithOutputs()
      .forEach(targetWithOutputs -> builder.add(targetWithOutputs.getBuildTarget()));
  return builder.build();
}
 
Example 9
Source File: AbstractCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 10
Source File: DefaultDependencyFileRuleKeyFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 11
Source File: BuildReport.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 12
Source File: VisibilityPatterns.java    From buck with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 13
Source File: CxxConstructorArg.java    From buck with Apache License 2.0 5 votes vote down vote up
/** 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()));
  }
}
 
Example 14
Source File: GroupedList.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 15
Source File: BuildConfigurationFunction.java    From bazel with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: LeftComposingComputation.java    From buck with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 17
Source File: ImmutableSetRuntimeCodec.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 18
Source File: LegacyIncludeScanner.java    From bazel with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 19
Source File: RuleAnalysisLegacyBuildRuleView.java    From buck with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 20
Source File: AbstractOffsetMap.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
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());
}