You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sexpy.py 1.0KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. from __future__ import absolute_import, division
  4. from twisted.python.compat import intToBytes
  5. def parse(s):
  6. s = s.strip()
  7. expr = []
  8. while s:
  9. if s[0:1] == b'(':
  10. newSexp = []
  11. if expr:
  12. expr[-1].append(newSexp)
  13. expr.append(newSexp)
  14. s = s[1:]
  15. continue
  16. if s[0:1] == b')':
  17. aList = expr.pop()
  18. s=s[1:]
  19. if not expr:
  20. assert not s
  21. return aList
  22. continue
  23. i = 0
  24. while s[i:i+1].isdigit(): i+=1
  25. assert i
  26. length = int(s[:i])
  27. data = s[i+1:i+1+length]
  28. expr[-1].append(data)
  29. s=s[i+1+length:]
  30. assert 0, "this should not happen"
  31. def pack(sexp):
  32. s = b""
  33. for o in sexp:
  34. if type(o) in (type(()), type([])):
  35. s+=b'('
  36. s+=pack(o)
  37. s+=b')'
  38. else:
  39. s+=intToBytes(len(o)) + b":" + o
  40. return s