rangelib.py: Add parse_raw() method.

parse_raw() parses a string generated by RangeSet.to_string_raw().

>>> RangeSet.parse_raw(RangeSet("0-9").to_string_raw())
<RangeSet("0-9")>

Change-Id: Ia74daa30476d5e9ad73c368f4ecc64c755b734a5
This commit is contained in:
Tao Bao 2016-03-24 11:08:51 -07:00
parent cdc8f21180
commit 8179d68458
2 changed files with 27 additions and 0 deletions

View File

@ -71,6 +71,19 @@ class RangeSet(object):
"""
return cls(text)
@classmethod
def parse_raw(cls, text):
"""Parse a string generated by RangeSet.to_string_raw().
>>> RangeSet.parse_raw(RangeSet("0-9").to_string_raw())
<RangeSet("0-9")>
"""
raw = [int(i) for i in text.split(',')]
assert raw[0] == len(raw[1:]), "Invalid raw string."
return cls(data=raw[1:])
def _parse_internal(self, text):
data = []
last = -1

View File

@ -123,3 +123,17 @@ class RangeSetTest(unittest.TestCase):
self.assertTrue(RangeSet(data=[2, 9, 30, 31, 31, 32, 35, 36]).monotonic)
self.assertTrue(RangeSet(data=[0, 5, 5, 10]).monotonic)
self.assertFalse(RangeSet(data=[5, 10, 0, 5]).monotonic)
def test_parse_raw(self):
self.assertEqual(
RangeSet.parse_raw(RangeSet("0-9").to_string_raw()),
RangeSet("0-9"))
self.assertEqual(RangeSet.parse_raw(
RangeSet("2-10 12").to_string_raw()),
RangeSet("2-10 12"))
self.assertEqual(
RangeSet.parse_raw(RangeSet("11 2-10 12 1 0").to_string_raw()),
RangeSet("11 2-10 12 1 0"))
with self.assertRaises(AssertionError):
RangeSet.parse_raw("4,0,10")