1# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3# Copyright (C) 2012-2017 Nominum, Inc.
4#
5# Permission to use, copy, modify, and distribute this software and its
6# documentation for any purpose with or without fee is hereby granted,
7# provided that the above copyright notice and this permission notice
8# appear in all copies.
9#
10# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18"""DNS GENERATE range conversion."""
19
20import dns
21
22def from_text(text):
23    """Convert the text form of a range in a ``$GENERATE`` statement to an
24    integer.
25
26    *text*, a ``str``, the textual range in ``$GENERATE`` form.
27
28    Returns a tuple of three ``int`` values ``(start, stop, step)``.
29    """
30
31    # TODO, figure out the bounds on start, stop and step.
32    step = 1
33    cur = ''
34    state = 0
35    # state   0 1 2 3 4
36    #         x - y / z
37
38    if text and text[0] == '-':
39        raise dns.exception.SyntaxError("Start cannot be a negative number")
40
41    for c in text:
42        if c == '-' and state == 0:
43            start = int(cur)
44            cur = ''
45            state = 2
46        elif c == '/':
47            stop = int(cur)
48            cur = ''
49            state = 4
50        elif c.isdigit():
51            cur += c
52        else:
53            raise dns.exception.SyntaxError("Could not parse %s" % (c))
54
55    if state in (1, 3):
56        raise dns.exception.SyntaxError()
57
58    if state == 2:
59        stop = int(cur)
60
61    if state == 4:
62        step = int(cur)
63
64    assert step >= 1
65    assert start >= 0
66    assert start <= stop
67    # TODO, can start == stop?
68
69    return (start, stop, step)
70