Example usage for com.google.common.collect RangeSet add

List of usage examples for com.google.common.collect RangeSet add

Introduction

In this page you can find the example usage for com.google.common.collect RangeSet add.

Prototype

void add(Range<C> range);

Source Link

Document

Adds the specified range to this RangeSet (optional operation).

Usage

From source file:com.google.googlejavaformat.java.RemoveUnusedImports.java

/** Applies the replacements to the given source, and re-format any edited javadoc. */
private static String applyReplacements(String source, RangeMap<Integer, String> replacements) {
    // save non-empty fixed ranges for reformatting after fixes are applied
    RangeSet<Integer> fixedRanges = TreeRangeSet.create();

    // Apply the fixes in increasing order, adjusting ranges to account for
    // earlier fixes that change the length of the source. The output ranges are
    // needed so we can reformat fixed regions, otherwise the fixes could just
    // be applied in descending order without adjusting offsets.
    StringBuilder sb = new StringBuilder(source);
    int offset = 0;
    for (Map.Entry<Range<Integer>, String> replacement : replacements.asMapOfRanges().entrySet()) {
        Range<Integer> range = replacement.getKey();
        String replaceWith = replacement.getValue();
        int start = offset + range.lowerEndpoint();
        int end = offset + range.upperEndpoint();
        sb.replace(start, end, replaceWith);
        if (!replaceWith.isEmpty()) {
            fixedRanges.add(Range.closedOpen(start, end));
        }/*from   www .ja va2  s .  c o m*/
        offset += replaceWith.length() - (range.upperEndpoint() - range.lowerEndpoint());
    }
    String result = sb.toString();

    // If there were any non-empty replaced ranges (e.g. javadoc), reformat the fixed regions.
    // We could avoid formatting twice in --fix-imports=also mode, but that is not the default
    // and removing imports won't usually affect javadoc.
    if (!fixedRanges.isEmpty()) {
        try {
            result = new Formatter().formatSource(result, fixedRanges.asRanges());
        } catch (FormatterException e) {
            // javadoc reformatting is best-effort
        }
    }
    return result;
}

From source file:com.google.googlejavaformat.java.SnippetFormatter.java

/** Runs the Google Java formatter on the given source, with only the given ranges specified. */
public List<Replacement> format(SnippetKind kind, String source, List<Range<Integer>> ranges, int initialIndent,
        boolean includeComments) throws FormatterException {
    RangeSet<Integer> rangeSet = TreeRangeSet.create();
    for (Range<Integer> range : ranges) {
        rangeSet.add(range);
    }/* ww  w  . j a  v  a 2 s .  c  om*/
    if (includeComments) {
        if (kind != SnippetKind.COMPILATION_UNIT) {
            throw new IllegalArgumentException("comment formatting is only supported for compilation units");
        }
        return formatter.getFormatReplacements(source, ranges);
    }
    SnippetWrapper wrapper = snippetWrapper(kind, source, initialIndent);
    ranges = offsetRanges(ranges, wrapper.offset);

    String replacement = formatter.formatSource(wrapper.contents.toString(), ranges);
    replacement = replacement.substring(wrapper.offset,
            replacement.length() - (wrapper.contents.length() - wrapper.offset - source.length()));

    List<Replacement> replacements = toReplacements(source, replacement);
    List<Replacement> filtered = new ArrayList<>();
    for (Replacement r : replacements) {
        if (rangeSet.encloses(r.getReplaceRange())) {
            filtered.add(r);
        }
    }
    return filtered;
}

From source file:io.druid.query.filter.InDimFilter.java

