Example usage for com.google.common.collect Range isEmpty

List of usage examples for com.google.common.collect Range isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect Range isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this range is of the form [v..v) or (v..v] .

Usage

From source file:org.dishevelled.bio.range.tree.CenteredRangeTree.java

/**
 * Depth first search.//from   w w  w.j a v a2 s  .c  o m
 *
 * @param query query range
 * @param node node
 * @param result list of matching ranges
 * @param visited set of visited nodes
 */
private void depthFirstSearch(final Range<C> query, final Node node, final List<Range<C>> result,
        final Set<Node> visited) {
    if (node == null || visited.contains(node) || query.isEmpty()) {
        return;
    }
    if (node.left() != null && Ranges.isLessThan(query, node.center())) {
        depthFirstSearch(query, node.left(), result, visited);
    } else if (node.right() != null && Ranges.isGreaterThan(query, node.center())) {
        depthFirstSearch(query, node.right(), result, visited);
    }
    if (Ranges.isGreaterThan(query, node.center())) {
        for (Range<C> range : node.overlapByUpperEndpoint()) {
            if (Ranges.intersect(range, query)) {
                result.add(range);
            }
            if (Ranges.isGreaterThan(query, range.upperEndpoint())) {
                break;
            }
        }
    } else if (Ranges.isLessThan(query, node.center())) {
        for (Range<C> range : node.overlapByLowerEndpoint()) {
            if (Ranges.intersect(range, query)) {
                result.add(range);
            }
            if (Ranges.isLessThan(query, range.lowerEndpoint())) {
                break;
            }
        }
    } else {
        result.addAll(node.overlapByLowerEndpoint());
    }
    visited.add(node);
}

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

@Override
public void append(String text, Range<Integer> range) {
    if (!range.isEmpty()) {
        boolean sawNewlines = false;
        // Skip over input line we've passed.
        int iN = javaInput.getLineCount();
        while (iLine < iN && (javaInput.getRanges(iLine).isEmpty()
                || javaInput.getRanges(iLine).upperEndpoint() <= range.lowerEndpoint())) {
            if (javaInput.getRanges(iLine).isEmpty()) {
                // Skipped over a blank line.
                sawNewlines = true;/*  w w w.  ja va 2  s.c  o m*/
            }
            ++iLine;
        }
        /*
         * Output blank line if we've called {@link OpsBuilder#blankLine}{@code (true)} here, or if
         * there's a blank line here and it's a comment.
         */
        BlankLineWanted wanted = blankLines.getOrDefault(lastK, BlankLineWanted.NO);
        if (isComment(text) ? sawNewlines : wanted.wanted().orElse(sawNewlines)) {
            ++newlinesPending;
        }
    }
    if (Newlines.isNewline(text)) {
        /*
         * Don't update range information, and swallow extra newlines. The case below for '\n' is for
         * block comments.
         */
        if (newlinesPending == 0) {
            ++newlinesPending;
        }
        spacesPending = 0;
    } else {
        boolean rangesSet = false;
        int textN = text.length();
        for (int i = 0; i < textN; i++) {
            char c = text.charAt(i);
            switch (c) {
            case ' ':
                ++spacesPending;
                break;
            case '\r':
                if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
                    i++;
                }
                // falls through
            case '\n':
                spacesPending = 0;
                ++newlinesPending;
                break;
            default:
                while (newlinesPending > 0) {
                    // drop leading blank lines
                    if (!mutableLines.isEmpty() || lineBuilder.length() > 0) {
                        mutableLines.add(lineBuilder.toString());
                    }
                    lineBuilder = new StringBuilder();
                    rangesSet = false;
                    --newlinesPending;
                }
                while (spacesPending > 0) {
                    lineBuilder.append(' ');
                    --spacesPending;
                }
                lineBuilder.append(c);
                if (!range.isEmpty()) {
                    if (!rangesSet) {
                        while (ranges.size() <= mutableLines.size()) {
                            ranges.add(Formatter.EMPTY_RANGE);
                        }
                        ranges.set(mutableLines.size(), union(ranges.get(mutableLines.size()), range));
                        rangesSet = true;
                    }
                }
            }
        }
    }
    if (!range.isEmpty()) {
        lastK = range.upperEndpoint();
    }
}

