summaryrefslogtreecommitdiffstats
path: root/tools/releasetools/rangelib.py
blob: 1506658f33c28dd3ee60414b50f279f13d89a239 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# Copyright (C) 2014 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function
import heapq
import itertools

__all__ = ["RangeSet"]

class RangeSet(object):
  """A RangeSet represents a set of nonoverlapping ranges on the
  integers (ie, a set of integers, but efficient when the set contains
  lots of runs."""

  def __init__(self, data=None):
    self.monotonic = False
    if isinstance(data, str):
      self._parse_internal(data)
    elif data:
      self.data = tuple(self._remove_pairs(data))
    else:
      self.data = ()

  def __iter__(self):
    for i in range(0, len(self.data), 2):
      yield self.data[i:i+2]

  def __eq__(self, other):
    return self.data == other.data
  def __ne__(self, other):
    return self.data != other.data
  def __nonzero__(self):
    return bool(self.data)

  def __str__(self):
    if not self.data:
      return "empty"
    else:
      return self.to_string()

  def __repr__(self):
    return '<RangeSet("' + self.to_string() + '")>'

  @classmethod
  def parse(cls, text):
    """Parse a text string consisting of a space-separated list of
    blocks and ranges, eg "10-20 30 35-40".  Ranges are interpreted to
    include both their ends (so the above example represents 18
    individual blocks.  Returns a RangeSet object.

    If the input has all its blocks in increasing order, then returned
    RangeSet will have an extra attribute 'monotonic' that is set to
    True.  For example the input "10-20 30" is monotonic, but the input
    "15-20 30 10-14" is not, even though they represent the same set
    of blocks (and the two RangeSets will compare equal with ==).
    """
    return cls(text)

  def _parse_internal(self, text):
    data = []
    last = -1
    monotonic = True
    for p in text.split():
      if "-" in p:
        s, e = p.split("-")
        data.append(int(s))
        data.append(int(e)+1)
        if last <= s <= e:
          last = e
        else:
          monotonic = False
      else:
        s = int(p)
        data.append(s)
        data.append(s+1)
        if last <= s:
          last = s+1
        else:
          monotonic = True
    data.sort()
    self.data = tuple(self._remove_pairs(data))
    self.monotonic = monotonic

  @staticmethod
  def _remove_pairs(source):
    last = None
    for i in source:
      if i == last:
        last = None
      else:
        if last is not None:
          yield last
        last = i
    if last is not None:
      yield last

  def to_string(self):
    out = []
    for i in range(0, len(self.data), 2):
      s, e = self.data[i:i+2]
      if e == s+1:
        out.append(str(s))
      else:
        out.append(str(s) + "-" + str(e-1))
    return " ".join(out)

  def to_string_raw(self):
    return str(len(self.data)) + "," + ",".join(str(i) for i in self.data)

  def union(self, other):
    """Return a new RangeSet representing the union of this RangeSet
    with the argument.

    >>> RangeSet("10-19 30-34").union(RangeSet("18-29"))
    <RangeSet("10-34")>
    >>> RangeSet("10-19 30-34").union(RangeSet("22 32"))
    <RangeSet("10-19 22 30-34")>
    """
    out = []
    z = 0
    for p, d in heapq.merge(zip(self.data, itertools.cycle((+1, -1))),
                            zip(other.data, itertools.cycle((+1, -1)))):
      if (z == 0 and d == 1) or (z == 1 and d == -1):
        out.append(p)
      z += d
    return RangeSet(data=out)

  def intersect(self, other):
    """Return a new RangeSet representing the intersection of this
    RangeSet with the argument.

    >>> RangeSet("10-19 30-34").intersect(RangeSet("18-32"))
    <RangeSet("18-19 30-32")>
    >>> RangeSet("10-19 30-34").intersect(RangeSet("22-28"))
    <RangeSet("")>
    """
    out = []
    z = 0
    for p, d in heapq.merge(zip(self.data, itertools.cycle((+1, -1))),
                            zip(other.data, itertools.cycle((+1, -1)))):
      if (z == 1 and d == 1) or (z == 2 and d == -1):
        out.append(p)
      z += d
    return RangeSet(data=out)

  def subtract(self, other):
    """Return a new RangeSet representing subtracting the argument
    from this RangeSet.

    >>> RangeSet("10-19 30-34").subtract(RangeSet("18-32"))
    <RangeSet("10-17 33-34")>
    >>> RangeSet("10-19 30-34").subtract(RangeSet("22-28"))
    <RangeSet("10-19 30-34")>
    """

    out = []
    z = 0
    for p, d in heapq.merge(zip(self.data, itertools.cycle((+1, -1))),
                            zip(other.data, itertools.cycle((-1, +1)))):
      if (z == 0 and d == 1) or (z == 1 and d == -1):
        out.append(p)
      z += d
    return RangeSet(data=out)

  def overlaps(self, other):
    """Returns true if the argument has a nonempty overlap with this
    RangeSet.

    >>> RangeSet("10-19 30-34").overlaps(RangeSet("18-32"))
    True
    >>> RangeSet("10-19 30-34").overlaps(RangeSet("22-28"))
    False
    """

    # This is like intersect, but we can stop as soon as we discover the
    # output is going to be nonempty.
    z = 0
    for _, d in heapq.merge(zip(self.data, itertools.cycle((+1, -1))),
                            zip(other.data, itertools.cycle((+1, -1)))):
      if (z == 1 and d == 1) or (z == 2 and d == -1):
        return True
      z += d
    return False

  def size(self):
    """Returns the total size of the RangeSet (ie, how many integers
    are in the set).

    >>> RangeSet("10-19 30-34").size()
    15
    """

    total = 0
    for i, p in enumerate(self.data):
      if i % 2:
        total += p
      else:
        total -= p
    return total

  def map_within(self, other):
    """'other' should be a subset of 'self'.  Returns a RangeSet
    representing what 'other' would get translated to if the integers
    of 'self' were translated down to be contiguous starting at zero.

    >>> RangeSet("0-9").map_within(RangeSet("3-4"))
    <RangeSet("3-4")>
    >>> RangeSet("10-19").map_within(RangeSet("13-14"))
    <RangeSet("3-4")>
    >>> RangeSet("10-19 30-39").map_within(RangeSet("17-19 30-32"))
    <RangeSet("7-12")>
    >>> RangeSet("10-19 30-39").map_within(RangeSet("12-13 17-19 30-32"))
    <RangeSet("2-3 7-12")>
    """

    out = []
    offset = 0
    start = None
    for p, d in heapq.merge(zip(self.data, itertools.cycle((-5, +5))),
                            zip(other.data, itertools.cycle((-1, +1)))):
      if d == -5:
        start = p
      elif d == +5:
        offset += p-start
        start = None
      else:
        out.append(offset + p - start)
    return RangeSet(data=out)

  def extend(self, n):
    """Extend the RangeSet by 'n' blocks.

    The lower bound is guaranteed to be non-negative.

    >>> RangeSet("0-9").extend(1)
    <RangeSet("0-10")>
    >>> RangeSet("10-19").extend(15)
    <RangeSet("0-34")>
    >>> RangeSet("10-19 30-39").extend(4)
    <RangeSet("6-23 26-43")>
    >>> RangeSet("10-19 30-39").extend(10)
    <RangeSet("0-49")>
    """
    out = self
    for i in range(0, len(self.data), 2):
      s, e = self.data[i:i+2]
      s1 = max(0, s - n)
      e1 = e + n
      out = out.union(RangeSet(str(s1) + "-" + str(e1-1)))
    return out


if __name__ == "__main__":
  import doctest
  doctest.testmod()