001 /*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements. See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership. The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License. You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing,
014 * software distributed under the License is distributed on an
015 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
016 * KIND, either express or implied. See the License for the
017 * specific language governing permissions and limitations
018 * under the License.
019 *
020 */
021 package org.apache.qpid.transport;
022
023 import java.util.Iterator;
024 import java.util.ListIterator;
025 import java.util.LinkedList;
026
027 import static org.apache.qpid.util.Serial.*;
028
029 /**
030 * RangeSet
031 *
032 * @author Rafael H. Schloming
033 */
034
035 public final class RangeSet implements Iterable<Range>
036 {
037
038 private LinkedList<Range> ranges = new LinkedList<Range>();
039
040 public int size()
041 {
042 return ranges.size();
043 }
044
045 public Iterator<Range> iterator()
046 {
047 return ranges.iterator();
048 }
049
050 public Range getFirst()
051 {
052 return ranges.getFirst();
053 }
054
055 public boolean includes(Range range)
056 {
057 for (Range r : this)
058 {
059 if (r.includes(range))
060 {
061 return true;
062 }
063 }
064
065 return false;
066 }
067
068 public boolean includes(int n)
069 {
070 for (Range r : this)
071 {
072 if (r.includes(n))
073 {
074 return true;
075 }
076 }
077
078 return false;
079 }
080
081 public void add(Range range)
082 {
083 ListIterator<Range> it = ranges.listIterator();
084
085 while (it.hasNext())
086 {
087 Range next = it.next();
088 if (range.touches(next))
089 {
090 it.remove();
091 range = range.span(next);
092 }
093 else if (lt(range.getUpper(), next.getLower()))
094 {
095 it.previous();
096 it.add(range);
097 return;
098 }
099 }
100
101 it.add(range);
102 }
103
104 public void add(int lower, int upper)
105 {
106 add(new Range(lower, upper));
107 }
108
109 public void add(int value)
110 {
111 add(value, value);
112 }
113
114 public void clear()
115 {
116 ranges.clear();
117 }
118
119 public RangeSet copy()
120 {
121 RangeSet copy = new RangeSet();
122 copy.ranges.addAll(ranges);
123 return copy;
124 }
125
126 public String toString()
127 {
128 StringBuffer str = new StringBuffer();
129 str.append("{");
130 boolean first = true;
131 for (Range range : ranges)
132 {
133 if (first)
134 {
135 first = false;
136 }
137 else
138 {
139 str.append(", ");
140 }
141 str.append(range);
142 }
143 str.append("}");
144 return str.toString();
145 }
146
147 }
|