argmap.py 8.12 KB
Newer Older
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
35
36
try:
    from collections import OrderedDict
except ImportError:
37
    from .ordereddict import OrderedDict
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
38
39
40
from itertools import chain
from cStringIO import StringIO

41
42
ARGMAP_MAGIC = '[=ARGMAP=]'

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class arguments(object):
    __slots__ = ('args', 'kw')

    def __init__(self, *args, **kwargs):
        self.args = list(args)
        kw = OrderedDict()
        kwitems = kw.pop('kwitems', None)
        if kwitems is not None:
            kw.update(kwitems)
        kw.update(kwargs)
        self.kw = kw

    def __str__(self):
        return str(self.args) + '+' + str(self.kw)

    def __repr__(self):
        return repr(self.args) + '+' + repr(self.kw)

    def __getitem__(self, key):
        if (isinstance(key, int)
            or isinstance(key, long)
            or isinstance(key, slice)):
                return self.args[key]
        else:
            return self.kw[key]

    def __setitem__(self, key, value):
        if (isinstance(key, int)
            or isinstance(key, long)
            or isinstance(key, slice)):
                self.args[key] = value
        else:
            self.kw[key] = value

    def __delitem__(self, key):
        if (isinstance(key, int)
            or isinstance(key, long)
            or isinstance(key, slice)):
                del self.args[key]
        else:
                del self.kw[key]

    def iteritems(self):
        for item in self.args:
            yield None, item
        for k, v in self.kw:
            yield k, v

    def items(self):
        return list(self.iteritems())

    def iterkeys(self):
        return self.kw.iterkeys()

    def keys(self):
        return self.kw.keys()

    def itervalues(self):
        return chain(self.args, self.kw.itervalues())

    def values(self):
        return list(self.itervalues)

    def append(self, value):
        self.args.append(value)


110
def argmap_encode(obj, output):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    if obj is None:
        output('[=null]')
        return

    if isinstance(obj, basestring):
        if not obj:
            output('""')
        if isinstance(obj, unicode):
            obj = obj.encode('utf-8')
        output('"')
        start = 0
        while 1:
            end = obj.find(start) + 1
            if end < 0:
                break
            output(obj[start:end] + '"')
            start = end
        output(obj[start:])
        output('"')
        return

    if isinstance(obj, int) or isinstance(obj, long):
        output(str(obj))
        return

    if hasattr(obj, 'iteritems'):
        output('[')
        once = 1
        for k, v in obj.iteritems():
            if once:
                once = 0
            else:
                output(' ')
            if k is not None:
145
                argmap_encode(k)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
146
                output('=')
147
            argmap_encode(v)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
148
149
150
151
152
153
154
155
156
157
        output(']')
        
    if hasattr(obj, '__iter__'):
        output('[')
        once = 1
        for item in obj:
            if once:
                once = 0
            else:
                output(' ')
158
            argmap_encode(item)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
159
160
161
162
163
        output(']')

    m = "Unsupported type '%s'" % (type(obj))


164
def argmap_decode(inputf, s=None):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    if isinstance(inputf, str):
        inputf = StringIO(inputf).read

    if s is None:
        s = inputf(1)

    while 1:
        if not s.isspace():
            break
        s = inputf(1)

    item = ''
    if s == '"':
        s = inputf(1)
        while 1:
            if s == '"':
                s = inputf(1)
                if s != '"':
                    return item, s
            item += s
            s = inputf(1)
    elif s == '[':
187
        item, s = argmap_decode_args(inputf)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
188
189
190
191
192
193
194
195
196
        return item, s
    else:
        while 1:
            item += s
            s = inputf(1)
            if s in ' =]':
                return item, s


197
def argmap_decode_atom(inputf):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
198
199
200
201
202
203
204
    s = inputf(4)
    if s != 'null':
        m = "Invalid atom '%s'" % (s,)
        raise ValueError(m)
    return None, None


205
def argmap_decode_args(inputf):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
206
207
208
209
210
211
212
213
214
215
216
    append = args.append
    s = inputf(1)
    key = None

    while 1:
        if s is None:
            s = inputf(1)

        if s == ']':
            if key is not None:
                append((None, key))
217
	    args.append(ARGMAP_MAGIC)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
218
219
220
221
            return args, None

        if s == '=':
            if key is None:
222
                atom, s = argmap_decode_atom(inputf)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
223
224
                append((None, atom))
            else:
225
                value, s = argmap_decode(inputf)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
226
227
228
229
230
231
232
233
234
235
236
                append((key, value))
                key = None
        elif s == ' ':
            if key is not None:
                append((None, key))
                key = None
            s = inputf(1)
        elif s == '':
            m = "EOF while scanning for ']'"
            raise ValueError(m)
        else:
Giorgos Korfiatis's avatar
bug fix    
Giorgos Korfiatis committed
237
238
            if key is not None:
                append((None, key))
239
240
241
242
243
244
245
            key, s = argmap_decode(inputf, s=s)


def argmap_check(obj):
    if hasattr(obj, 'keys'):
        # this could cover both cases
        return ARGMAP_MAGIC in obj
246
    return hasattr(obj, '__len__') and len(obj) and obj[-1] == ARGMAP_MAGIC
247
248
249
250
251
252
253
254
255
256
257
258
259
260

def argmap_unzip_dict(argmap):
    if not hasattr(argmap, 'keys'):
        m = "argmap unzip dict: not a dict"
        raise TypeError(m)
    if ARGMAP_MAGIC not in argmap:
        m = "argmap unzip dict: magic not found"
        raise ValueError(m)
    args = argmap.pop(None, [])
    kw = OrderedDict(argmap)
    del kw[ARGMAP_MAGIC]
    return args, kw

def argmap_unzip_list(argmap):
261
    if not argmap or argmap[-1] != ARGMAP_MAGIC:
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
        m = "argmap unzip list: magic not found"
        raise ValueError(m)

    iter_argmap = iter(argmap)
    for magic in iter_argmap:
        break

    args = []
    append = args.append
    kw = OrderedDict()
    for k, v in iter_argmap:
        if k is None:
            append(v)
        else:
            kw[k] = v

    return args, kw

def argmap_unzip(argmap):
    if hasattr(argmap, 'keys'):
        return argmap_unzip_dict(argmap)
    elif hasattr(argmap, '__iter__'):
        return argmap_unzip_list(argmap)
    else:
        m = "argmap: cannot unzip type %s" % (type(argmap),)
        raise ValueError(m)

def argmap_zip_list(args, kw):
290
    return [(None, a) for a in args] + kw.items() + [ARGMAP_MAGIC]
291
292
293
294
295
296
297
298
299

def argmap_zip_dict(args, kw):
    argmap = OrderedDict()
    argmap.update(kw)
    argmap[ARGMAP_MAGIC] = ARGMAP_MAGIC
    argmap[None] = list(args) + (argmap[None] if None in argmap else [])
    return argmap

argmap_zip = argmap_zip_list
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
300

301
302
303
304
305
306
307
308
309
310
def argmap_list_to_dict(argmap):
    args, kw = argmap_unzip_list(argmap)
    kw[ARGMAP_MAGIC] = ARGMAP_MAGIC
    kw[None] = args
    return kw

def argmap_dict_to_list(argmap):
    args, kw = argmap_unzip_dict(argmap)
    return args + kw.items() + [ARGMAP_MAGIC]