message.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright (C) 2009 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. #
  16. # Functions for reading and parsing cc messages
  17. # Currently these are only abstraction functions for JSON conversion.
  18. #
  19. import sys
  20. import struct
  21. import json
  22. def to_wire(items):
  23. '''Encodes the given python structure in JSON, and converts the
  24. result to bytes. Raises a TypeError if the given structure is
  25. not serializable with JSON.'''
  26. return json.dumps(items).encode('utf8')
  27. def from_wire(data):
  28. '''Decodes the given bytes and parses it with the builtin JSON
  29. parser. Raises a ValueError if the data is not valid JSON.
  30. Raises an AttributeError if the given object has no decode()
  31. method (which should return a string).
  32. '''
  33. return json.loads(data.decode('utf8'), strict=False)
  34. if __name__ == "__main__":
  35. import doctest
  36. doctest.testmod()