@Override
public RangeSet<String> getDimensionRangeSet(String dimension) {
    if (!Objects.equals(getDimension(), dimension) || getExtractionFn() != null) {
        return null;
    }// ww  w . ja  va 2s.c o  m
    RangeSet<String> retSet = TreeRangeSet.create();
    for (String value : values) {
        retSet.add(Range.singleton(Strings.nullToEmpty(value)));
    }
    return retSet;
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.VFlow.java

private void onNumberOfLinesChange(Observable x, Number o, Number n) {
    if (n.intValue() > o.intValue()) {
        RangeSet<Integer> toUpdate = TreeRangeSet.create();
        toUpdate.add(Range.closedOpen(Integer.valueOf(o.intValue()), Integer.valueOf(n.intValue())));
        triggerUpdate(toUpdate);//from   ww  w  .j a  v a2 s.  c o  m
    } else if (n.intValue() < o.intValue()) {
        RangeSet<Integer> toRelease = TreeRangeSet.create();
        toRelease.add(Range.closed(Integer.valueOf(n.intValue()), Integer.valueOf(o.intValue())));
        triggerRelease(toRelease);
    }
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.VFlow.java

private void onVisibleLinesChange(Observable x, Range<Integer> o, Range<Integer> n) {
    RangeSet<Integer> toUpdate = TreeRangeSet.create();
    RangeSet<Integer> toRelease = TreeRangeSet.create();

    if (o != null && n != null) {
        RangeSet<Integer> hidden = TreeRangeSet.create();
        hidden.add(o);
        hidden.remove(n);/*  w ww  .ja  va 2 s  . c om*/

        toRelease.addAll(hidden);
    }

    if (n != null) {
        toUpdate.add(getVisible());
    }

    triggerUpdate(toUpdate);
    triggerRelease(toRelease);
    requestLayout();
}

From source file:com.google.errorprone.bugpatterns.javadoc.UnescapedEntity.java

private Description handle(@Nullable DocTreePath path, VisitorState state) {
    if (path == null) {
        return NO_MATCH;
    }/*from   w w w .  j  ava  2 s .  c  o  m*/
    RangesFinder rangesFinder = new RangesFinder(state);
    rangesFinder.scan(path, null);
    Comment comment = ((DCDocComment) path.getDocComment()).comment;
    Matcher matcher = GENERIC_PATTERN.matcher(comment.getText());
    RangeSet<Integer> generics = TreeRangeSet.create();
    while (matcher.find()) {
        generics.add(
                Range.closedOpen(comment.getSourcePos(matcher.start()), comment.getSourcePos(matcher.end())));
    }
    RangeSet<Integer> emittedFixes = fixGenerics(generics, rangesFinder.preTags, rangesFinder.dontEmitCodeFix,
            state);
    new EntityChecker(state, generics, rangesFinder.preTags, emittedFixes).scan(path, null);
    return NO_MATCH;
}

From source file:org.robotframework.red.nattable.painter.RedTableTextPainter.java

private RangeSet<Integer> getHyperlinks(final TableCellStringData data, final String text,
        final String originalText) {
    final List<TableCellStringData> datas = data == null ? new ArrayList<>()
            : Lists.<TableCellStringData>newArrayList(data);
    final List<Range<Integer>> hyperlinkRanges = datas.stream().map(TableCellStringData::getHyperlinkRegion)
            .filter(notNull()).collect(toList());

    final RangeSet<Integer> hyperlinksRanges = mapOriginalRangesToCurrentLabel(hyperlinkRanges, text,
            originalText);//from   ww w .j a  v a  2 s . c o m
    if (hyperlinksRanges.isEmpty()) {
        hyperlinksRanges.add(Range.closed(-1, -1));
    }
    return hyperlinksRanges;
}

From source file:org.apache.druid.query.filter.SelectorDimFilter.java

@Override
public RangeSet<String> getDimensionRangeSet(String dimension) {
    if (!Objects.equals(getDimension(), dimension) || getExtractionFn() != null) {
        return null;
    }/*from w ww.  j  a v  a  2 s . c  o  m*/
    RangeSet<String> retSet = TreeRangeSet.create();
    String valueEquivalent = NullHandling.nullToEmptyIfNeeded(value);
    if (valueEquivalent == null) {
        // Case when SQL compatible null handling is enabled
        // Nulls are less than empty String in segments
        retSet.add(Range.lessThan(""));
    } else {
        retSet.add(Range.singleton(valueEquivalent));
    }
    return retSet;
}

From source file:org.nmdp.ngs.tools.EvaluateScaffolds.java

@Override
public Integer call() throws Exception {
    PrintWriter writer = null;//from  w ww. j a  v a  2s  .c o  m
    try {
        writer = writer(evalFile);

        Sequence reference = readReference();
        List<Sequence> scaffolds = readScaffolds();

        writer.println("#reference length = " + reference.length());
        writer.println("#scaffold count = " + scaffolds.size());
        writer.println("#scaffold lengths = " + dumpLengths(scaffolds));

        RangeSet<Long> ranges = TreeRangeSet.create();
        for (HighScoringPair hsp : blastn(referenceFastaFile, scaffoldsFastaFile)) {
            if (reference.getName().equals(hsp.target())) {
                writer.println("#" + hsp.toString());
                if (hsp.targetStart() <= hsp.targetEnd()) { // strands match
                    ranges.add(Range.closed(hsp.targetStart(), hsp.targetEnd()));
                } else {
                    ranges.add(Range.closed(hsp.targetEnd(), hsp.targetStart()));
                }
            }
        }

        writer.println("#coalesced intervals = " + ranges);

        long breadthOfCoverage = 0;
        for (Range<Long> range : ranges.asRanges()) {
            breadthOfCoverage += ContiguousSet.create(range, DiscreteDomain.longs()).size();
        }
        double normalizedBreadthOfCoverage = (double) breadthOfCoverage / (double) reference.length();
        writer.println("#breadth-of-coverage = " + breadthOfCoverage);
        writer.println("#normalized breadth-of-coverage = " + normalizedBreadthOfCoverage);

        StringBuilder sb = new StringBuilder();
        sb.append(referenceFastaFile.getName());
        sb.append("\t");
        sb.append(scaffoldsFastaFile.getName());
        sb.append("\t");
        sb.append(reference.length());
        sb.append("\t");
        sb.append(scaffolds.size());
        sb.append("\t");
        sb.append(ranges.asRanges().size());
        sb.append("\t");
        sb.append(breadthOfCoverage);
        sb.append("\t");
        sb.append(normalizedBreadthOfCoverage);
        sb.append("\t");
        writer.println(sb.toString());

        return 0;
    } finally {
        try {
            writer.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:com.google.testing.pogen.parser.template.TemplateParser.java

/**
 * Returns a {@link RangeSet} of indexes between the start and the end tags
 * for nested tags. If there're nested tags, returns the outermost ranges.
 * /*from  w  w w .j  av  a  2  s.c o  m*/
 * @param text
 *            the string to be parsed
 * @param startPattern
 *            the regular expression of start tags to find
 * @param endPattern
 *            the regular expression of end tags to find
 * @return the {@link RangeSet} of the indexes between the start and the end
 *         tags
 * @throws TemplateParseException
 *             if the specified template is in bad format where broken pairs
 *             of start and end tags appear
 */
protected static RangeSet<Integer> getIndexRangesOfNestedTags(String text, Pattern startPattern,
        Pattern endPattern) throws TemplateParseException {
    RangeSet<Integer> rangeSet = TreeRangeSet.create();

    List<Integer> startIndexes = getMatchedIndexes(text, startPattern);
    List<Integer> endIndexes = getMatchedIndexes(text, endPattern);

    int startIndex = 0, endIndex = 0;
    // Check whether the sizes of start tags and end tags are equal
    if (startIndexes.size() != endIndexes.size()) {
        throw new TemplateParseException(String.format(
                "The sizes of start tags and end tags are not equal (#start tags: %d, #end tags: %d).",
                startIndexes.size(), endIndexes.size()));
    }

    int depth = 0, lastStartIndex = 0;
    while (endIndex < endIndexes.size()) {
        boolean consumedStartIndexes = startIndex == startIndexes.size();
        // Process a previous index before a next index
        if (consumedStartIndexes || endIndexes.get(endIndex) < startIndexes.get(startIndex)) {
            if (--depth <= 0) {
                if (depth < 0) {
                    // Check whether all start tags and end tags are paired
                    // correctly
                    throw new TemplateParseException(
                            String.format("Broken pairs of start and end tags are found."));
                }
                rangeSet.add(Range.closedOpen(lastStartIndex, endIndexes.get(endIndex)));
            }
            endIndex++;
        } else {
            if (depth++ == 0) {
                lastStartIndex = startIndexes.get(startIndex);
            }
            startIndex++;
        }
    }
    return rangeSet;
}