From source file:com.github.fge.grappa.matchers.join.JoinMatcherBuilder.java

/**
 * Generic method to build a {@link JoinMatcher}
 *
 * <p>You can use this method directly; note however that the range you will
 * pass as an argument will be {@link Range#intersection(Range) intersected}
 * with {@code Range.atLeast(0)}; if the result of the intersection is an
 * {@link Range#isEmpty() empty range}, this is an error condition.</p>
 *
 * <p>Ranges which are {@link BoundType#OPEN open} on any end will be turned
 * to closed range using {@link Range#canonical(DiscreteDomain)}.</p>
 *
 * @param range the range (must not be null)
 * @return a rule//from w  ww .j a  va  2s  .  com
 * @throws IllegalArgumentException see description
 *
 * @see Range#canonical(DiscreteDomain)
 */
// TODO: check that it actually has an effect
@Cached
public Rule range(@Nonnull Range<Integer> range) {
    Objects.requireNonNull(range, "range must not be null");
    /*
     * We always intersect with that range...
     */
    Range<Integer> realRange = AT_LEAST_ZERO.intersection(range);

    /*
     * Empty ranges not allowed (what are we supposed to do with that
     * anyway?)
     */
    Preconditions.checkArgument(!realRange.isEmpty(),
            "illegal range " + range + ": should not be empty after intersection with " + AT_LEAST_ZERO);

    /*
     * Given that we intersect with AT_LEAST_ZERO, which has a lower bound,
     * the range will always have a lower bound. We want a closed range
     * internally, therefore change it if it is open.
     */
    Range<Integer> closedRange = toClosedRange(realRange);

    /*
     * We always have a lower bound
     */
    int lowerBound = closedRange.lowerEndpoint();

    /*
     * Handle the case where there is no upper bound
     */
    if (!closedRange.hasUpperBound())
        return new BoundedDownJoinMatcher(joined, joining, lowerBound);

    /*
     * There is an upper bound. Handle the case where it is 0 or 1. Since
     * the range is legal, we know that if it is 0, so is the lowerbound;
     * and if it is one, the lower bound is either 0 or 1.
     */
    int upperBound = closedRange.upperEndpoint();
    if (upperBound == 0)
        return new EmptyMatcher();
    if (upperBound == 1)
        return lowerBound == 0 ? new OptionalMatcher(joined) : joined;

    /*
     * So, upper bound is 2 or greater; return the appropriate matcher
     * according to what the lower bound is.
     *
     * Also, if the lower and upper bounds are equal, return a matcher doing
     * a fixed number of matches.
     */
    if (lowerBound == 0)
        return new BoundedUpJoinMatcher(joined, joining, upperBound);

    return lowerBound == upperBound ? new ExactMatchesJoinMatcher(joined, joining, lowerBound)
            : new BoundedBothJoinMatcher(joined, joining, lowerBound, upperBound);
}

From source file:org.dishevelled.bio.range.entrytree.CenteredRangeTree.java

/**
 * Depth first search./* w w  w. j av a  2 s .c om*/
 *
 * @param query query range
 * @param node node
 * @param result list of matching ranges
 * @param visited set of visited nodes
 */
