| 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 |
|
| 20 |
from typing import Tuple |
| 21 |
|
| 22 |
import dns.exception |
| 23 |
|
| 24 |
|
| 25 |
def from_text(text: str) -> Tuple[int, int, int]: |
| 26 |
"""Convert the text form of a range in a ``$GENERATE`` statement to an |
| 27 |
integer. |
| 28 |
|
| 29 |
*text*, a ``str``, the textual range in ``$GENERATE`` form. |
| 30 |
|
| 31 |
Returns a tuple of three ``int`` values ``(start, stop, step)``. |
| 32 |
""" |
| 33 |
|
| 34 |
start = -1 |
| 35 |
stop = -1 |
| 36 |
step = 1 |
| 37 |
cur = "" |
| 38 |
state = 0 |
| 39 |
# state 0 1 2 |
| 40 |
# x - y / z |
| 41 |
|
| 42 |
if text and text[0] == "-": |
| 43 |
raise dns.exception.SyntaxError("Start cannot be a negative number") |
| 44 |
|
| 45 |
for c in text: |
| 46 |
if c == "-" and state == 0: |
| 47 |
start = int(cur) |
| 48 |
cur = "" |
| 49 |
state = 1 |
| 50 |
elif c == "/": |
| 51 |
stop = int(cur) |
| 52 |
cur = "" |
| 53 |
state = 2 |
| 54 |
elif c.isdigit(): |
| 55 |
cur += c |
| 56 |
else: |
| 57 |
raise dns.exception.SyntaxError(f"Could not parse {c}") |
| 58 |
|
| 59 |
if state == 0: |
| 60 |
raise dns.exception.SyntaxError("no stop value specified") |
| 61 |
elif state == 1: |
| 62 |
stop = int(cur) |
| 63 |
else: |
| 64 |
assert state == 2 |
| 65 |
step = int(cur) |
| 66 |
|
| 67 |
assert step >= 1 |
| 68 |
assert start >= 0 |
| 69 |
if start > stop: |
| 70 |
raise dns.exception.SyntaxError("start must be <= stop") |
| 71 |
|
| 72 |
return (start, stop, step) |