View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.checkstyle;
6   
7   import com.google.common.collect.FluentIterable;
8   import java.util.ArrayList;
9   import java.util.Collection;
10  import java.util.Iterator;
11  
12  /**
13   * Represents a set of LineRange objects. For example, an instance of this class
14   * could represent all the line ranges for methods in a given Java source code
15   * file.
16   *
17   * @since 0.16
18   */
19  public final class LineRanges {
20  
21      /**
22       * Line ranges collected so far.
23       */
24      private final Collection<LineRange> lines;
25  
26      /**
27       * Default constructor.
28       */
29      public LineRanges() {
30          this.lines = new ArrayList<>(20);
31      }
32  
33      /**
34       * Adds a line range to the collection.
35       *
36       * @param line The line range to add to the collection
37       */
38      public void add(final LineRange line) {
39          this.lines.add(line);
40      }
41  
42      /**
43       * Returns an iterator for this collection.
44       *
45       * @return Iterator pointing to the internal collections elements
46       */
47      public Iterator<LineRange> iterator() {
48          return this.lines.iterator();
49      }
50  
51      /**
52       * Detects if the given line number is within any of the line ranges.
53       *
54       * @param line The given line number to check
55       * @return True if the given line number is within any line range
56       */
57      public boolean inRange(final int line) {
58          return !this.lines.isEmpty()
59              && FluentIterable.from(this.lines)
60              .anyMatch(new LineWithAny(line));
61      }
62  
63      /**
64       * Gets the subset of LineRanges that are within all given ranges. Does
65       * not return null; instead, returns empty range if there are no matches.
66       *
67       * @param ranges The ranges to filter on
68       * @return Returns all LineRange elements that are within range
69       */
70      public LineRanges within(final LineRanges ranges) {
71          final LineRanges result = new com.qulice.checkstyle.LineRanges();
72          final Iterator<LineRange> iterator = ranges.iterator();
73          while (iterator.hasNext()) {
74              final LineRange next = iterator.next();
75              for (final LineRange line : this.lines) {
76                  if (next.within(line)) {
77                      result.add(line);
78                  }
79              }
80          }
81          return result;
82      }
83  
84      /**
85       * Clears the collection.
86       */
87      public void clear() {
88          this.lines.clear();
89      }
90  }