private void depthFirstSearch(final Range<C> query, final Node node, final List<Entry<C, V>> result,
        final Set<Node> visited) {
    if (node == null || visited.contains(node) || query.isEmpty()) {
        return;
    }
    if (node.left() != null && Ranges.isLessThan(query, node.center())) {
        depthFirstSearch(query, node.left(), result, visited);
    } else if (node.right() != null && Ranges.isGreaterThan(query, node.center())) {
        depthFirstSearch(query, node.right(), result, visited);
    }
    if (Ranges.isGreaterThan(query, node.center())) {
        for (Entry<C, V> entry : node.overlapByUpperEndpoint()) {
            Range<C> range = entry.getRange();
            if (Ranges.intersect(range, query)) {
                result.add(entry);
            }
            if (Ranges.isGreaterThan(query, range.upperEndpoint())) {
                break;
            }
        }
    } else if (Ranges.isLessThan(query, node.center())) {
        for (Entry<C, V> entry : node.overlapByLowerEndpoint()) {
            Range<C> range = entry.getRange();
            if (Ranges.intersect(range, query)) {
                result.add(entry);
            }
            if (Ranges.isLessThan(query, range.lowerEndpoint())) {
                break;
            }
        }
    } else {
        result.addAll(node.overlapByLowerEndpoint());
    }
    visited.add(node);
}

From source file:org.dishevelled.bio.range.entrytree.CenteredRangeTree.java

/**
 * Create and return a new node for the specified range entries.
 *
 * @param entries range entries//from  w w  w.ja  v  a  2s  . c o  m
 * @return a new node for the specified range entries
 */
private Node createNode(final Iterable<Entry<C, V>> entries) {
    Entry<C, V> first = Iterables.getFirst(entries, null);
    if (first == null) {
        return null;
    }
    Range<C> span = first.getRange();

    for (Entry<C, V> entry : entries) {
        Range<C> range = entry.getRange();
        span = range.span(span);
    }
    if (span.isEmpty()) {
        return null;
    }
    C center = Ranges.center(span);
    List<Entry<C, V>> left = Lists.newArrayList();
    List<Entry<C, V>> right = Lists.newArrayList();
    List<Entry<C, V>> overlap = Lists.newArrayList();

    for (Entry<C, V> entry : entries) {
        Range<C> range = entry.getRange();
        if (Ranges.isLessThan(range, center)) {
            left.add(entry);
        } else if (Ranges.isGreaterThan(range, center)) {
            right.add(entry);
        } else {
            overlap.add(entry);
        }
    }
    return new Node(center, createNode(left), createNode(right), overlap);
}

From source file:org.dishevelled.bio.range.tree.CenteredRangeTree.java

/**
 * Create and return a new node for the specified ranges.
 *
 * @param ranges ranges/* ww  w  .  java  2  s . c  o m*/
 * @return a new node for the specified ranges
 */
private Node createNode(final Iterable<Range<C>> ranges) {
    Range<C> span = Iterables.getFirst(ranges, null);
    if (span == null) {
        return null;
    }
    for (Range<C> range : ranges) {
        checkNotNull(range, "ranges must not contain null ranges");
        span = range.span(span);
    }
    if (span.isEmpty()) {
        return null;
    }
    C center = Ranges.center(span);
    List<Range<C>> left = Lists.newArrayList();
    List<Range<C>> right = Lists.newArrayList();
    List<Range<C>> overlap = Lists.newArrayList();
    for (Range<C> range : ranges) {
        if (Ranges.isLessThan(range, center)) {
            left.add(range);
        } else if (Ranges.isGreaterThan(range, center)) {
            right.add(range);
        } else {
            overlap.add(range);
        }
    }
    return new Node(center, createNode(left), createNode(right), overlap);
}

From source file:edu.mit.streamjit.impl.compiler2.Storage.java

/**
 * Compute this storage's steady-state throughput and capacity.
 * @param externalSchedule the external schedule
 *//*w ww . j a  v a  2 s . co m*/
