grange.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose with or without fee is hereby granted,
  5. # provided that the above copyright notice and this permission notice
  6. # appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  9. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  11. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  14. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """DNS GENERATE range conversion."""
  16. import dns
  17. def from_text(text):
  18. """Convert the text form of a range in a GENERATE statement to an
  19. integer.
  20. @param text: the textual range
  21. @type text: string
  22. @return: The start, stop and step values.
  23. @rtype: tuple
  24. """
  25. # TODO, figure out the bounds on start, stop and step.
  26. step = 1
  27. cur = ''
  28. state = 0
  29. # state 0 1 2 3 4
  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 = 2
  38. elif c == '/':
  39. stop = int(cur)
  40. cur = ''
  41. state = 4
  42. elif c.isdigit():
  43. cur += c
  44. else:
  45. raise dns.exception.SyntaxError("Could not parse %s" % (c))
  46. if state in (1, 3):
  47. raise dns.exception.SyntaxError()
  48. if state == 2:
  49. stop = int(cur)
  50. if state == 4:
  51. step = int(cur)
  52. assert step >= 1
  53. assert start >= 0
  54. assert start <= stop
  55. # TODO, can start == stop?
  56. return (start, stop, step)