grange.py 2.0 KB

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