# HG changeset patch # User Paul Boddie # Date 1411567503 -7200 # Node ID bfb1e0c934714588e87d51f115f20b076d2fea2a # Parent ffea599ea31be165d752d24a8eee766f6f3898bc Moved representation conversion functions into vContent. diff -r ffea599ea31b -r bfb1e0c93471 vCalendar.py --- a/vCalendar.py Mon Sep 22 18:26:59 2014 +0200 +++ b/vCalendar.py Wed Sep 24 16:05:03 2014 +0200 @@ -276,4 +276,7 @@ return vContent.iterwrite(stream_or_string, write, encoding, line_length, vCalendarStreamWriter) +to_dict = vContent.to_dict +to_node = vContent.to_node + # vim: tabstop=4 expandtab shiftwidth=4 diff -r ffea599ea31b -r bfb1e0c93471 vContent.py --- a/vContent.py Mon Sep 22 18:26:59 2014 +0200 +++ b/vContent.py Wed Sep 24 16:05:03 2014 +0200 @@ -620,6 +620,43 @@ else: return codecs.open(stream_or_string, "w", encoding=(encoding or default_encoding)) +def items_to_dict(items): + + """ + Return the given 'items' as a dictionary mapping names to tuples of the form + (value, attributes). + """ + + d = {} + for name, attr, value in items: + if not d.has_key(name): + d[name] = [] + if isinstance(value, list): + d[name].append((items_to_dict(value), attr)) + else: + d[name].append((value, attr)) + return d + +def dict_to_items(d): + + """ + Return 'd' converted to a list of items suitable for serialisation using + iterwrite. + """ + + items = [] + for name, value in d.items(): + if isinstance(value, list): + for v, a in value: + if isinstance(v, dict): + items.append((name, a, dict_to_items(v))) + else: + items.append((name, a, v)) + else: + v, a = value + items.append((name, a, dict_to_items(v))) + return items + # Public functions. def parse(stream_or_string, encoding=None, non_standard_newline=0, parser_cls=None): @@ -708,4 +745,17 @@ return (writer_cls or StreamWriter)(_writer) +def to_dict(node): + + "Return the 'node' converted to a dictionary representation." + + name, attr, items = node + return {name : (isinstance(items, list) and items_to_dict(items) or items, attr)} + +def to_node(d): + + "Return 'd' converted to a items-based representation." + + return dict_to_items(d)[0] + # vim: tabstop=4 expandtab shiftwidth=4