public void computeSteadyStateRequirements(Map<ActorGroup, Integer> externalSchedule) {
    Range<Integer> readIndices = readIndexSpan(externalSchedule);
    Range<Integer> writeIndices = writeIndexSpan(externalSchedule);
    assert readIndices.isEmpty() == writeIndices.isEmpty() : readIndices + " " + writeIndices;
    //We need to know the count of indices, so we can't just use the span
    //here.  There may be a lot of indices so writeIndices will use a lot of
    //memory.  But we know (assume) there are no overwrites, so we'll count.
    this.throughput = 0;
    for (Actor a : upstream()) {
        int iterations = a.group().schedule().get(a) * externalSchedule.get(a.group());
        for (int output = 0; output < a.outputs().size(); ++output)
            if (a.outputs().get(output).equals(this))
                this.throughput += iterations * a.push(output).max();
    }
    this.steadyStateCapacity = ContiguousSet.create(readIndices.span(writeIndices), DiscreteDomain.integers())
            .size();
}

From source file:org.cinchapi.concourse.server.model.Ranges.java

/**
 * Return the ranges that include the points that are in {@code a} or the
 * {@code b} one and not in their intersection. The return set will include
 * between 0 and 2 ranges that together include all the points that meet
 * this criteria./*  ww  w . j av  a  2s .co  m*/
 * <p>
 * <strong>NOTE:</strong> If the two ranges do not intersect, then a
 * collection containing both of them is returned (since they already form
 * their xor).
 * </p>
 * 
 * @param a
 * @param b
 * @return the set or ranges that make uValue the symmetric difference
 *         between this range and the {@code other} one
 */
public static Iterable<Range<Value>> xor(Range<Value> a, Range<Value> b) {
    List<Range<Value>> ranges = Lists.newArrayList();
    try {
        Range<Value> intersection = a.intersection(b);
        boolean aStart = compareToLower(a, b) < 0;
        boolean aEnd = compareToUpper(a, b) > 0;
        boolean lower = getLowerBoundType(aStart ? a : b) == BoundType.CLOSED;
        boolean upper = getUpperBoundType(aEnd ? a : b) == BoundType.CLOSED;
        boolean interLower = getLowerBoundType(intersection) == BoundType.OPEN;
        boolean interUpper = getUpperBoundType(intersection) == BoundType.OPEN;
        Range<Value> first;
        if (lower && interLower) {
            first = Range.closed(getLowerEndpoint(aStart ? a : b), getLowerEndpoint(intersection));
        } else if (!lower && interLower) {
            first = Range.openClosed(getLowerEndpoint(aStart ? a : b), getLowerEndpoint(intersection));
        } else if (lower && !interLower) {
            first = Range.closedOpen(getLowerEndpoint(aStart ? a : b), getLowerEndpoint(intersection));
        } else {
            first = Range.open(getLowerEndpoint(aStart ? a : b), getLowerEndpoint(intersection));
        }
        Range<Value> second;
        if (interUpper && upper) {
            second = Range.closed(getUpperEndpoint(intersection), getUpperEndpoint(aEnd ? a : b));
        } else if (!interUpper && upper) {
            second = Range.openClosed(getUpperEndpoint(intersection), getUpperEndpoint(aEnd ? a : b));
        } else if (interUpper && !interUpper) {
            second = Range.closedOpen(getUpperEndpoint(intersection), getUpperEndpoint(aEnd ? a : b));
        } else {
            second = Range.open(getUpperEndpoint(intersection), getUpperEndpoint(aEnd ? a : b));
        }
        if (!first.isEmpty()) {
            ranges.add(first);
        }
        if (!second.isEmpty()) {
            ranges.add(second);
        }
    } catch (IllegalArgumentException e) { // ranges dont intersect
        ranges.add(a);
        ranges.add(b);
    }
    return ranges;
}

From source file:edu.mit.streamjit.impl.compiler2.ActorGroup.java

/**
 * Make loop handles for each Actor that execute the iteration given as
 * an argument, then bind them together in an outer loop body that
 * executes all the iterations.  Before the outer loop we must also
 * reinitialize the splitter/joiner index arrays to their initial
 * values./*  ww w  .j  a v  a  2 s  .c om*/
 */
private MethodHandle makeGroupLoop(Range<Integer> iterations, int unrollFactor,
        Map<Actor, MethodHandle> withRWHandlesBound) {
    if (iterations.isEmpty())
        return Combinators.nop();
    List<MethodHandle> loopHandles = new ArrayList<>(actors().size());
    Map<int[], int[]> requiredCopies = new LinkedHashMap<>();
    for (Actor a : actors())
        loopHandles.add(makeWorkerLoop((WorkerActor) a, withRWHandlesBound.get(a), unrollFactor,
                iterations.lowerEndpoint(), requiredCopies));
    MethodHandle groupLoop = MethodHandles.insertArguments(OVERALL_GROUP_LOOP, 0,
            Combinators.semicolon(loopHandles), iterations.lowerEndpoint(), iterations.upperEndpoint(),
            unrollFactor);
    if (!requiredCopies.isEmpty()) {
        int[][] copies = new int[requiredCopies.size() * 2][];
        int i = 0;
        for (Map.Entry<int[], int[]> e : requiredCopies.entrySet()) {
            copies[i++] = e.getKey();
            copies[i++] = e.getValue();
        }
        groupLoop = Combinators
                .semicolon(MethodHandles.insertArguments(REINITIALIZE_ARRAYS, 0, (Object) copies), groupLoop);
    }
    return groupLoop;
}

From source file:org.sosy_lab.cpachecker.cfa.ast.c.CInitializers.java

/**
 * Handle the case when the current subobject that will be initialized next
 * is an array.//from www .  ja  v  a2  s .c  o  m
 * This method only prepares the two stacks by pushing one object on both
 * of them (for the next element to be initialized, and the iterator for the
 * remainder of the elements).
 * @param currentSubobject The struct/union to be initialized
 * @param startIndex The index of the first element to be initialized
 * @param arrayType The type of currentSubobject
 * @param currentSubobjects as in {@link #handleInitializerList(CExpression, CInitializerList, FileLocation, CFAEdge)}
 * @param nextSubobjects as in {@link #handleInitializerList(CExpression, CInitializerList, FileLocation, CFAEdge)}
 */
private static boolean handleInitializerForArray(final CExpression currentSubobject, final long startIndex,
        final CArrayType arrayType, final Deque<CExpression> currentSubobjects,
        final Deque<Iterator<CExpression>> nextSubobjects, final FileLocation loc, final CFAEdge edge,
        final CDesignator designator) throws UnrecognizedCCodeException {

    Range<Long> arrayIndices;
    if (arrayType.getLength() instanceof CIntegerLiteralExpression) {
        // fixed-size array
        BigInteger size = ((CIntegerLiteralExpression) arrayType.getLength()).getValue();
        if (!BigInteger.valueOf(size.longValue()).equals(size)) {
            throw new UnrecognizedCCodeException(
                    "Size of type " + arrayType + " is too large to initialize explicitly", edge, designator);
        }
        // TODO use DiscreteDomain.bigintegers() when it's available.

        arrayIndices = Range.closedOpen(startIndex, size.longValue());

    } else if (arrayType.getLength() == null) {
        // variable-length array, this array goes until there are no more initializer values

        arrayIndices = Range.atLeast(startIndex);

    } else {
        throw new UnrecognizedCCodeException(
                "Cannot initialize arrays with variable modified type like " + arrayType, edge, designator);
    }

    if (arrayIndices.isEmpty()) {
        return false;
    }

    final CType elementType = arrayType.getType();

    Set<Long> indexSet = ContiguousSet.create(arrayIndices, DiscreteDomain.longs());
    Iterator<CExpression> elements = from(indexSet).transform(new Function<Long, CExpression>() {
        @Override
        public CExpression apply(Long pInput) {
            CExpression index = new CIntegerLiteralExpression(loc, CNumericTypes.INT,
                    BigInteger.valueOf(pInput.longValue()));

            return new CArraySubscriptExpression(loc, elementType, currentSubobject, index);
        }
    }).iterator();

    CExpression firstElement = elements.next();

    currentSubobjects.push(firstElement);
    nextSubobjects.push(elements);

    return true;
}